{"text": "\n# Week 8 February 22-26: Gradient Methods, and start Resampling Techniques\n\n \n**Morten Hjorth-Jensen Email morten.hjorth-jensen@fys.uio.no**, Department of Physics and Center fo Computing in Science Education, University of Oslo, Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, East Lansing, Michigan, USA\n\nDate: **Feb 24, 2021**\n\nCopyright 1999-2021, Morten Hjorth-Jensen Email morten.hjorth-jensen@fys.uio.no. Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n## Overview of week 8, February 22-26\n**Topics.**\n\n* Start discussion of Resampling Techniques and statistics\n\n\n\n\n**Teaching Material, videos and written material.**\n\n* These lecture notes\n\n* [Video on the Conjugate Gradient methods](https://www.youtube.com/watch?v=eAYohMUpPMA&ab_channel=TomCarlone)\n\n* Recommended background literature, [Convex Optimization](https://web.stanford.edu/~boyd/cvxbook/) by Boyd and Vandenberghe. Their [lecture slides](https://web.stanford.edu/~boyd/cvxbook/bv_cvxslides.pdf) are very useful (warning, these are some 300 pages).\n\n\n\n\n\n\n## Brief reminder on Newton-Raphson's method\n\nLet us quickly remind ourselves how we derive the above method.\n\nPerhaps the most celebrated of all one-dimensional root-finding\nroutines is Newton's method, also called the Newton-Raphson\nmethod. This method requires the evaluation of both the\nfunction $f$ and its derivative $f'$ at arbitrary points. \nIf you can only calculate the derivative\nnumerically and/or your function is not of the smooth type, we\nnormally discourage the use of this method.\n\n## The equations\n\nThe Newton-Raphson formula consists geometrically of extending the\ntangent line at a current point until it crosses zero, then setting\nthe next guess to the abscissa of that zero-crossing. The mathematics\nbehind this method is rather simple. Employing a Taylor expansion for\n$x$ sufficiently close to the solution $s$, we have\n\n\n
\n\n$$\nf(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n \\label{eq:taylornr} \\tag{1}\n$$\n\nFor small enough values of the function and for well-behaved\nfunctions, the terms beyond linear are unimportant, hence we obtain\n\n$$\nf(x)+(s-x)f'(x)\\approx 0,\n$$\n\nyielding\n\n$$\ns\\approx x-\\frac{f(x)}{f'(x)}.\n$$\n\nHaving in mind an iterative procedure, it is natural to start iterating with\n\n$$\nx_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n$$\n\n## Simple geometric interpretation\n\nThe above is Newton-Raphson's method. It has a simple geometric\ninterpretation, namely $x_{n+1}$ is the point where the tangent from\n$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\nNewton-Raphson converges fast to the desired result. However, if we\nare far from a root, where the higher-order terms in the series are\nimportant, the Newton-Raphson formula can give grossly inaccurate\nresults. For instance, the initial guess for the root might be so far\nfrom the true root as to let the search interval include a local\nmaximum or minimum of the function. If an iteration places a trial\nguess near such a local extremum, so that the first derivative nearly\nvanishes, then Newton-Raphson may fail totally\n\n\n## Extending to more than one variable\n\nNewton's method can be generalized to systems of several non-linear equations\nand variables. Consider the case with two equations\n\n$$\n\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n f_2(x_1,x_2) &=0,\\end{array}\n$$\n\nwhich we Taylor expand to obtain\n\n$$\n\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n \\partial f_1/\\partial x_1+h_2\n \\partial f_1/\\partial x_2+\\dots\\\\\n 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1\n \\partial f_2/\\partial x_1+h_2\n \\partial f_2/\\partial x_2+\\dots\n \\end{array}.\n$$\n\nDefining the Jacobian matrix $\\hat{J}$ we have\n\n$$\n\\hat{J}=\\left( \\begin{array}{cc}\n \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n \\end{array} \\right),\n$$\n\nwe can rephrase Newton's method as\n\n$$\n\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n\\left(\\begin{array}{c} x_1^{n} \\\\ x_2^{n} \\end{array} \\right)+\n\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right),\n$$\n\nwhere we have defined\n\n$$\n\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n -{\\bf \\hat{J}}^{-1}\n \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n$$\n\nWe need thus to compute the inverse of the Jacobian matrix and it\nis to understand that difficulties may\narise in case $\\hat{J}$ is nearly singular.\n\nIt is rather straightforward to extend the above scheme to systems of\nmore than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. \n\n\n\n## Steepest descent\n\nThe basic idea of gradient descent is\nthat a function $F(\\mathbf{x})$, \n$\\mathbf{x} \\equiv (x_1,\\cdots,x_n)$, decreases fastest if one goes from $\\bf {x}$ in the\ndirection of the negative gradient $-\\nabla F(\\mathbf{x})$.\n\nIt can be shown that if\n\n$$\n\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n$$\n\nwith $\\gamma_k > 0$.\n\nFor $\\gamma_k$ small enough, then $F(\\mathbf{x}_{k+1}) \\leq\nF(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\nwe are always moving towards smaller function values, i.e a minimum.\n\n\n## More on Steepest descent\n\nThe previous observation is the basis of the method of steepest\ndescent, which is also referred to as just gradient descent (GD). One\nstarts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\ncomputes new approximations according to\n\n$$\n\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n$$\n\nThe parameter $\\gamma_k$ is often referred to as the step length or\nthe learning rate within the context of Machine Learning.\n\n\n## The ideal\n\nIdeally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\nminimum of the function $F$. In general we do not know if we are in a\nglobal or local minimum. In the special case when $F$ is a convex\nfunction, all local minima are also global minima, so in this case\ngradient descent can converge to the global solution. The advantage of\nthis scheme is that it is conceptually simple and straightforward to\nimplement. However the method in this form has some severe\nlimitations:\n\nIn machine learing we are often faced with non-convex high dimensional\ncost functions with many local minima. Since GD is deterministic we\nwill get stuck in a local minimum, if the method converges, unless we\nhave a very good intial guess. This also implies that the scheme is\nsensitive to the chosen initial condition.\n\nNote that the gradient is a function of $\\mathbf{x} =\n(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically.\n\n\n\n## The sensitiveness of the gradient descent\n\nThe gradient descent method \nis sensitive to the choice of learning rate $\\gamma_k$. This is due\nto the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\nF(\\mathbf{x}_k)$ for sufficiently small $\\gamma_k$. The problem is to\ndetermine an optimal learning rate. If the learning rate is chosen too\nsmall the method will take a long time to converge and if it is too\nlarge we can experience erratic behavior.\n\nMany of these shortcomings can be alleviated by introducing\nrandomness. One such method is that of Stochastic Gradient Descent\n(SGD), see below.\n\n\n\n## Convex functions\n\nIdeally we want our cost/loss function to be convex(concave).\n\nFirst we give the definition of a convex set: A set $C$ in\n$\\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and\nall $t \\in (0,1)$ , the point $(1 − t)x + ty$ also belongs to\nC. Geometrically this means that every point on the line segment\nconnecting $x$ and $y$ is in $C$ as discussed below.\n\nThe convex subsets of $\\mathbb{R}$ are the intervals of\n$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\nregular polygons (triangles, rectangles, pentagons, etc...).\n\n## Convex function\n\n**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$. If $\\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.\n\n## Conditions on convex functions\n\nIn the following we state first and second-order conditions which\nensures convexity of a function $f$. We write $D_f$ to denote the\ndomain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\ndetails and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n\n**First order condition.**\n\nSuppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\nall $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\nis a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\nfor all $x,y \\in D_f$. This condition means that for a convex function\nthe first order Taylor expansion (right hand side above) at any point\na global under estimator of the function. To convince yourself you can\nmake a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\nnote that it is always below the graph.\n\n\n\n**Second order condition.**\n\nAssume that $f$ is twice\ndifferentiable, i.e the Hessian matrix exists at each point in\n$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\nHessian is positive semi-definite for all $x\\in D_f$. For a\nsingle-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\neverywhere.\n\n\n\nThis condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.\n\n## More on convex functions\n\nThe next result is of great importance to us and the reason why we are\ngoing on about convex functions. In machine learning we frequently\nhave to minimize a loss/cost function in order to find the best\nparameters for the model we are considering. \n\nIdeally we want the\nglobal minimum (for high-dimensional models it is hard to know\nif we have local or global minimum). However, if the cost/loss function\nis convex the following result provides invaluable information:\n\n**Any minimum is global for convex functions.**\n\nConsider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\nis minimal, where $f$ is convex and differentiable. Then, any point\n$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n\n\n\nThis result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.\n\n## Some simple problems\n\n1. Show that $f(x)=x^2$ is convex for $x \\in \\mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \\in D_f$ and any $\\lambda \\in [0,1]$ $\\lambda f(x)+(1-\\lambda)f(y)-f(\\lambda x + (1-\\lambda) y ) \\geq 0$.\n\n2. Using the second order condition show that the following functions are convex on the specified domain.\n\n * $f(x) = e^x$ is convex for $x \\in \\mathbb{R}$.\n\n * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n\n\n3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \\in \\mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.\n\n4. A norm is any function that satisfy the following properties\n\n * $f(\\alpha x) = |\\alpha| f(x)$ for all $\\alpha \\in \\mathbb{R}$.\n\n * $f(x+y) \\leq f(x) + f(y)$\n\n * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n\n\nUsing the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this).\n\n\n## Standard steepest descent\n\n\nBefore we proceed, we would like to discuss the approach called the\n**standard Steepest descent**, which again leads to us having to be able\nto compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).\n\n[The success of the CG method](https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf)\nfor finding solutions of non-linear problems is based on the theory\nof conjugate gradients for linear systems of equations. It belongs to\nthe class of iterative methods for solving problems from linear\nalgebra of the type\n\n$$\n\\hat{A}\\hat{x} = \\hat{b}.\n$$\n\nIn the iterative process we end up with a problem like\n\n$$\n\\hat{r}= \\hat{b}-\\hat{A}\\hat{x},\n$$\n\nwhere $\\hat{r}$ is the so-called residual or error in the iterative process.\n\nWhen we have found the exact solution, $\\hat{r}=0$.\n\n## Gradient method\n\nThe residual is zero when we reach the minimum of the quadratic equation\n\n$$\nP(\\hat{x})=\\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T\\hat{b},\n$$\n\nwith the constraint that the matrix $\\hat{A}$ is positive definite and\nsymmetric. This defines also the Hessian and we want it to be positive definite. \n\n\n## Steepest descent method\n\nWe denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \nWe can assume without loss of generality that\n\n$$\n\\hat{x}_0=0,\n$$\n\nor consider the system\n\n$$\n\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n$$\n\ninstead.\n\n\n## Steepest descent method\nOne can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form\n\n$$\nf(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n$$\n\nThis suggests taking the first basis vector $\\hat{r}_1$ (see below for definition) \nto be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \nwhich equals\n\n$$\n\\hat{A}\\hat{x}_0-\\hat{b},\n$$\n\nand \n$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n\n\n\n## Final expressions\nWe can compute the residual iteratively as\n\n$$\n\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n$$\n\nwhich equals\n\n$$\n\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{r}_k),\n$$\n\nor\n\n$$\n(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{r}_k,\n$$\n\nwhich gives\n\n$$\n\\alpha_k = \\frac{\\hat{r}_k^T\\hat{r}_k}{\\hat{r}_k^T\\hat{A}\\hat{r}_k}\n$$\n\nleading to the iterative scheme\n\n$$\n\\hat{x}_{k+1}=\\hat{x}_k-\\alpha_k\\hat{r}_{k},\n$$\n\n## Code examples for steepest descent\n\n## Simple codes for steepest descent and conjugate gradient using a $2\\times 2$ matrix, in c++, Python code to come\n\n #include \n #include \n #include \n #include \n #include \"vectormatrixclass.h\"\n using namespace std;\n // Main function begins here\n int main(int argc, char * argv[]){\n int dim = 2;\n Vector x(dim),xsd(dim), b(dim),x0(dim);\n Matrix A(dim,dim);\n \n // Set our initial guess\n x0(0) = x0(1) = 0;\n // Set the matrix\n A(0,0) = 3; A(1,0) = 2; A(0,1) = 2; A(1,1) = 6;\n b(0) = 2; b(1) = -8;\n cout << \"The Matrix A that we are using: \" << endl;\n A.Print();\n cout << endl;\n xsd = SteepestDescent(A,b,x0);\n cout << \"The approximate solution using Steepest Descent is: \" << endl;\n xsd.Print();\n cout << endl;\n }\n\n\n## The routine for the steepest descent method\n\n Vector SteepestDescent(Matrix A, Vector b, Vector x0){\n int IterMax, i;\n int dim = x0.Dimension();\n const double tolerance = 1.0e-14;\n Vector x(dim),f(dim),z(dim);\n double c,alpha,d;\n IterMax = 30;\n x = x0;\n r = A*x-b;\n i = 0;\n while (i <= IterMax){\n z = A*r;\n c = dot(r,r);\n alpha = c/dot(r,z);\n x = x - alpha*r;\n r = A*x-b;\n if(sqrt(dot(r,r)) < tolerance) break;\n i++;\n }\n return x;\n }\n\n\n## Steepest descent example\n\n\n```python\n%matplotlib inline\n\nimport numpy as np\nimport numpy.linalg as la\n\nimport scipy.optimize as sopt\n\nimport matplotlib.pyplot as pt\nfrom mpl_toolkits.mplot3d import axes3d\n\ndef f(x):\n return 0.5*x[0]**2 + 2.5*x[1]**2\n\ndef df(x):\n return np.array([x[0], 5*x[1]])\n\nfig = pt.figure()\nax = fig.gca(projection=\"3d\")\n\nxmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]\nfmesh = f(np.array([xmesh, ymesh]))\nax.plot_surface(xmesh, ymesh, fmesh)\n```\n\nAnd then as countor plot\n\n\n```python\npt.axis(\"equal\")\npt.contour(xmesh, ymesh, fmesh)\nguesses = [np.array([2, 2./5])]\n```\n\nFind guesses\n\n\n```python\nx = guesses[-1]\ns = -df(x)\n```\n\nRun it!\n\n\n```python\ndef f1d(alpha):\n return f(x + alpha*s)\n\nalpha_opt = sopt.golden(f1d)\nnext_guess = x + alpha_opt * s\nguesses.append(next_guess)\nprint(next_guess)\n```\n\n [ 1.33333333 -0.26666667]\n\n\nWhat happened?\n\n\n```python\npt.axis(\"equal\")\npt.contour(xmesh, ymesh, fmesh, 50)\nit_array = np.array(guesses)\npt.plot(it_array.T[0], it_array.T[1], \"x-\")\n```\n\n## Conjugate gradient method\nIn the CG method we define so-called conjugate directions and two vectors \n$\\hat{s}$ and $\\hat{t}$\nare said to be\nconjugate if\n\n$$\n\\hat{s}^T\\hat{A}\\hat{t}= 0.\n$$\n\nThe philosophy of the CG method is to perform searches in various conjugate directions\nof our vectors $\\hat{x}_i$ obeying the above criterion, namely\n\n$$\n\\hat{x}_i^T\\hat{A}\\hat{x}_j= 0.\n$$\n\nTwo vectors are conjugate if they are orthogonal with respect to \nthis inner product. Being conjugate is a symmetric relation: if $\\hat{s}$ is conjugate to $\\hat{t}$, then $\\hat{t}$ is conjugate to $\\hat{s}$.\n\n\n\n## Conjugate gradient method\nAn example is given by the eigenvectors of the matrix\n\n$$\n\\hat{v}_i^T\\hat{A}\\hat{v}_j= \\lambda\\hat{v}_i^T\\hat{v}_j,\n$$\n\nwhich is zero unless $i=j$.\n\n\n\n\n## Conjugate gradient method\nAssume now that we have a symmetric positive-definite matrix $\\hat{A}$ of size\n$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector\n\n$$\n\\hat{x}_{i+1}=\\hat{x}_{i}+\\alpha_i\\hat{p}_{i}.\n$$\n\nWe assume that $\\hat{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \nThen the $\\hat{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n$ \\hat{A}\\hat{x} = \\hat{b}$ in this basis, namely\n\n$$\n\\hat{x} = \\sum^{n}_{i=1} \\alpha_i \\hat{p}_i.\n$$\n\n## Conjugate gradient method\nThe coefficients are given by\n\n$$\n\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n$$\n\nMultiplying with $\\hat{p}_k^T$ from the left gives\n\n$$\n\\hat{p}_k^T \\hat{A}\\hat{x} = \\sum^{n}_{i=1} \\alpha_i\\hat{p}_k^T \\hat{A}\\hat{p}_i= \\hat{p}_k^T \\hat{b},\n$$\n\nand we can define the coefficients $\\alpha_k$ as\n\n$$\n\\alpha_k = \\frac{\\hat{p}_k^T \\hat{b}}{\\hat{p}_k^T \\hat{A} \\hat{p}_k}\n$$\n\n## Conjugate gradient method and iterations\n\nIf we choose the conjugate vectors $\\hat{p}_k$ carefully, \nthen we may not need all of them to obtain a good approximation to the solution \n$\\hat{x}$. \nWe want to regard the conjugate gradient method as an iterative method. \nThis will us to solve systems where $n$ is so large that the direct \nmethod would take too much time.\n\nWe denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \nWe can assume without loss of generality that\n\n$$\n\\hat{x}_0=0,\n$$\n\nor consider the system\n\n$$\n\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n$$\n\ninstead.\n\n\n\n\n## Conjugate gradient method\nOne can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form\n\n$$\nf(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n$$\n\nThis suggests taking the first basis vector $\\hat{p}_1$ \nto be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \nwhich equals\n\n$$\n\\hat{A}\\hat{x}_0-\\hat{b},\n$$\n\nand \n$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\nThe other vectors in the basis will be conjugate to the gradient, \nhence the name conjugate gradient method.\n\n\n\n\n## Conjugate gradient method\nLet $\\hat{r}_k$ be the residual at the $k$-th step:\n\n$$\n\\hat{r}_k=\\hat{b}-\\hat{A}\\hat{x}_k.\n$$\n\nNote that $\\hat{r}_k$ is the negative gradient of $f$ at \n$\\hat{x}=\\hat{x}_k$, \nso the gradient descent method would be to move in the direction $\\hat{r}_k$. \nHere, we insist that the directions $\\hat{p}_k$ are conjugate to each other, \nso we take the direction closest to the gradient $\\hat{r}_k$ \nunder the conjugacy constraint. \nThis gives the following expression\n\n$$\n\\hat{p}_{k+1}=\\hat{r}_k-\\frac{\\hat{p}_k^T \\hat{A}\\hat{r}_k}{\\hat{p}_k^T\\hat{A}\\hat{p}_k} \\hat{p}_k.\n$$\n\n## Conjugate gradient method\nWe can also compute the residual iteratively as\n\n$$\n\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n$$\n\nwhich equals\n\n$$\n\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{p}_k),\n$$\n\nor\n\n$$\n(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{p}_k,\n$$\n\nwhich gives\n\n$$\n\\hat{r}_{k+1}=\\hat{r}_k-\\hat{A}\\hat{p}_{k},\n$$\n\n## Simple implementation of the Conjugate gradient algorithm\n\n Vector ConjugateGradient(Matrix A, Vector b, Vector x0){\n int dim = x0.Dimension();\n const double tolerance = 1.0e-14;\n Vector x(dim),r(dim),v(dim),z(dim);\n double c,t,d;\n \n x = x0;\n r = b - A*x;\n v = r;\n c = dot(r,r);\n int i = 0; IterMax = dim;\n while(i <= IterMax){\n z = A*v;\n t = c/dot(v,z);\n x = x + t*v;\n r = r - t*z;\n d = dot(r,r);\n if(sqrt(d) < tolerance)\n break;\n v = r + (d/c)*v;\n c = d; i++;\n }\n return x;\n } \n\n\n## Broyden–Fletcher–Goldfarb–Shanno algorithm\nThe optimization problem is to minimize $f(\\mathbf {x} )$ where $\\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\\mathbf {x}$ can take.\n\nThe algorithm begins at an initial estimate for the optimal value $\\mathbf {x}_{0}$ and proceeds iteratively to get a better estimate at each stage.\n\nThe search direction $p_k$ at stage $k$ is given by the solution of the analogue of the Newton equation\n\n$$\nB_{k}\\mathbf {p} _{k}=-\\nabla f(\\mathbf {x}_{k}),\n$$\n\nwhere $B_{k}$ is an approximation to the Hessian matrix, which is\nupdated iteratively at each stage, and $\\nabla f(\\mathbf {x} _{k})$\nis the gradient of the function\nevaluated at $x_k$. \nA line search in the direction $p_k$ is then used to\nfind the next point $x_{k+1}$ by minimising\n\n$$\nf(\\mathbf {x}_{k}+\\alpha \\mathbf {p}_{k}),\n$$\n\nover the scalar $\\alpha > 0$.\n\n\n\n\n## Stochastic Gradient Descent\n\nStochastic gradient descent (SGD) and variants thereof address some of\nthe shortcomings of the Gradient descent method discussed above.\n\nThe underlying idea of SGD comes from the observation that a given \nfunction, which we want to minimize, can almost always be written as a\nsum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$,\n\n$$\nC(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n\\mathbf{\\beta}).\n$$\n\n## Computation of gradients\n\nThis in turn means that the gradient can be\ncomputed as a sum over $i$-gradients\n\n$$\n\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n\\mathbf{\\beta}).\n$$\n\nStochasticity/randomness is introduced by only taking the\ngradient on a subset of the data called minibatches. If there are $n$\ndata points and the size of each minibatch is $M$, there will be $n/M$\nminibatches. We denote these minibatches by $B_k$ where\n$k=1,\\cdots,n/M$.\n\n## SGD example\nAs an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \nand we choose to have $M=5$ minibathces,\nthen each minibatch contains two data points. In particular we have\n$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\nhave only a single batch with all data points and on the other extreme,\nyou may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n$B_k = \\mathbf{x}_k$.\n\nThe idea is now to approximate the gradient by replacing the sum over\nall data points with a sum over the data points in one the minibatches\npicked at random in each gradient descent step\n\n$$\n\\nabla_{\\beta}\nC(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\nc_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n$$\n\n## The gradient step\n\nThus a gradient descent step now looks like\n\n$$\n\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n\\mathbf{\\beta})\n$$\n\nwhere $k$ is picked at random with equal\nprobability from $[1,n/M]$. An iteration over the number of\nminibathces (n/M) is commonly referred to as an epoch. Thus it is\ntypical to choose a number of epochs and for each epoch iterate over\nthe number of minibatches, as exemplified in the code below.\n\n## Simple example code\n\n\n```python\nimport numpy as np \n\nn = 100 #100 datapoints \nM = 5 #size of each minibatch\nm = int(n/M) #number of minibatches\nn_epochs = 10 #number of epochs\n\nj = 0\nfor epoch in range(1,n_epochs+1):\n for i in range(m):\n k = np.random.randint(m) #Pick the k-th minibatch at random\n #Compute the gradient using the data in minibatch Bk\n #Compute new suggestion for \n j += 1\n```\n\nTaking the gradient only on a subset of the data has two important\nbenefits. First, it introduces randomness which decreases the chance\nthat our opmization scheme gets stuck in a local minima. Second, if\nthe size of the minibatches are small relative to the number of\ndatapoints ($M < n$), the computation of the gradient is much\ncheaper since we sum over the datapoints in the $k-th$ minibatch and not\nall $n$ datapoints.\n\n## When do we stop?\n\nA natural question is when do we stop the search for a new minimum?\nOne possibility is to compute the full gradient after a given number\nof epochs and check if the norm of the gradient is smaller than some\nthreshold and stop if true. However, the condition that the gradient\nis zero is valid also for local minima, so this would only tell us\nthat we are close to a local/global minimum. However, we could also\nevaluate the cost function at this point, store the result and\ncontinue the search. If the test kicks in at a later stage we can\ncompare the values of the cost function and keep the $\\beta$ that\ngave the lowest value.\n\n## Slightly different approach\n\nAnother approach is to let the step length $\\gamma_j$ depend on the\nnumber of epochs in such a way that it becomes very small after a\nreasonable time such that we do not move at all.\n\nAs an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n\nIn this way we can fix the number of epochs, compute $\\beta$ and\nevaluate the cost function at the end. Repeating the computation will\ngive a different result since the scheme is random by design. Then we\npick the final $\\beta$ that gives the lowest value of the cost\nfunction.\n\n\n```python\nimport numpy as np \n\ndef step_length(t,t0,t1):\n return t0/(t+t1)\n\nn = 100 #100 datapoints \nM = 5 #size of each minibatch\nm = int(n/M) #number of minibatches\nn_epochs = 500 #number of epochs\nt0 = 1.0\nt1 = 10\n\ngamma_j = t0/t1\nj = 0\nfor epoch in range(1,n_epochs+1):\n for i in range(m):\n k = np.random.randint(m) #Pick the k-th minibatch at random\n #Compute the gradient using the data in minibatch Bk\n #Compute new suggestion for beta\n t = epoch*m+i\n gamma_j = step_length(t,t0,t1)\n j += 1\n\nprint(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))\n```\n\n## Program for stochastic gradient\n\n\n```python\n# Importing various packages\nfrom math import exp, sqrt\nfrom random import random, seed\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import SGDRegressor\n\nx = 2*np.random.rand(100,1)\ny = 4+3*x+np.random.randn(100,1)\n\nxb = np.c_[np.ones((100,1)), x]\ntheta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\nprint(\"Own inversion\")\nprint(theta_linreg)\nsgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\nsgdreg.fit(x,y.ravel())\nprint(\"sgdreg from scikit\")\nprint(sgdreg.intercept_, sgdreg.coef_)\n\n\ntheta = np.random.randn(2,1)\n\neta = 0.1\nNiterations = 1000\nm = 100\n\nfor iter in range(Niterations):\n gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)\n theta -= eta*gradients\nprint(\"theta frm own gd\")\nprint(theta)\n\nxnew = np.array([[0],[2]])\nxbnew = np.c_[np.ones((2,1)), xnew]\nypredict = xbnew.dot(theta)\nypredict2 = xbnew.dot(theta_linreg)\n\n\nn_epochs = 50\nt0, t1 = 5, 50\nm = 100\ndef learning_schedule(t):\n return t0/(t+t1)\n\ntheta = np.random.randn(2,1)\n\nfor epoch in range(n_epochs):\n for i in range(m):\n random_index = np.random.randint(m)\n xi = xb[random_index:random_index+1]\n yi = y[random_index:random_index+1]\n gradients = 2 * xi.T.dot(xi.dot(theta)-yi)\n eta = learning_schedule(epoch*m+i)\n theta = theta - eta*gradients\nprint(\"theta from own sdg\")\nprint(theta)\n\n\nplt.plot(xnew, ypredict, \"r-\")\nplt.plot(xnew, ypredict2, \"b-\")\nplt.plot(x, y ,'ro')\nplt.axis([0,2.0,0, 15.0])\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\nplt.title(r'Random numbers ')\nplt.show()\n```\n\n## Using gradient descent methods, limitations\n\n* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n\n* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n\n* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the energy function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n\n* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n\n* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n\n* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.\n\n## Codes from numerical recipes\nYou can however use codes we have adapted from the text [Numerical Recipes in C++](http://www.nr.com/), see chapter 10.7. \nHere we present a program, which you also can find at the webpage of the course we use the functions **dfpmin** and **lnsrch**. This is a variant of the Broyden et al algorithm discussed in the previous slide.\n\n* The program uses the harmonic oscillator in one dimensions as example.\n\n* The program does not use armadillo to handle vectors and matrices, but employs rather my own vector-matrix class. These auxiliary functions, and the main program *model.cpp* can all be found under the [program link here](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/pub/cg/programs/c%2B%2B).\n\nBelow we show only excerpts from the main program. For the full program, see the above link.\n\n\n\n\n## Finding the minimum of the harmonic oscillator model in one dimension\n\n // Main function begins here\n int main()\n {\n int n, iter;\n double gtol, fret;\n double alpha;\n n = 1;\n // reserve space in memory for vectors containing the variational\n // parameters\n Vector g(n), p(n);\n cout << \"Read in guess for alpha\" << endl;\n cin >> alpha;\n gtol = 1.0e-5;\n // now call dfmin and compute the minimum\n p(0) = alpha;\n dfpmin(p, n, gtol, &iter, &fret, Efunction, dEfunction);\n cout << \"Value of energy minimum = \" << fret << endl;\n cout << \"Number of iterations = \" << iter << endl;\n cout << \"Value of alpha at minimum = \" << p(0) << endl;\n return 0;\n } // end of main program\n \n\n\n## Functions to observe\nThe functions **Efunction** and **dEfunction** compute the expectation value of the energy and its derivative.\nThey use the the quasi-Newton method of [Broyden, Fletcher, Goldfarb, and Shanno (BFGS)](https://www.springer.com/it/book/9780387303031)\nIt uses the first derivatives only. The BFGS algorithm has proven good performance even for non-smooth optimizations. \nThese functions need to be changed when you want to your own derivatives.\n\n // this function defines the expectation value of the local energy\n double Efunction(Vector &x)\n {\n double value = x(0)*x(0)*0.5+1.0/(8*x(0)*x(0));\n return value;\n } // end of function to evaluate\n \n // this function defines the derivative of the energy \n void dEfunction(Vector &x, Vector &g)\n {\n g(0) = x(0)-1.0/(4*x(0)*x(0)*x(0));\n } // end of function to evaluate\n\n\nYou need to change these functions in order to compute the local energy for your system. I used 1000\ncycles per call to get a new value of $\\langle E_L[\\alpha]\\rangle$.\nWhen I compute the local energy I also compute its derivative.\nAfter roughly 10-20 iterations I got a converged result in terms of $\\alpha$.\n\n\n\n\n\n\n\n## Resampling methods\nResampling methods are an indispensable tool in modern\nstatistics. They involve repeatedly drawing samples from a training\nset and refitting a model of interest on each sample in order to\nobtain additional information about the fitted model. For example, in\norder to estimate the variability of a linear regression fit, we can\nrepeatedly draw different samples from the training data, fit a linear\nregression to each new sample, and then examine the extent to which\nthe resulting fits differ. Such an approach may allow us to obtain\ninformation that would not be available from fitting the model only\nonce using the original training sample.\n\n\n\n## Resampling approaches can be computationally expensive\nResampling approaches can be computationally expensive, because they\ninvolve fitting the same statistical method multiple times using\ndifferent subsets of the training data. However, due to recent\nadvances in computing power, the computational requirements of\nresampling methods generally are not prohibitive. In this chapter, we\ndiscuss two of the most commonly used resampling methods,\ncross-validation and the bootstrap. Both methods are important tools\nin the practical application of many statistical learning\nprocedures. For example, cross-validation can be used to estimate the\ntest error associated with a given statistical learning method in\norder to evaluate its performance, or to select the appropriate level\nof flexibility. The process of evaluating a model’s performance is\nknown as model assessment, whereas the process of selecting the proper\nlevel of flexibility for a model is known as model selection. The\nbootstrap is widely used.\n\n\n\n## Why resampling methods ?\n**Statistical analysis.**\n\n * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n\n * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n\n * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n\n \n\n## Statistical analysis\n * As in other experiments, many numerical experiments have two classes of errors:\n\n * Statistical errors\n\n * Systematical errors\n\n\n * Statistical errors can be estimated using standard tools from statistics\n\n * Systematical errors are method specific and must be treated differently from case to case.\n\n \n\n## Statistics\nThe *probability distribution function (PDF)* is a function\n$p(x)$ on the domain which, in the discrete case, gives us the\nprobability or relative frequency with which these values of $X$ occur:\n\n$$\np(x) = \\mathrm{prob}(X=x)\n$$\n\nIn the continuous case, the PDF does not directly depict the\nactual probability. Instead we define the probability for the\nstochastic variable to assume any value on an infinitesimal interval\naround $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\nthe *density* of the probability rather than the probability\nitself. The probability for a stochastic variable to assume any value\non a non-infinitesimal interval $[a,\\,b]$ is then just the integral:\n\n$$\n\\mathrm{prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx\n$$\n\nQualitatively speaking, a stochastic variable represents the values of\nnumbers chosen as if by chance from some specified PDF so that the\nselection of a large set of these numbers reproduces this PDF.\n\n\n\n\n## Statistics, moments\nA particularly useful class of special expectation values are the\n*moments*. The $n$-th moment of the PDF $p$ is defined as\nfollows:\n\n$$\n\\langle x^n\\rangle \\equiv \\int\\! x^n p(x)\\,dx\n$$\n\nThe zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\nand often denoted by the letter $\\mu$:\n\n$$\n\\langle x\\rangle = \\mu \\equiv \\int\\! x p(x)\\,dx\n$$\n\n## Statistics, central moments\nA special version of the moments is the set of *central moments*,\nthe n-th central moment defined as:\n\n$$\n\\langle (x-\\langle x \\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n$$\n\nThe zero-th and first central moments are both trivial, equal $1$ and\n$0$, respectively. But the second central moment, known as the\n*variance* of $p$, is of particular interest. For the stochastic\nvariable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{var}(X)$:\n\n\n
\n\n$$\n\\begin{equation}\n\\sigma^2_X\\ \\ =\\ \\ \\mathrm{var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n\\int\\! (x-\\langle x\\rangle)^2 p(x)\\,dx\n\\label{_auto1} \\tag{2}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\int\\! \\left(x^2 - 2 x \\langle x\\rangle^{2} +\n \\langle x\\rangle^2\\right)p(x)\\,dx\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\langle x^2\\rangle - \\langle x\\rangle^2\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nThe square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square)\nvalue of the deviation of the PDF from its mean value, interpreted\nqualitatively as the *spread* of $p$ around its mean.\n\n\n\n## Statistics, covariance\nAnother important quantity is the so called covariance, a variant of\nthe above defined variance. Consider again the set $\\{X_i\\}$ of $n$\nstochastic variables (not necessarily uncorrelated) with the\nmultivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\nof the stochastic variables, $X_i$ and $X_j$, is defined as follows:\n\n$$\n\\mathrm{cov}(X_i,\\,X_j) \\equiv \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n\\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\n\\int\\!\\cdots\\!\\int\\!(x_i-\\langle x_i \\rangle)(x_j-\\langle x_j \\rangle)\\,\nP(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n\\label{eq:def_covariance} \\tag{6}\n\\end{equation}\n$$\n\nwith\n\n$$\n\\langle x_i\\rangle =\n\\int\\!\\cdots\\!\\int\\!x_i\\,P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n$$\n\n## Statistics, more covariance\nIf we consider the above covariance as a matrix $C_{ij}=\\mathrm{cov}(X_i,\\,X_j)$, then the diagonal elements are just the familiar\nvariances, $C_{ii} = \\mathrm{cov}(X_i,\\,X_i) = \\mathrm{var}(X_i)$. It turns out that\nall the off-diagonal elements are zero if the stochastic variables are\nuncorrelated. This is easy to show, keeping in mind the linearity of\nthe expectation value. Consider the stochastic variables $X_i$ and\n$X_j$, ($i\\neq j$):\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{cov}(X_i,\\,X_j) = \\langle(x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n\\label{_auto5} \\tag{7}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \n\\label{_auto6} \\tag{8}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j\\rangle +\n\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\n\\label{_auto7} \\tag{9}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n\\langle x_i\\rangle\\langle x_j\\rangle\n\\label{_auto8} \\tag{10}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n\\label{_auto9} \\tag{11}\n\\end{equation}\n$$\n\n## Statistics, independent variables\nIf $X_i$ and $X_j$ are independent, we get \n$\\langle x_i x_j\\rangle =\\langle x_i\\rangle\\langle x_j\\rangle$, resulting in $\\mathrm{cov}(X_i, X_j) = 0\\ \\ (i\\neq j)$.\n\nAlso useful for us is the covariance of linear combinations of\nstochastic variables. Let $\\{X_i\\}$ and $\\{Y_i\\}$ be two sets of\nstochastic variables. Let also $\\{a_i\\}$ and $\\{b_i\\}$ be two sets of\nscalars. Consider the linear combination:\n\n$$\nU = \\sum_i a_i X_i \\qquad V = \\sum_j b_j Y_j\n$$\n\nBy the linearity of the expectation value\n\n$$\n\\mathrm{cov}(U, V) = \\sum_{i,j}a_i b_j \\mathrm{cov}(X_i, Y_j)\n$$\n\n## Statistics, more variance\nNow, since the variance is just $\\mathrm{var}(X_i) = \\mathrm{cov}(X_i, X_i)$, we get\nthe variance of the linear combination $U = \\sum_i a_i X_i$:\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{var}(U) = \\sum_{i,j}a_i a_j \\mathrm{cov}(X_i, X_j)\n\\label{eq:variance_linear_combination} \\tag{12}\n\\end{equation}\n$$\n\nAnd in the special case when the stochastic variables are\nuncorrelated, the off-diagonal elements of the covariance are as we\nknow zero, resulting in:\n\n6\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\mathrm{var}(\\sum_i a_i X_i) = \\sum_i a_i^2 \\mathrm{var}(X_i)\n$$\n\nwhich will become very useful in our study of the error in the mean\nvalue of a set of measurements.\n\n\n\n## Statistics and stochastic processes\nA *stochastic process* is a process that produces sequentially a\nchain of values:\n\n$$\n\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n$$\n\nWe will call these\nvalues our *measurements* and the entire set as our measured\n*sample*. The action of measuring all the elements of a sample\nwe will call a stochastic *experiment* since, operationally,\nthey are often associated with results of empirical observation of\nsome physical or mathematical phenomena; precisely an experiment. We\nassume that these values are distributed according to some \nPDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\nstochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\ntrying to determine the full distribution $p$ we are often only\ninterested in finding the few lowest moments, like the mean\n$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n\n\n\n\n\n## Statistics and sample variables\nIn practical situations a sample is always of finite size. Let that\nsize be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows:\n\n$$\n\\bar{x}_n \\equiv \\frac{1}{n}\\sum_{k=1}^n x_k\n$$\n\nThe *sample variance* is:\n\n$$\n\\mathrm{var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar{x}_n)^2\n$$\n\nits square root being the *standard deviation of the sample*. The\n*sample covariance* is:\n\n$$\n\\mathrm{cov}(x)\\equiv\\frac{1}{n}\\sum_{kl}(x_k - \\bar{x}_n)(x_l - \\bar{x}_n)\n$$\n\n## Statistics, sample variance and covariance\nNote that the sample variance is the sample covariance without the\ncross terms. In a similar manner as the covariance in Eq. ([6](#eq:def_covariance)) is a measure of the correlation between\ntwo stochastic variables, the above defined sample covariance is a\nmeasure of the sequential correlation between succeeding measurements\nof a sample.\n\nThese quantities, being known experimental values, differ\nsignificantly from and must not be confused with the similarly named\nquantities for stochastic variables, mean $\\mu_X$, variance $\\mathrm{var}(X)$\nand covariance $\\mathrm{cov}(X,Y)$.\n\n\n\n## Statistics, law of large numbers\nThe law of large numbers\nstates that as the size of our sample grows to infinity, the sample\nmean approaches the true mean $\\mu_X^{\\phantom X}$ of the chosen PDF:\n\n$$\n\\lim_{n\\to\\infty}\\bar{x}_n = \\mu_X^{\\phantom X}\n$$\n\nThe sample mean $\\bar{x}_n$ works therefore as an estimate of the true\nmean $\\mu_X^{\\phantom X}$.\n\nWhat we need to find out is how good an approximation $\\bar{x}_n$ is to\n$\\mu_X^{\\phantom X}$. In any stochastic measurement, an estimated\nmean is of no use to us without a measure of its error. A quantity\nthat tells us how well we can reproduce it in another experiment. We\nare therefore interested in the PDF of the sample mean itself. Its\nstandard deviation will be a measure of the spread of sample means,\nand we will simply call it the *error* of the sample mean, or\njust sample error, and denote it by $\\mathrm{err}_X^{\\phantom X}$. In\npractice, we will only be able to produce an *estimate* of the\nsample error since the exact value would require the knowledge of the\ntrue PDFs behind, which we usually do not have.\n\n\n\n\n## Statistics, more on sample error\nLet us first take a look at what happens to the sample error as the\nsize of the sample grows. In a sample, each of the measurements $x_i$\ncan be associated with its own stochastic variable $X_i$. The\nstochastic variable $\\overline X_n$ for the sample mean $\\bar{x}_n$ is\nthen just a linear combination, already familiar to us:\n\n$$\n\\overline X_n = \\frac{1}{n}\\sum_{i=1}^n X_i\n$$\n\nAll the coefficients are just equal $1/n$. The PDF of $\\overline X_n$,\ndenoted by $p_{\\overline X_n}(x)$ is the desired PDF of the sample\nmeans.\n\n\n\n## Statistics\nThe probability density of obtaining a sample mean $\\bar x_n$\nis the product of probabilities of obtaining arbitrary values $x_1,\nx_2,\\dots,x_n$ with the constraint that the mean of the set $\\{x_i\\}$\nis $\\bar x_n$:\n\n$$\np_{\\overline X_n}(x) = \\int p_X^{\\phantom X}(x_1)\\cdots\n\\int p_X^{\\phantom X}(x_n)\\ \n\\delta\\!\\left(x - \\frac{x_1+x_2+\\dots+x_n}{n}\\right)dx_n \\cdots dx_1\n$$\n\nAnd in particular we are interested in its variance $\\mathrm{var}(\\overline X_n)$.\n\n\n\n\n\n## Statistics, central limit theorem\nIt is generally not possible to express $p_{\\overline X_n}(x)$ in a\nclosed form given an arbitrary PDF $p_X^{\\phantom X}$ and a number\n$n$. But for the limit $n\\to\\infty$ it is possible to make an\napproximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity,\n$p_{\\overline X_n}(x)$ approaches a Gaussian distribution whose mean\nand variance equal the true mean and variance, $\\mu_{X}^{\\phantom X}$\nand $\\sigma_{X}^{2}$, respectively:\n\n\n
\n\n$$\n\\begin{equation}\n\\lim_{n\\to\\infty} p_{\\overline X_n}(x) =\n\\left(\\frac{n}{2\\pi\\mathrm{var}(X)}\\right)^{1/2}\ne^{-\\frac{n(x-\\bar x_n)^2}{2\\mathrm{var}(X)}}\n\\label{eq:central_limit_gaussian} \\tag{13}\n\\end{equation}\n$$\n\n## Statistics, more technicalities\nThe desired variance\n$\\mathrm{var}(\\overline X_n)$, i.e. the sample error squared\n$\\mathrm{err}_X^2$, is given by:\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{err}_X^2 = \\mathrm{var}(\\overline X_n) = \\frac{1}{n^2}\n\\sum_{ij} \\mathrm{cov}(X_i, X_j)\n\\label{eq:error_exact} \\tag{14}\n\\end{equation}\n$$\n\nWe see now that in order to calculate the exact error of the sample\nwith the above expression, we would need the true means\n$\\mu_{X_i}^{\\phantom X}$ of the stochastic variables $X_i$. To\ncalculate these requires that we know the true multivariate PDF of all\nthe $X_i$. But this PDF is unknown to us, we have only got the measurements of\none sample. The best we can do is to let the sample itself be an\nestimate of the PDF of each of the $X_i$, estimating all properties of\n$X_i$ through the measurements of the sample.\n\n\n\n\n## Statistics\nOur estimate of $\\mu_{X_i}^{\\phantom X}$ is then the sample mean $\\bar x$\nitself, in accordance with the the central limit theorem:\n\n$$\n\\mu_{X_i}^{\\phantom X} = \\langle x_i\\rangle \\approx \\frac{1}{n}\\sum_{k=1}^n x_k = \\bar x\n$$\n\nUsing $\\bar x$ in place of $\\mu_{X_i}^{\\phantom X}$ we can give an\n*estimate* of the covariance in Eq. ([14](#eq:error_exact))\n\n$$\n\\mathrm{cov}(X_i, X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n\\approx\\langle (x_i - \\bar x)(x_j - \\bar{x})\\rangle,\n$$\n\nresulting in\n\n$$\n\\frac{1}{n} \\sum_{l}^n \\left(\\frac{1}{n}\\sum_{k}^n (x_k -\\bar x_n)(x_l - \\bar x_n)\\right)=\\frac{1}{n}\\frac{1}{n} \\sum_{kl} (x_k -\\bar x_n)(x_l - \\bar x_n)=\\frac{1}{n}\\mathrm{cov}(x)\n$$\n\n## Statistics and sample variance\nBy the same procedure we can use the sample variance as an\nestimate of the variance of any of the stochastic variables $X_i$\n\n$$\n\\mathrm{var}(X_i)=\\langle x_i - \\langle x_i\\rangle\\rangle \\approx \\langle x_i - \\bar x_n\\rangle\\nonumber,\n$$\n\nwhich is approximated as\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{var}(X_i)\\approx \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar x_n)=\\mathrm{var}(x)\n\\label{eq:var_estimate_i_think} \\tag{15}\n\\end{equation}\n$$\n\nNow we can calculate an estimate of the error\n$\\mathrm{err}_X^{\\phantom X}$ of the sample mean $\\bar x_n$:\n\n$$\n\\mathrm{err}_X^2\n=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) \\nonumber\n$$\n\n$$\n\\approx\\frac{1}{n^2}\\sum_{ij}\\frac{1}{n}\\mathrm{cov}(x) =\\frac{1}{n^2}n^2\\frac{1}{n}\\mathrm{cov}(x)\\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\frac{1}{n}\\mathrm{cov}(x)\n\\label{eq:error_estimate} \\tag{16}\n\\end{equation}\n$$\n\nwhich is nothing but the sample covariance divided by the number of\nmeasurements in the sample.\n\n\n\n## Statistics, uncorrelated results\n\nIn the special case that the measurements of the sample are\nuncorrelated (equivalently the stochastic variables $X_i$ are\nuncorrelated) we have that the off-diagonal elements of the covariance\nare zero. This gives the following estimate of the sample error:\n\n$$\n\\mathrm{err}_X^2=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) =\n\\frac{1}{n^2} \\sum_i \\mathrm{var}(X_i),\n$$\n\nresulting in\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{err}_X^2\\approx \\frac{1}{n^2} \\sum_i \\mathrm{var}(x)= \\frac{1}{n}\\mathrm{var}(x)\n\\label{eq:error_estimate_uncorrel} \\tag{17}\n\\end{equation}\n$$\n\nwhere in the second step we have used Eq. ([15](#eq:var_estimate_i_think)).\nThe error of the sample is then just its standard deviation divided by\nthe square root of the number of measurements the sample contains.\nThis is a very useful formula which is easy to compute. It acts as a\nfirst approximation to the error, but in numerical experiments, we\ncannot overlook the always present correlations.\n\n\n\n## Statistics, computations\nFor computational purposes one usually splits up the estimate of\n$\\mathrm{err}_X^2$, given by Eq. ([16](#eq:error_estimate)), into two\nparts\n\n$$\n\\mathrm{err}_X^2 = \\frac{1}{n}\\mathrm{var}(x) + \\frac{1}{n}(\\mathrm{cov}(x)-\\mathrm{var}(x)),\n$$\n\nwhich equals\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{1}{n^2}\\sum_{k=1}^n (x_k - \\bar x_n)^2 +\\frac{2}{n^2}\\sum_{k\n
\n\n$$\n\\begin{equation} \n=\\frac{\\tau}{n}\\cdot\\mathrm{var}(x)\n\\label{eq:error_estimate_corr_time} \\tag{19}\n\\end{equation}\n$$\n\nand we see that $\\mathrm{err}_X$ can be expressed in terms the\nuncorrelated sample variance times a correction factor $\\tau$ which\naccounts for the correlation between measurements. We call this\ncorrection factor the *autocorrelation time*:\n\n\n
\n\n$$\n\\begin{equation}\n\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n\\label{eq:autocorrelation_time} \\tag{20}\n\\end{equation}\n$$\n\n## Statistics, effective number of correlations\nFor a correlation free experiment, $\\tau$\nequals 1. From the point of view of\neq. ([19](#eq:error_estimate_corr_time)) we can interpret a sequential\ncorrelation as an effective reduction of the number of measurements by\na factor $\\tau$. The effective number of measurements becomes:\n\n$$\nn_\\mathrm{eff} = \\frac{n}{\\tau}\n$$\n\nTo neglect the autocorrelation time $\\tau$ will always cause our\nsimple uncorrelated estimate of $\\mathrm{err}_X^2\\approx \\mathrm{var}(x)/n$ to\nbe less than the true sample error. The estimate of the error will be\ntoo *good*. On the other hand, the calculation of the full\nautocorrelation time poses an efficiency problem if the set of\nmeasurements is very large.\n\n\n\n\n\n\n\n\n## Can we understand this? Time Auto-correlation Function\nThe so-called time-displacement autocorrelation $\\phi(t)$ for a quantity $\\mathbf{M}$ is given by\n\n$$\n\\phi(t) = \\int dt' \\left[\\mathbf{M}(t')-\\langle \\mathbf{M} \\rangle\\right]\\left[\\mathbf{M}(t'+t)-\\langle \\mathbf{M} \\rangle\\right],\n$$\n\nwhich can be rewritten as\n\n$$\n\\phi(t) = \\int dt' \\left[\\mathbf{M}(t')\\mathbf{M}(t'+t)-\\langle \\mathbf{M} \\rangle^2\\right],\n$$\n\nwhere $\\langle \\mathbf{M} \\rangle$ is the average value and\n$\\mathbf{M}(t)$ its instantaneous value. We can discretize this function as follows, where we used our\nset of computed values $\\mathbf{M}(t)$ for a set of discretized times (our Monte Carlo cycles corresponding to moving all electrons?)\n\n\n
\n\n$$\n\\phi(t) = \\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t')\\mathbf{M}(t'+t)\n-\\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t')\\times\n\\frac{1}{t_{\\mathrm{max}}-t}\\sum_{t'=0}^{t_{\\mathrm{max}}-t}\\mathbf{M}(t'+t).\n\\label{eq:phitf} \\tag{21}\n$$\n\n## Time Auto-correlation Function\nOne should be careful with times close to $t_{\\mathrm{max}}$, the upper limit of the sums \nbecomes small and we end up integrating over a rather small time interval. This means that the statistical\nerror in $\\phi(t)$ due to the random nature of the fluctuations in $\\mathbf{M}(t)$ can become large.\n\nOne should therefore choose $t \\ll t_{\\mathrm{max}}$.\n\nNote that the variable $\\mathbf{M}$ can be any expectation values of interest.\n\n\n\nThe time-correlation function gives a measure of the correlation between the various values of the variable \nat a time $t'$ and a time $t'+t$. If we multiply the values of $\\mathbf{M}$ at these two different times,\nwe will get a positive contribution if they are fluctuating in the same direction, or a negative value\nif they fluctuate in the opposite direction. If we then integrate over time, or use the discretized version of, the time correlation function $\\phi(t)$ should take a non-zero value if the fluctuations are \ncorrelated, else it should gradually go to zero. For times a long way apart \nthe different values of $\\mathbf{M}$ are most likely \nuncorrelated and $\\phi(t)$ should be zero.\n\n\n\n\n\n\n## Time Auto-correlation Function\nWe can derive the correlation time by observing that our Metropolis algorithm is based on a random\nwalk in the space of all possible spin configurations. \nOur probability \ndistribution function $\\mathbf{\\hat{w}}(t)$ after a given number of time steps $t$ could be written as\n\n$$\n\\mathbf{\\hat{w}}(t) = \\mathbf{\\hat{W}^t\\hat{w}}(0),\n$$\n\nwith $\\mathbf{\\hat{w}}(0)$ the distribution at $t=0$ and $\\mathbf{\\hat{W}}$ representing the \ntransition probability matrix. \nWe can always expand $\\mathbf{\\hat{w}}(0)$ in terms of the right eigenvectors of \n$\\mathbf{\\hat{v}}$ of $\\mathbf{\\hat{W}}$ as\n\n$$\n\\mathbf{\\hat{w}}(0) = \\sum_i\\alpha_i\\mathbf{\\hat{v}}_i,\n$$\n\nresulting in\n\n$$\n\\mathbf{\\hat{w}}(t) = \\mathbf{\\hat{W}}^t\\mathbf{\\hat{w}}(0)=\\mathbf{\\hat{W}}^t\\sum_i\\alpha_i\\mathbf{\\hat{v}}_i=\n\\sum_i\\lambda_i^t\\alpha_i\\mathbf{\\hat{v}}_i,\n$$\n\nwith $\\lambda_i$ the $i^{\\mathrm{th}}$ eigenvalue corresponding to \nthe eigenvector $\\mathbf{\\hat{v}}_i$.\n\n\n\n\n\n\n## Time Auto-correlation Function\nIf we assume that $\\lambda_0$ is the largest eigenvector we see that in the limit $t\\rightarrow \\infty$,\n$\\mathbf{\\hat{w}}(t)$ becomes proportional to the corresponding eigenvector \n$\\mathbf{\\hat{v}}_0$. This is our steady state or final distribution. \n\nWe can relate this property to an observable like the mean energy.\nWith the probabilty $\\mathbf{\\hat{w}}(t)$ (which in our case is the squared trial wave function) we\ncan write the expectation values as\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\sum_{\\mu} \\mathbf{\\hat{w}}(t)_{\\mu}\\mathbf{M}_{\\mu},\n$$\n\nor as the scalar of a vector product\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\mathbf{\\hat{w}}(t)\\mathbf{m},\n$$\n\nwith $\\mathbf{m}$ being the vector whose elements are the values of $\\mathbf{M}_{\\mu}$ in its \nvarious microstates $\\mu$.\n\n\n\n\n## Time Auto-correlation Function\nWe rewrite this relation as\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\mathbf{\\hat{w}}(t)\\mathbf{m}=\\sum_i\\lambda_i^t\\alpha_i\\mathbf{\\hat{v}}_i\\mathbf{m}_i.\n$$\n\nIf we define $m_i=\\mathbf{\\hat{v}}_i\\mathbf{m}_i$ as the expectation value of\n$\\mathbf{M}$ in the $i^{\\mathrm{th}}$ eigenstate we can rewrite the last equation as\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\sum_i\\lambda_i^t\\alpha_im_i.\n$$\n\nSince we have that in the limit $t\\rightarrow \\infty$ the mean value is dominated by the \nthe largest eigenvalue $\\lambda_0$, we can rewrite the last equation as\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\langle \\mathbf{M}(\\infty) \\rangle+\\sum_{i\\ne 0}\\lambda_i^t\\alpha_im_i.\n$$\n\nWe define the quantity\n\n$$\n\\tau_i=-\\frac{1}{log\\lambda_i},\n$$\n\nand rewrite the last expectation value as\n\n\n
\n\n$$\n\\langle \\mathbf{M}(t) \\rangle = \\langle \\mathbf{M}(\\infty) \\rangle+\\sum_{i\\ne 0}\\alpha_im_ie^{-t/\\tau_i}.\n\\label{eq:finalmeanm} \\tag{22}\n$$\n\n## Time Auto-correlation Function\n\nThe quantities $\\tau_i$ are the correlation times for the system. They control also the auto-correlation function \ndiscussed above. The longest correlation time is obviously given by the second largest\neigenvalue $\\tau_1$, which normally defines the correlation time discussed above. For large times, this is the \nonly correlation time that survives. If higher eigenvalues of the transition matrix are well separated from \n$\\lambda_1$ and we simulate long enough, $\\tau_1$ may well define the correlation time. \nIn other cases we may not be able to extract a reliable result for $\\tau_1$. \nComing back to the time correlation function $\\phi(t)$ we can present a more general definition in terms\nof the mean magnetizations $ \\langle \\mathbf{M}(t) \\rangle$. Recalling that the mean value is equal \nto $ \\langle \\mathbf{M}(\\infty) \\rangle$ we arrive at the expectation values\n\n$$\n\\phi(t) =\\langle \\mathbf{M}(0)-\\mathbf{M}(\\infty)\\rangle \\langle \\mathbf{M}(t)-\\mathbf{M}(\\infty)\\rangle,\n$$\n\nresulting in\n\n$$\n\\phi(t) =\\sum_{i,j\\ne 0}m_i\\alpha_im_j\\alpha_je^{-t/\\tau_i},\n$$\n\nwhich is appropriate for all times.\n\n\n\n\n\n## Correlation Time\n\nIf the correlation function decays exponentially\n\n$$\n\\phi (t) \\sim \\exp{(-t/\\tau)}\n$$\n\nthen the exponential correlation time can be computed as the average\n\n$$\n\\tau_{\\mathrm{exp}} = -\\langle \\frac{t}{log|\\frac{\\phi(t)}{\\phi(0)}|} \\rangle.\n$$\n\nIf the decay is exponential, then\n\n$$\n\\int_0^{\\infty} dt \\phi(t) = \\int_0^{\\infty} dt \\phi(0)\\exp{(-t/\\tau)} = \\tau \\phi(0),\n$$\n\nwhich suggests another measure of correlation\n\n$$\n\\tau_{\\mathrm{int}} = \\sum_k \\frac{\\phi(k)}{\\phi(0)},\n$$\n\ncalled the integrated correlation time.\n", "meta": {"hexsha": "13381119ce7f0a74ccdeeef0e958cf1d622bbc3d", "size": 338687, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/week7/ipynb/week7.ipynb", "max_stars_repo_name": "Schoyen/ComputationalPhysics2", "max_stars_repo_head_hexsha": "9cf10ffb2557cc73c4e6bab060d53690ee39426f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/pub/week7/ipynb/week7.ipynb", "max_issues_repo_name": "Schoyen/ComputationalPhysics2", "max_issues_repo_head_hexsha": "9cf10ffb2557cc73c4e6bab060d53690ee39426f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/pub/week7/ipynb/week7.ipynb", "max_forks_repo_name": "Schoyen/ComputationalPhysics2", "max_forks_repo_head_hexsha": "9cf10ffb2557cc73c4e6bab060d53690ee39426f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 101.1609916368, "max_line_length": 135072, "alphanum_fraction": 0.8395184935, "converted": true, "num_tokens": 19089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.19997617827965505}} {"text": "# 3. Imagined movement\n\nIn this tutorial we will look at imagined movement. Our movement is controlled in the motor cortex where there is an increased level of mu activity (8–12 Hz) when we perform movements. This is accompanied by a reduction of this mu activity in specific regions that deal with the limb that is currently moving. This decrease is called Event Related Desynchronization (ERD). By measuring the amount of mu activity at different locations on the motor cortex, we can determine which limb the subject is moving. Through mirror neurons, this effect also occurs when the subject is not actually moving his limbs, but merely imagining it.\n\n## Credits\nThe CSP code was originally written by Boris Reuderink of the Donders\nInstitute for Brain, Cognition and Behavior. It is part of his Python EEG\ntoolbox: https://github.com/breuderink/eegtools\n\nInspiration for this tutorial also came from the excellent code example\ngiven in the book chapter:\n \nArnaud Delorme, Christian Kothe, Andrey Vankov, Nima Bigdely-Shamlo,\nRobert Oostenveld, Thorsten Zander, and Scott Makeig. MATLAB-Based Tools\nfor BCI Research, In _(B+H)CI: The Human in Brain-Computer Interfaces and\nthe Brain in Human-Computer Interaction._ Desney S. Tan and Anton Nijholt\n(eds.), 2009, 241-259, http://dx.doi.org/10.1007/978-1-84996-272-8\n\n## Obtaining the data\nThe dataset for this tutorial is provided by the fourth BCI competition,\nwhich you will have to download youself. First, go to http://www.bbci.de/competition/iv/#download\nand fill in your name and email address. An email will be sent to you\nautomatically containing a username and password for the download area.\n\nDownload Data Set 1, from Berlin, the 100Hz version in MATLAB format:\nhttp://bbci.de/competition/download/competition_iv/BCICIV_1_mat.zip\nand unzip it in a subdirectory called 'data_set_IV'. This subdirectory\nshould be inside the directory in which you've store the tutorial files.\n\n[Description of the data](http://bbci.de/competition/iv/desc_1.html)\n\nIf you've followed the instructions above, the following code should load\nthe data:\n\n\n```python\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n\n```python\nimport numpy as np\nimport scipy.io\n\nm = scipy.io.loadmat('data_set_IV/BCICIV_calib_ds1d.mat', struct_as_record=True)\n\n# SciPy.io.loadmat does not deal well with Matlab structures, resulting in lots of\n# extra dimensions in the arrays. This makes the code a bit more cluttered\n\nsample_rate = m['nfo']['fs'][0][0][0][0]\nEEG = m['cnt'].T\nnchannels, nsamples = EEG.shape\n\nchannel_names = [s[0].encode('utf8') for s in m['nfo']['clab'][0][0][0]]\nevent_onsets = m['mrk'][0][0][0]\nevent_codes = m['mrk'][0][0][1]\nlabels = np.zeros((1, nsamples), int)\nlabels[0, event_onsets] = event_codes\n\ncl_lab = [s[0].encode('utf8') for s in m['nfo']['classes'][0][0][0]]\ncl1 = cl_lab[0]\ncl2 = cl_lab[1]\nnclasses = len(cl_lab)\nnevents = len(event_onsets)\n```\n\nNow we have the data in the following python variables:\n\n\n```python\n# Print some information\nprint 'Shape of EEG:', EEG.shape\nprint 'Sample rate:', sample_rate\nprint 'Number of channels:', nchannels\nprint 'Channel names:', channel_names\nprint 'Number of events:', len(event_onsets)\nprint 'Event codes:', np.unique(event_codes)\nprint 'Class labels:', cl_lab\nprint 'Number of classes:', nclasses\n```\n\n Shape of EEG: (59, 190473)\n Sample rate: 100\n Number of channels: 59\n Channel names: ['AF3', 'AF4', 'F5', 'F3', 'F1', 'Fz', 'F2', 'F4', 'F6', 'FC5', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'FC6', 'CFC7', 'CFC5', 'CFC3', 'CFC1', 'CFC2', 'CFC4', 'CFC6', 'CFC8', 'T7', 'C5', 'C3', 'C1', 'Cz', 'C2', 'C4', 'C6', 'T8', 'CCP7', 'CCP5', 'CCP3', 'CCP1', 'CCP2', 'CCP4', 'CCP6', 'CCP8', 'CP5', 'CP3', 'CP1', 'CPz', 'CP2', 'CP4', 'CP6', 'P5', 'P3', 'P1', 'Pz', 'P2', 'P4', 'P6', 'PO1', 'PO2', 'O1', 'O2']\n Number of events: 1\n Event codes: [-1 1]\n Class labels: ['left', 'right']\n Number of classes: 2\n\n\nThis is a large recording: 59 electrodes where used, spread across the entire scalp. The subject was given a cue and then imagined either right hand movement or the movement of his feet. As can be seen from the [Homunculus](http://en.wikipedia.org/wiki/Cortical_homunculus), foot movement is controlled at the center of the motor cortex (which makes it hard to distinguish left from right foot), while hand movement is controlled more lateral.\n\n\n\n## Plotting the data\n\nThe code below cuts trials for the two classes and should look familiar if you've completed the previous tutorials. Trials are cut in the interval [0.5–2.5 s] after the onset of the cue.\n\n\n```python\n# Dictionary to store the trials in, each class gets an entry\ntrials = {}\n\n# The time window (in samples) to extract for each trial, here 0.5 -- 2.5 seconds\nwin = np.arange(int(0.5*sample_rate), int(2.5*sample_rate))\n\n# Length of the time window\nnsamples = len(win)\n\n# Loop over the classes (right, foot)\nfor cl, code in zip(cl_lab, np.unique(event_codes)):\n \n # Extract the onsets for the class\n cl_onsets = event_onsets[event_codes == code]\n \n # Allocate memory for the trials\n trials[cl] = np.zeros((nchannels, nsamples, len(cl_onsets)))\n \n # Extract each trial\n for i, onset in enumerate(cl_onsets):\n trials[cl][:,:,i] = EEG[:, win+onset]\n \n# Some information about the dimensionality of the data (channels x time x trials)\nprint 'Shape of trials[cl1]:', trials[cl1].shape\nprint 'Shape of trials[cl2]:', trials[cl2].shape\n```\n\n Shape of trials[cl1]: (59, 200, 100)\n Shape of trials[cl2]: (59, 200, 100)\n\n\n\n\nSince the feature we're looking for (a decrease in $\\mu$-activity) is a frequency feature, lets plot the PSD of the trials in a similar manner as with the SSVEP data. The code below defines a function that computes the PSD for each trial (we're going to need it again later on):\n\n\n```python\nfrom matplotlib import mlab\n\ndef psd(trials):\n '''\n Calculates for each trial the Power Spectral Density (PSD).\n \n Parameters\n ----------\n trials : 3d-array (channels x samples x trials)\n The EEG signal\n \n Returns\n -------\n trial_PSD : 3d-array (channels x PSD x trials)\n the PSD for each trial. \n freqs : list of floats\n Yhe frequencies for which the PSD was computed (useful for plotting later)\n '''\n \n ntrials = trials.shape[2]\n trials_PSD = np.zeros((nchannels, 101, ntrials))\n\n # Iterate over trials and channels\n for trial in range(ntrials):\n for ch in range(nchannels):\n # Calculate the PSD\n (PSD, freqs) = mlab.psd(trials[ch,:,trial], NFFT=int(nsamples), Fs=sample_rate)\n trials_PSD[ch, :, trial] = PSD.ravel()\n \n return trials_PSD, freqs\n```\n\n\n```python\n# Apply the function\npsd_r, freqs = psd(trials[cl1])\npsd_f, freqs = psd(trials[cl2])\ntrials_PSD = {cl1: psd_r, cl2: psd_f}\n```\n\nThe function below plots the PSDs that are calculated with the above function. Since plotting it for 118 channels will clutter the display, it takes the indices of the desired channels as input, as well as some metadata to decorate the plot.\n\n\n```python\nimport matplotlib.pyplot as plt\n\ndef plot_psd(trials_PSD, freqs, chan_ind, chan_lab=None, maxy=None):\n '''\n Plots PSD data calculated with psd().\n \n Parameters\n ----------\n trials : 3d-array\n The PSD data, as returned by psd()\n freqs : list of floats\n The frequencies for which the PSD is defined, as returned by psd() \n chan_ind : list of integers\n The indices of the channels to plot\n chan_lab : list of strings\n (optional) List of names for each channel\n maxy : float\n (optional) Limit the y-axis to this value\n '''\n plt.figure(figsize=(12,5))\n \n nchans = len(chan_ind)\n \n # Maximum of 3 plots per row\n nrows = np.ceil(nchans / 3)\n ncols = min(3, nchans)\n \n # Enumerate over the channels\n for i,ch in enumerate(chan_ind):\n # Figure out which subplot to draw to\n plt.subplot(nrows,ncols,i+1)\n \n # Plot the PSD for each class\n for cl in trials.keys():\n plt.plot(freqs, np.mean(trials_PSD[cl][ch,:,:], axis=1), label=cl)\n \n # All plot decoration below...\n \n plt.xlim(1,30)\n \n if maxy != None:\n plt.ylim(0,maxy)\n \n plt.grid()\n \n plt.xlabel('Frequency (Hz)')\n \n if chan_lab == None:\n plt.title('Channel %d' % (ch+1))\n else:\n plt.title(chan_lab[i])\n\n plt.legend()\n \n plt.tight_layout()\n```\n\nLets put the `plot_psd()` function to use and plot three channels:\n\n 1. C3: Central, left\n 2. Cz: Central, central\n 3. C4: Central, right\n\n\n```python\nplot_psd(\n trials_PSD,\n freqs,\n [channel_names.index(ch) for ch in ['C3', 'Cz', 'C4']],\n chan_lab=['left', 'center', 'right'],\n maxy=500\n)\n```\n\nA spike of mu activity can be seen on each channel for both classes. At the right hemisphere, the mu for the left hand movement is lower than for the right hand movement due to the ERD. At the left electrode, the mu for the right hand movement is reduced and at the central electrode the mu activity is about equal for both classes. This is in line with the theory that the left hand is controlled by the left hemiphere and the feet are controlled centrally.\n\n## Classifying the data\n\nWe will use a machine learning algorithm to construct a model that can distinguish between the right hand and foot movement of this subject. In order to do this we need to:\n\n 1. find a way to quantify the amount of mu activity present in a trial\n 2. make a model that describes expected values of mu activity for each class\n 3. finally test this model on some unseen data to see if it can predict the correct class label\n\nWe will follow a classic BCI design by Blankertz et al. [1] where they use the logarithm of the variance of the signal in a certain frequency band as a feature for the classifier.\n\n[1] Blankertz, B., Dornhege, G., Krauledat, M., Müller, K.-R., & Curio, G. (2007). The non-invasive Berlin Brain-Computer Interface: fast acquisition of effective performance in untrained subjects. *NeuroImage*, 37(2), 539–550. doi:10.1016/j.neuroimage.2007.01.051\n\nThe script below designs a band pass filter using [`scipy.signal.irrfilter`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.iirfilter.html) that will strip away frequencies outside the 8--15Hz window. The filter is applied to all trials:\n\n\n```python\nimport scipy.signal \n\ndef bandpass(trials, lo, hi, sample_rate):\n '''\n Designs and applies a bandpass filter to the signal.\n \n Parameters\n ----------\n trials : 3d-array (channels x samples x trials)\n The EEGsignal\n lo : float\n Lower frequency bound (in Hz)\n hi : float\n Upper frequency bound (in Hz)\n sample_rate : float\n Sample rate of the signal (in Hz)\n \n Returns\n -------\n trials_filt : 3d-array (channels x samples x trials)\n The bandpassed signal\n '''\n\n # The iirfilter() function takes the filter order: higher numbers mean a sharper frequency cutoff,\n # but the resulting signal might be shifted in time, lower numbers mean a soft frequency cutoff,\n # but the resulting signal less distorted in time. It also takes the lower and upper frequency bounds\n # to pass, divided by the niquist frequency, which is the sample rate divided by 2:\n a, b = scipy.signal.iirfilter(6, [lo/(sample_rate/2.0), hi/(sample_rate/2.0)])\n\n # Applying the filter to each trial\n ntrials = trials.shape[2]\n trials_filt = np.zeros((nchannels, nsamples, ntrials))\n for i in range(ntrials):\n trials_filt[:,:,i] = scipy.signal.filtfilt(a, b, trials[:,:,i], axis=1)\n \n return trials_filt\n```\n\n\n```python\n# Apply the function\ntrials_filt = {cl1: bandpass(trials[cl1], 8, 15, sample_rate),\n cl2: bandpass(trials[cl2], 8, 15, sample_rate)}\n```\n\nPlotting the PSD of the resulting `trials_filt` shows the suppression of frequencies outside the passband of the filter:\n\n\n```python\npsd_r, freqs = psd(trials_filt[cl1])\npsd_f, freqs = psd(trials_filt[cl2])\ntrials_PSD = {cl1: psd_r, cl2: psd_f}\n\nplot_psd(\n trials_PSD,\n freqs,\n [channel_names.index(ch) for ch in ['C3', 'Cz', 'C4']],\n chan_lab=['left', 'center', 'right'],\n maxy=300\n)\n```\n\nAs a feature for the classifier, we will use the logarithm of the variance of each channel. The function below calculates this:\n\n\n```python\n# Calculate the log(var) of the trials\ndef logvar(trials):\n '''\n Calculate the log-var of each channel.\n \n Parameters\n ----------\n trials : 3d-array (channels x samples x trials)\n The EEG signal.\n \n Returns\n -------\n logvar - 2d-array (channels x trials)\n For each channel the logvar of the signal\n '''\n return np.log(np.var(trials, axis=1))\n```\n\n\n```python\n# Apply the function\ntrials_logvar = {cl1: logvar(trials_filt[cl1]),\n cl2: logvar(trials_filt[cl2])}\n```\n\nBelow is a function to visualize the logvar of each channel as a bar chart:\n\n\n```python\ndef plot_logvar(trials):\n '''\n Plots the log-var of each channel/component.\n arguments:\n trials - Dictionary containing the trials (log-vars x trials) for 2 classes.\n '''\n plt.figure(figsize=(12,5))\n \n x0 = np.arange(nchannels)\n x1 = np.arange(nchannels) + 0.4\n\n y0 = np.mean(trials[cl1], axis=1)\n y1 = np.mean(trials[cl2], axis=1)\n\n plt.bar(x0, y0, width=0.5, color='b')\n plt.bar(x1, y1, width=0.4, color='r')\n\n plt.xlim(-0.5, nchannels+0.5)\n\n plt.gca().yaxis.grid(True)\n plt.title('log-var of each channel/component')\n plt.xlabel('channels/components')\n plt.ylabel('log-var')\n plt.legend(cl_lab)\n```\n\n\n```python\n# Plot the log-vars\nplot_logvar(trials_logvar)\n```\n\nWe see that most channels show a small difference in the log-var of the signal between the two classes. The next step is to go from 118 channels to only a few channel mixtures. The CSP algorithm calculates mixtures of channels that are designed to maximize the difference in variation between two classes. These mixures are called spatial filters.\n\n\n```python\nfrom numpy import linalg\n\ndef cov(trials):\n ''' Calculate the covariance for each trial and return their average '''\n ntrials = trials.shape[2]\n covs = [ trials[:,:,i].dot(trials[:,:,i].T) / nsamples for i in range(ntrials) ]\n return np.mean(covs, axis=0)\n\ndef whitening(sigma):\n ''' Calculate a whitening matrix for covariance matrix sigma. '''\n U, l, _ = linalg.svd(sigma)\n return U.dot( np.diag(l ** -0.5) )\n\ndef csp(trials_r, trials_f):\n '''\n Calculate the CSP transformation matrix W.\n arguments:\n trials_r - Array (channels x samples x trials) containing right hand movement trials\n trials_f - Array (channels x samples x trials) containing foot movement trials\n returns:\n Mixing matrix W\n '''\n cov_r = cov(trials_r)\n cov_f = cov(trials_f)\n P = whitening(cov_r + cov_f)\n B, _, _ = linalg.svd( P.T.dot(cov_f).dot(P) )\n W = P.dot(B)\n return W\n\ndef apply_mix(W, trials):\n ''' Apply a mixing matrix to each trial (basically multiply W with the EEG signal matrix)'''\n ntrials = trials.shape[2]\n trials_csp = np.zeros((nchannels, nsamples, ntrials))\n for i in range(ntrials):\n trials_csp[:,:,i] = W.T.dot(trials[:,:,i])\n return trials_csp\n```\n\n\n```python\n# Apply the functions\nW = csp(trials_filt[cl1], trials_filt[cl2])\ntrials_csp = {cl1: apply_mix(W, trials_filt[cl1]),\n cl2: apply_mix(W, trials_filt[cl2])}\n```\n\nTo see the result of the CSP algorithm, we plot the log-var like we did before:\n\n\n```python\ntrials_logvar = {cl1: logvar(trials_csp[cl1]),\n cl2: logvar(trials_csp[cl2])}\nplot_logvar(trials_logvar)\n```\n\nInstead of 118 channels, we now have 118 mixtures of channels, called components. They are the result of 118 spatial filters applied to the data.\n\nThe first filters maximize the variation of the first class, while minimizing the variation of the second. The last filters maximize the variation of the second class, while minimizing the variation of the first.\n\nThis is also visible in a PSD plot. The code below plots the PSD for the first and last components as well as one in the middle:\n\n\n```python\npsd_r, freqs = psd(trials_csp[cl1])\npsd_f, freqs = psd(trials_csp[cl2])\ntrials_PSD = {cl1: psd_r, cl2: psd_f}\n\nplot_psd(trials_PSD, freqs, [0,58,-1], chan_lab=['first component', 'middle component', 'last component'], maxy=0.75 )\n```\n\nIn order to see how well we can differentiate between the two classes, a scatter plot is a useful tool. Here both classes are plotted on a 2-dimensional plane: the x-axis is the first CSP component, the y-axis is the last.\n\n\n```python\ndef plot_scatter(left, foot):\n plt.figure()\n plt.scatter(left[0,:], left[-1,:], color='b')\n plt.scatter(foot[0,:], foot[-1,:], color='r')\n plt.xlabel('Last component')\n plt.ylabel('First component')\n plt.legend(cl_lab)\n```\n\n\n```python\nplot_scatter(trials_logvar[cl1], trials_logvar[cl2])\n```\n\nWe will apply a linear classifier to this data. A linear classifier can be thought of as drawing a line in the above plot to separate the two classes. To determine the class for a new trial, we just check on which side of the line the trial would be if plotted as above.\n\nThe data is split into a train and a test set. The classifier will fit a model (in this case, a straight line) on the training set and use this model to make predictions about the test set (see on which side of the line each trial in the test set falls). Note that the CSP algorithm is part of the model, so for fairness sake it should be calculated using only the training data.\n\n\n```python\n# Percentage of trials to use for training (50-50 split here)\ntrain_percentage = 0.5 \n\n# Calculate the number of trials for each class the above percentage boils down to\nntrain_r = int(trials_filt[cl1].shape[2] * train_percentage)\nntrain_f = int(trials_filt[cl2].shape[2] * train_percentage)\nntest_r = trials_filt[cl1].shape[2] - ntrain_r\nntest_f = trials_filt[cl2].shape[2] - ntrain_f\n\n# Splitting the frequency filtered signal into a train and test set\ntrain = {cl1: trials_filt[cl1][:,:,:ntrain_r],\n cl2: trials_filt[cl2][:,:,:ntrain_f]}\n\ntest = {cl1: trials_filt[cl1][:,:,ntrain_r:],\n cl2: trials_filt[cl2][:,:,ntrain_f:]}\n\n# Train the CSP on the training set only\nW = csp(train[cl1], train[cl2])\n\n# Apply the CSP on both the training and test set\ntrain[cl1] = apply_mix(W, train[cl1])\ntrain[cl2] = apply_mix(W, train[cl2])\ntest[cl1] = apply_mix(W, test[cl1])\ntest[cl2] = apply_mix(W, test[cl2])\n\n# Select only the first and last components for classification\ncomp = np.array([0,-1])\ntrain[cl1] = train[cl1][comp,:,:]\ntrain[cl2] = train[cl2][comp,:,:]\ntest[cl1] = test[cl1][comp,:,:]\ntest[cl2] = test[cl2][comp,:,:]\n\n# Calculate the log-var\ntrain[cl1] = logvar(train[cl1])\ntrain[cl2] = logvar(train[cl2])\ntest[cl1] = logvar(test[cl1])\ntest[cl2] = logvar(test[cl2])\n```\n\nFor a classifier the Linear Discriminant Analysis (LDA) algorithm will be used. It fits a gaussian distribution to each class, characterized by the mean and covariance, and determines an optimal separating plane to divide the two. This plane is defined as $r = W_0 \\cdot X_0 + W_1 \\cdot X_1 + \\ldots + W_n \\cdot X_n - b$, where $r$ is the classifier output, $W$ are called the feature weights, $X$ are the features of the trial, $n$ is the dimensionality of the data and $b$ is called the offset.\n\nIn our case we have 2 dimensional data, so the separating plane will be a line: $r = W_0 \\cdot X_0 + W_1 \\cdot X_1 - b$. To determine a class label for an unseen trial, we can calculate whether the result is positive or negative.\n\n\n```python\ndef train_lda(class1, class2):\n '''\n Trains the LDA algorithm.\n arguments:\n class1 - An array (observations x features) for class 1\n class2 - An array (observations x features) for class 2\n returns:\n The projection matrix W\n The offset b\n '''\n nclasses = 2\n \n nclass1 = class1.shape[0]\n nclass2 = class2.shape[0]\n \n # Class priors: in this case, we have an equal number of training\n # examples for each class, so both priors are 0.5\n prior1 = nclass1 / float(nclass1 + nclass2)\n prior2 = nclass2 / float(nclass1 + nclass1)\n \n mean1 = np.mean(class1, axis=0)\n mean2 = np.mean(class2, axis=0)\n \n class1_centered = class1 - mean1\n class2_centered = class2 - mean2\n \n # Calculate the covariance between the features\n cov1 = class1_centered.T.dot(class1_centered) / (nclass1 - nclasses)\n cov2 = class2_centered.T.dot(class2_centered) / (nclass2 - nclasses)\n \n W = (mean2 - mean1).dot(np.linalg.pinv(prior1*cov1 + prior2*cov2))\n b = (prior1*mean1 + prior2*mean2).dot(W)\n \n return (W,b)\n\ndef apply_lda(test, W, b):\n '''\n Applies a previously trained LDA to new data.\n arguments:\n test - An array (features x trials) containing the data\n W - The project matrix W as calculated by train_lda()\n b - The offsets b as calculated by train_lda()\n returns:\n A list containing a classlabel for each trial\n '''\n ntrials = test.shape[1]\n \n prediction = []\n for i in range(ntrials):\n # The line below is a generalization for:\n # result = W[0] * test[0,i] + W[1] * test[1,i] - b\n result = W.dot(test[:,i]) - b\n if result <= 0:\n prediction.append(1)\n else:\n prediction.append(2)\n \n return np.array(prediction)\n```\n\nTraining the LDA using the training data gives us $W$ and $b$:\n\n\n```python\nW,b = train_lda(train[cl1].T, train[cl2].T)\n\nprint 'W:', W\nprint 'b:', b\n```\n\n W: [ 5.31347949 -5.52963938]\n b: 0.380247210381\n\n\nIt can be informative to recreate the scatter plot and overlay the decision boundary as determined by the LDA classifier. The decision boundary is the line for which the classifier output is exactly 0. The scatterplot used $X_0$ as $x$-axis and $X_1$ as $y$-axis. To find the function $y = f(x)$ describing the decision boundary, we set $r$ to 0 and solve for $y$ in the equation of the separating plane:\n\n
\n$$\\begin{align}\nW_0 \\cdot X_0 + W_1 \\cdot X_1 - b &= r &&\\text{the original equation} \\\\\\\nW_0 \\cdot x + W_1 \\cdot y - b &= 0 &&\\text{filling in $X_0=x$, $X_1=y$ and $r=0$} \\\\\\\nW_0 \\cdot x + W_1 \\cdot y &= b &&\\text{solving for $y$}\\\\\\\nW_1 \\cdot y &= b - W_0 \\cdot x \\\\\\\n\\\\\\\ny &= \\frac{b - W_0 \\cdot x}{W_1}\n\\end{align}$$\n
\n\nWe first plot the decision boundary with the training data used to calculate it:\n\n\n```python\n# Scatterplot like before\nplot_scatter(train[cl1], train[cl2])\ntitle('Training data')\n\n# Calculate decision boundary (x,y)\nx = np.arange(-5, 1, 0.1)\ny = (b - W[0]*x) / W[1]\n\n# Plot the decision boundary\nplt.plot(x,y, linestyle='--', linewidth=2, color='k')\nplt.xlim(-5, 1)\nplt.ylim(-2.2, 1)\n```\n\nThe code below plots the boundary with the test data on which we will apply the classifier. You will see the classifier is going to make some mistakes.\n\n\n```python\nplot_scatter(test[cl1], test[cl2])\ntitle('Test data')\nplt.plot(x,y, linestyle='--', linewidth=2, color='k')\nplt.xlim(-5, 1)\nplt.ylim(-2.2, 1)\n```\n\nNow the LDA is constructed and fitted to the training data. We can now apply it to the test data. The results are presented as a confusion matrix:\n \n\n \n \n \n \n
True labels →
↓ Predicted labelsRightFoot
Right
Foot
\n\nThe number at the diagonal will be trials that were correctly classified, any trials incorrectly classified (either a false positive or false negative) will be in the corners.\n\n\n```python\n# Print confusion matrix\nconf = np.array([\n [(apply_lda(test[cl1], W, b) == 1).sum(), (apply_lda(test[cl2], W, b) == 1).sum()],\n [(apply_lda(test[cl1], W, b) == 2).sum(), (apply_lda(test[cl2], W, b) == 2).sum()],\n])\n\nprint 'Confusion matrix:'\nprint conf\nprint\nprint 'Accuracy: %.3f' % (np.sum(np.diag(conf)) / float(np.sum(conf)))\n```\n\n Confusion matrix:\n [[45 4]\n [ 5 46]]\n \n Accuracy: 0.910\n\n\nThe confusion matrix shows that 4 out of the 50 trials with foot movement were incorrectly classified as right hand movement and 5 out of the 50 trials with right hand movement were incorrectly classified as foot movement. In total, 91% of the trials were correctly classified, not a bad score!\n\n\n```python\n\n```\n", "meta": {"hexsha": "cca7570637b902cabdd895efc23b6762e0af0904", "size": 228074, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "3. Imagined movement.ipynb", "max_stars_repo_name": "candleinwindsteve/neuroscience_tutorials", "max_stars_repo_head_hexsha": "80fb0bee5bbe895420a47434036be48ab0a5f968", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-08T22:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T22:53:01.000Z", "max_issues_repo_path": "3. Imagined movement.ipynb", "max_issues_repo_name": "candleinwindsteve/neuroscience_tutorials", "max_issues_repo_head_hexsha": "80fb0bee5bbe895420a47434036be48ab0a5f968", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3. Imagined movement.ipynb", "max_forks_repo_name": "candleinwindsteve/neuroscience_tutorials", "max_forks_repo_head_hexsha": "80fb0bee5bbe895420a47434036be48ab0a5f968", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 198.1529105126, "max_line_length": 45304, "alphanum_fraction": 0.8899304612, "converted": true, "num_tokens": 6945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19844910352416034}} {"text": "   \n\n# (Bonus) Tutorial 2: Facial recognition using modern convnets\n\n**Week 2, Day 2: Modern Convnets**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Laura Pede, Richard Vogg, Marissa Weis, Timo Lüddecke, Alexander Ecker\n\n__Content reviewers:__ Arush Tagade, Polina Turishcheva, Yu-Fang Yang, Bettina Hein, Melvin Selim Atay, Kelson Shilling-Scrivo\n\n__Content editors:__ Roberto Guidotti, Spiros Chavlis\n\n__Production editors:__ Anoop Kulkarni, Roberto Guidotti, Cary Murray, Spiros Chavlis\n\n*Notebook is based on an initial version by Ben Heil*\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial Objectives\n\nIn this tutorial you will learn about:\n\n1. An application of modern CNNs in facial recognition.\n2. Ethical aspects of facial recognition.\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorial\n\n# @markdown If you want to download locally the slides, click [here](https://osf.io/4r2dp/download)\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/4r2dp/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\n\n```python\n# @title Install dependencies\n# @markdown Install `facenet` - a model used to do facial recognition\n!pip install facenet-pytorch --quiet\n!pip install Pillow --quiet\n```\n\n\n```python\n# Imports\nimport glob\nimport torch\n\nimport numpy as np\nimport sklearn.decomposition\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\n\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom torchvision.datasets import ImageFolder\n\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# especially if torch modules used.\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nSEED = 2021\nset_seed(seed=SEED)\nDEVICE = set_device()\n```\n\n Random seed 2021 has been set.\n GPU is enabled in this notebook.\n\n\n---\n# Section 1: Face Recognition\n\n*Time estimate: ~12mins*\n\n## Section 1.1: Download and prepare the data\n\n\n```python\n# @title Download Data\nimport requests, zipfile, io, os\n\n# original link: https://github.com/ben-heil/cis_522_data.git\nurl = 'https://osf.io/2kyfb/download'\n\nfname = 'faces'\n\nif not os.path.exists(fname+'zip'):\n print(\"Data is being downloaded...\")\n r = requests.get(url, stream=True)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n z.extractall()\n print(\"The download has been completed.\")\nelse:\n print(\"Data has already been downloaded.\")\n```\n\n Data is being downloaded...\n The download has been completed.\n\n\n\n```python\n# @title Video 1: Face Recognition using CNNs\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV17B4y1K7WV\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"jJqEv8hpRa4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n\n Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})\n\n\nOne application of large CNNs is **facial recognition**. The problem formulation in facial recognition is a little different from the image classification we've seen so far. In facial recognition, we don't want to have a fixed number of individuals that the model can learn. If that were the case then to learn a new person it would be necessary to modify the output portion of the architecture and retrain to account for the new person.\n\nInstead, we train a model to learn an **embedding** where images from the same individual are close to each other in an embedded space, and images corresponding to different people are far apart. When the model is trained, it takes as input an image and outputs an embedding vector corresponding to the image. \n\nTo achieve this, facial recognitions typically use a **triplet loss** that compares two images from the same individual (i.e., \"anchor\" and \"positive\" images) and a negative image from a different individual (i.e., \"negative\" image). The loss requires the distance between the anchor and negative points to be greater than a margin $\\alpha$ + the distance between the anchor and positive points.\n\n## Section 1.2: View and transform the data\n\nA well-trained facial recognition system should be able to map different images of the same individual relatively close together. We will load 15 images of three individuals (maybe you know them - then you can see that your brain is quite well in facial recognition).\n\nAfter viewing the images, we will transform them: MTCNN ([github repo](https://github.com/ipazc/mtcnn)) detects the face and crops the image around the face. Then we stack all the images together in a tensor.\n\n\n```python\n# @title Display Images\n# @markdown Here are the source images of Bruce Lee, Neil Patrick Harris, and Pam Grier\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nface_dataset = ImageFolder('faces', transform=train_transform)\n\nimage_count = len(face_dataset)\n\nface_loader = torch.utils.data.DataLoader(face_dataset,\n batch_size=45,\n shuffle=False)\n\ndataiter = iter(face_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.figure(figsize=(15, 15))\nplt.imshow(make_grid(images, nrow=15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n# @title Image Preprocessing Function\ndef process_images(image_dir: str, size=256):\n \"\"\"\n This function returns two tensors for the given image dir: one usable for inputting into the\n facenet model, and one that is [0,1] scaled for visualizing\n\n Parameters:\n image_dir: The glob corresponding to images in a directory\n\n Returns:\n model_tensor: A image_count x channels x height x width tensor scaled to between -1 and 1,\n with the faces detected and cropped to the center using mtcnn\n display_tensor: A transformed version of the model tensor scaled to between 0 and 1\n \"\"\"\n mtcnn = MTCNN(image_size=size, margin=32)\n images = []\n for img_path in glob.glob(image_dir):\n img = Image.open(img_path)\n # Normalize and crop image\n img_cropped = mtcnn(img)\n images.append(img_cropped)\n\n model_tensor = torch.stack(images)\n display_tensor = model_tensor / (model_tensor.max() * 2)\n display_tensor += .5\n\n return model_tensor, display_tensor\n```\n\nNow that we have our images loaded, we need to preprocess them. To make the images easier for the network to learn, we crop them to include just faces.\n\n\n```python\nbruce_tensor, bruce_display = process_images('faces/bruce/*.jpg')\nneil_tensor, neil_display = process_images('faces/neil/*.jpg')\npam_tensor, pam_display = process_images('faces/pam/*.jpg')\n\ntensor_to_display = torch.cat((bruce_display, neil_display, pam_display))\n\nplt.figure(figsize=(15, 15))\nplt.imshow(make_grid(tensor_to_display, nrow=15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n## Section 1.3: Embedding with a pretrained network \n\nWe load a pretrained facial recognition model called [FaceNet](https://github.com/timesler/facenet-pytorch). It was trained on the [VGGFace2](https://github.com/ox-vgg/vgg_face2) dataset which contains 3.31 million images of 9131 individuals.\n\nWe use the pretrained model to calculate embeddings for all of our input images.\n\n\n```python\nresnet = InceptionResnetV1(pretrained='vggface2').eval().to(DEVICE)\n```\n\n\n```python\n# Calculate embedding\nresnet.classify = False\nbruce_embeddings = resnet(bruce_tensor.to(DEVICE))\nneil_embeddings = resnet(neil_tensor.to(DEVICE))\npam_embeddings = resnet(pam_tensor.to(DEVICE))\n```\n\n### Think! 1.3: Embedding vectors\n\nWe want to understand what happens when the model receives an image and returns the corresponding embedding vector.\n\n- What are the height, width and number of channels of one input image?\n- What are the dimensions of one stack of images (e.g. bruce_tensor)?\n- What are the dimensions of the corresponding embedding (e.g. bruce_embeddings)?\n- What would be the dimensions of the embedding of one input image?\n\n\n**Hints:**\n- You can double click on a variable name and hover over it to see the dimensions of tensors.\n- You do not have to answer the questions in the order they are asked.\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_22e742e7.py)\n\n\n\nWe cannot show 512-dimensional vectors visually, but using **Principal Component Analysis (PCA)** we can project the 512 dimensions onto a 2-dimensional space while preserving the maximum amount of data variation possible. This is just a visual aid for us to understand the concept. Note that if you would like to do any calculation, like distances between two images, this would be done with the whole 512-dimensional embedding vectors.\n\n\n```python\nembedding_tensor = torch.cat((bruce_embeddings,\n neil_embeddings,\n pam_embeddings)).to(device='cpu')\n\npca = sklearn.decomposition.PCA(n_components=2)\npca_tensor = pca.fit_transform(embedding_tensor.detach().cpu().numpy())\n```\n\n\n```python\nnum = 15\ncategs = 3\ncolors = ['blue', 'orange', 'magenta']\nlabels = ['Bruce Lee', 'Neil Patrick Harris', 'Pam Grier']\nmarkers = ['o', 'x', 's']\nplt.figure(figsize=(8, 8))\nfor i in range(categs):\n plt.scatter(pca_tensor[i*num:(i+1)*num, 0],\n pca_tensor[i*num:(i+1)*num, 1],\n c=colors[i],\n marker=markers[i], label=labels[i])\nplt.legend()\nplt.title('PCA Representation of the Image Embeddings')\nplt.xlabel('PC 1')\nplt.ylabel('PC 2')\nplt.show()\n```\n\nGreat! The images corresponding to each individual are separated from each other in the embedding space!\n\nIf Neil Patrick Harris wants to unlock his phone with facial recognition, the phone takes the image from the camera, calculates the embedding and checks if it is close to the registered embeddings corresponding to Neil Patrick Harris.\n\n---\n# Section 2: Ethics – bias/discrimination due to pre-training datasets\n\n*Time estimate: ~19mins*\n\nPopular facial recognition datasets like VGGFace2 and CASIA-WebFace consist primarily of caucasian faces. \nAs a result, even state of the art facial recognition models [substantially underperform](https://openaccess.thecvf.com/content_ICCV_2019/papers/Wang_Racial_Faces_in_the_Wild_Reducing_Racial_Bias_by_Information_ICCV_2019_paper.pdf) when attempting to recognize faces of other races.\n\nGiven the implications that poor model performance can have in fields like security and criminal justice, it's very important to be aware of these limitations if you're going to be building facial recognition systems.\n\nIn this example we will work with a small subset from the [UTKFace](https://susanqq.github.io/UTKFace/) dataset with 49 pictures of black women and 49 picture of white women. We will use the same pretrained model as in Section 8 of Tutorial 1, see and discuss the consequences of the model being trained on an imbalanced dataset.\n\n\n```python\n# @title Video 2: Ethical aspects\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Jo4y1Q7K3\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"vYilJV3PqUM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n## Section 2.1: Download the Data\n\n\n```python\n# @title Run this cell to get the data\n\n# original link: https://github.com/richardvogg/face_sample.git\nurl = 'https://osf.io/36wyh/download'\nfname = 'face_sample2'\n\nif not os.path.exists(fname+'zip'):\n print(\"Data is being downloaded...\")\n r = requests.get(url, stream=True)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n z.extractall()\n print(\"The download has been completed.\")\nelse:\n print(\"Data has already been downloaded.\")\n```\n\n## Section 2.2: Load, view and transform the data\n\n\n```python\nblack_female_tensor, black_female_display = process_images('face_sample2/??_1_1_*.jpg', size=150)\nwhite_female_tensor, white_female_display = process_images('face_sample2/??_1_0_*.jpg', size=150)\n```\n\nWe can check the dimensions of these tensors and see that for each group we have images of size $150 \\times 150$ and three channels (RGB) of 49 individuals.\n\n**Note:** Originally, the size of images was $200 \\times 200$, but due to RAM resources, we have reduced it. You can change it back, i.e., `size=200`.\n\n\n```python\nprint(white_female_tensor.shape)\nprint(black_female_tensor.shape)\n```\n\n\n```python\n# @title Visualize some example faces\ntensor_to_display = torch.cat((white_female_display[:15],\n black_female_display[:15]))\n\nplt.figure(figsize=(12, 12))\nplt.imshow(make_grid(tensor_to_display, nrow = 15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n## Section 2.3: Calculate embeddings\n\nWe use the same pretrained facial recognition network as in section 8 to calculate embeddings. If you have memory issues running this part, go to `Edit > Notebook settings` and check if GPU is selected as `Hardware accelerator`. If this does not help you can restart the notebook, go to `Runtime -> Restart runtime`.\n\n\n```python\nresnet.classify = False\nblack_female_embeddings = resnet(black_female_tensor.to(DEVICE))\nwhite_female_embeddings = resnet(white_female_tensor.to(DEVICE))\n```\n\nWe will use the embeddings to show that the model was trained on an imbalanced dataset. For this, we are going to calculate a distance matrix of all combinations of images, like in this small example with $n=3$ (in our case $n=98$).\n\n\n\nCalculate the distance between each pair of image embeddings in our tensor and visualize all the distances. Remember that two embeddings are vectors and the distance between two vectors is the Euclidean distance.\n\n\n```python\n# @title Function to calculate pairwise distances\n\n# @markdown [`torch.cdist`](https://pytorch.org/docs/stable/generated/torch.cdist.html) is used\n\ndef calculate_pairwise_distances(embedding_tensor):\n \"\"\"\n This function calculates the distance between each pair of image embeddings\n in a tensor using the `torch.cdist`.\n\n Parameters:\n embedding_tensor : torch.Tensor\n A num_images x embedding_dimension tensor\n\n Returns:\n distances : torch.Tensor\n A num_images x num_images tensor containing the pairwise distances between\n each to image embedding\n \"\"\"\n\n distances = torch.cdist(embedding_tensor, embedding_tensor)\n\n return distances\n```\n\n\n```python\n# @title Visualize the distances\n\nembedding_tensor = torch.cat((black_female_embeddings,\n white_female_embeddings)).to(device='cpu')\n\ndistances = calculate_pairwise_distances(embedding_tensor)\n\nplt.figure(figsize=(8, 8))\nplt.imshow(distances.detach().cpu().numpy())\nplt.annotate('Black female', (2, -0.5), fontsize=20, va='bottom')\nplt.annotate('White female', (52, -0.5), fontsize=20, va='bottom')\nplt.annotate('Black female', (-0.5, 45), fontsize=20, rotation=90, ha='right')\nplt.annotate('White female', (-0.5, 90), fontsize=20, rotation=90, ha='right')\ncbar = plt.colorbar()\ncbar.set_label('Distance', fontsize=16)\nplt.axis('off')\nplt.show()\n```\n\n## Exercise 2.1\n\nWhat do you observe? The faces of which group are more similar to each other for the Face Detection algorithm?\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_2309aa23.py)\n\n\n\n## Exercise 2.2\n- What does it mean in real life applications that the distance is smaller between the embeddings of one group?\n- Can you come up with example situations/applications where this has a negative impact?\n- What could you do to avoid these problems?\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_9a053438.py)\n\n\n\nLastly, to show the importance of the dataset which you use to pretrain your model, look at how much space white men and women take in different embeddings. *FairFace* is a dataset which is specifically created with completely balanced classes. The blue dots in all visualizations are white male and white female.\n\n\n\nAdopted from [Kärkkäinen and Joo, 2019, arXiv](https://arxiv.org/abs/1908.04913)\n\n---\n# Section 3: Within Sum of Squares\n\n*Time estimate: ~10mins*\n\n\nWe can try to put this observation in numbers. For this we work with the embeddings.\nWe want to calculate the centroid of each group, which is the average of the 49 embeddings of the group. As each embedding vector has a dimension of 512, the centroid will also have this dimension.\n\nNow we can calculate how far away the observations $x$ of each group $S_i$ are from the centroid $\\mu_i$. This concept is known as Within Sum of Squares (WSS) from cluster analysis.\n\n\\begin{equation}\n\\text{WSS} = \\sum_{x\\in S_i} ||x - \\mu_i||^2\n\\end{equation}\n\nwhere $|| \\cdot ||$ is the Euclidean norm.\n\nThe Within Sum of Squares (WSS) is a number which measures this variability of a group in the embedding space. If all embeddings of one group were very close to each other, the WSS would be very small. In our case we see that the WSS for the black females is much smaller than for the white females. This means that it is much harder for the model to distinguish two black females than to distinguish two white females. The WSS complements the observation from the distance matrix, where we observed overall smaller pairwise distances between black females.\n\n\n```python\n# @title Function to calculate WSS\n\ndef wss(group):\n \"\"\"\n This function returns the sum of squared distances of the N vectors of a\n group tensor (N x K) to its centroid (1 x K).\n\n Args:\n group: A image_count x embedding_size tensor\n\n Returns:\n sum_sq: A 1x1 tensor with the sum of squared distances.\n\n Hints:\n - to calculate the centroid, torch.mean() will be of use.\n - We need the mean of the N=49 observations. If our input tensor is of size\n N x K, we expect the centroid to be of dimensions 1 x K.\n Use the axis argument within torch.mean\n \"\"\"\n\n centroid = torch.mean(group, axis=0)\n distance = torch.linalg.norm(group - centroid.view(1, -1), axis=1)\n sum_sq = torch.sum(distance**2)\n return sum_sq\n```\n\n\n```python\n# @markdown Let's calculate the WSS for the two groups of our example.\n\nprint(f\"Black female embedding WSS: {np.round(wss(black_female_embeddings).item(), 2)}\")\nprint(f\"White female embedding WSS: {np.round(wss(white_female_embeddings).item(), 2)}\")\n```\n\n---\n# Summary\n\nIn this tutorial we have learned how to apply a modern convnet in real application such as facial recognition. However, as the state-of-the-art tools for facial recognition are trained mostly with caucasian faces, they fail or they perform much worst when they have to deal with faces from other races.\n", "meta": {"hexsha": "bc6dd223b46392e00d230afce64dd3175d0b7d98", "size": 817319, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_stars_repo_name": "eduardojdiniz/course-content-dl", "max_stars_repo_head_hexsha": "8d66641683651bce7b0179b6d890aef5a048a8b9", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_issues_repo_name": "eduardojdiniz/course-content-dl", "max_issues_repo_head_hexsha": "8d66641683651bce7b0179b6d890aef5a048a8b9", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_forks_repo_name": "eduardojdiniz/course-content-dl", "max_forks_repo_head_hexsha": "8d66641683651bce7b0179b6d890aef5a048a8b9", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 738.986437613, "max_line_length": 389088, "alphanum_fraction": 0.9460235233, "converted": true, "num_tokens": 5440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.19654140123347116}} {"text": "```python\n%matplotlib notebook\n%matplotlib inline\nimport math\nimport matplotlib.pyplot as plt\n\n```\n\n# Nuclear Fuel Resources, Mining, and Milling\n\n**Mining:** Nuclear fuel starts as natural uranium or thorium deposits in the earth. This material can be mined from the ground or even extracted from the sea. \n\n**Milling:** and other chemical and physical processes then follow in order to produce a uniform, concentrated material. In the case of Uranium, the product is called 'yellowcake'.\n\n## Learning Objectives\n\nThis lesson should equip you to:\n\n- Describe the extent, geography, and characteristics of uranium and thorium resources.\n- Understand various methods of prospecting.\n- Differentiate various methods for uranium extraction.\n- Model the economic relationship between uranium resources and extraction price.\n- Apply decay energy calculations to the Radon decay chain.\n- Evaluate the radiation danger associated with uranium mining. \n- Calculate radition exposure for mine workers.\n- Understand the process in milling operations.\n- Recognize the chemical form of yellowcake and its role in the fuel cycle.\n\n\n\n# Uranium Resources\n\nThere are important distinctions between production, supply, known reserves, and estimated resources. The book makes the distinction, further, among \"probable,\" \"possible,\" and \"speculative\" resources. \n\n\n\n## Geography of Uranium Resources\n\n\n\n\n\n| Mine | Country | Main owner | Type | Production (tU) | % of world |\n| ------------ |:-------------:|:-------------:|:-------------:|:-------------:|:-------------:|\n| McArthur River | Canada | Cameco | underground | 7356 | 13 |\n| Tortkuduk & Moinkum | Kazakhstan | Katco JV/Areva, Kazatomprom | ISL | 4322 | 8 |\n| Olympic Dam | Australia | BHP Billiton | by-product/underground | 3351 | 6 |\n| SOMAIR | Niger | Areva | open pit | 2331 | 5 |\n| Budenovskoye 2 | Kazakhstan | Karatau JV/Kazatomprom, Uranium One | ISL | 2084 | 4 |\n| South Inkai | Kazakhstan | Betpak Dala JV/Uranium One, Kazatomprom | ISL | 2002 | 4 |\n| Priagunsky | Russia | ARMZ | underground | 1970 | 4 |\n| Langer Heinrich | Namibia | Paladin | open pit | 1947 | 4 |\n| Inkai | Kazakhstan | Inkai JV/Cameco, Kazatomprom | ISL | 1922 | 3 |\n| Central Mynkuduk | Kazakhstan | JSC Ken Dala, Kazatomprom | ISL | 1790 | 3 |\n| Top 10 total | | | | 29,075 | 54% |\n
[Source: WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/mining-of-uranium/uranium-mining-overview.aspx)
\n\n## Geology of Uranium Resources\n\n\n### Grades of Uranium Ore\nUranium deposits are found in different \"grades\" of ore. The \"grade\" is the mass percentage of the rock that is made up of elemental uranium. \n\n| Ore Grade | PPM |\n| ------------- |:-------------:|\n| Very high-grade ore (Canada) – 20% U\t| 200,000 ppm U\n| High-grade ore – 2% U,\t| 20,000 ppm U |\n| Low-grade ore – 0.1% U, |\t1,000 ppm U |\n| Very low-grade ore* (Namibia) – 0.01% U\t| 100 ppm U |\n| Granite\t| 3-5 ppm U |\n| Sedimentary rock\t| 2-3 ppm U |\n| Earth's continental crust (av)\t| 2.8 ppm U |\n| Seawater |\t0.003 ppm U |\n
[Source: WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/uranium-resources/supply-of-uranium.aspx)
\n\n\n```python\ndef U(U_0, z):\n \"\"\"Uranium concentration as a function of depth.\n :param U_0: concentration at surface in ppm\n :param z: depth\n :return c: concentration at depth z\"\"\"\n c = U_0*math.exp(-z/6300)\n return c\n```\n\n\n```python\nb = range(1, 1000, 5)\nto_plot = [U(2.8, z) for z in b]\n```\n\n\n```python\nplt.plot(to_plot)\nplt.title('Uranium Concentration as a Function of Depth')\nplt.ylabel('Uranium Concentration (ppm)')\nplt.xlabel('Depth [m]')\n```\n\n## Extent of Uranium Resources\n\nUranium production was at one point far ahead of demand. \nRecently, mining follows demand a bit more closely.\n\n\n\nAnd, we know that there is a lot more out there.\n\n| Nation | tonnes U | percentage of world |\n| ------------ |:-------------:|:-------------:|\n| Australia | 1,706,100 | 29% |\n| Kazakhstan | 679,300 | 12% |\n| Russia | 505,900 | 9% |\n| Canada | 493,900 | 8% |\n| Niger | 404,900 | 7% |\n| Namibia | 382,800 | 6% |\n| South Africa | 338,100 | 6% |\n| Brazil | 276,100 | 5% |\n| USA | 207,400 | 4% |\n| China | 199,100 | 4% |\n| Mongolia | 141,500 | 2% |\n| Ukraine | 117,700 | 2% |\n| Uzbekistan | 91,300 | 2% |\n| Botswana | 68,800 | 1% |\n| Tanzania | 58,500 | 1% |\n| Jordan | 40,000 | 1% |\n| Other | 191,500 | 3% |\n| World total | 5,902,900 | 100% |\n
[Reasonably Assured Resources, Source: WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/mining-of-uranium/world-uranium-mining-production.aspx)
\n\n## Prospecting\n\n- Geologic Study \n\n\n\n- Botanical Study\n\n\n\n- Airborne Study \n\n\n\n\n- Surface Study\n\n\n- Well Logging\n\n\n\n\n\n### Gamma Decay Review\n\nRadiometric measurements are typically taken from the air by a gamma ray detector.\n\n\n\n\n\n\n\n\n\n### Discussion: What naturally occurring elements have reasonably detectable gamma decays?\n\n\n \n\n\n \n\n\n\n## Open Pit Mining\n\n\n\n## Underground Mining\n\n\n
Mi Vida uranium mine in Moab, UT
\n\n### Radon\n\n\n\n### Discussion: If the daughters of radon are solids, how do they get into your lungs?\n\n\n\n\n### Discussion: Given this, what methods, in addition to moving the air around, might mitigate recieved dose?\n\n\n\n\n \n\n\n \n\n### Working Level\n\nThe working level is a unit of measurement for radon exposure. Alpha particles from radon and its progeny (daughters) are ionizing radiation and damage the DNA of the cells of your lungs, sometimes leading to cancer. \n\nThe radon progeny in equilibrium with $100 \\frac{pCi}{L}$ radon gas at a mine would typically release approximately 130,000 MeV alpha energy in decay, so the WL was defined as:\n\n\\begin{align}\n1 WL &= 130,000\\frac{MeV}{L} \\mbox{ alpha energy from radon + daughters}\\\\\n &= 20.8 \\frac{\\mu J}{m^3} \\mbox{ alpha energy from radon + daughters}\\\\\n\\end{align}\n\nThe nominal working hours per month assume 40 hours per week and 4.25 weeks per month. Accordingly, the working level month (WLM) was introduced:\n\n\\begin{align}\nWLM &= \\mbox{Working Level Month}\\\\\n &= \\mbox{1 WL exposure for 170 hours}\\\\\n1 WLM &= 170 x 20.8 = 3.54 \\frac{\\mu J h}{m^3}\\\\ \n\\end{align}\n\nNote that for conversion's sake:\n\n\\begin{align}\n17,000\\frac{pCi h}{L} &= 1 WLM\\\\\n1\\frac{pCi h}{L} &= 59 \\mu WLM\n\\end{align}\n\n\n```python\nr = 2.6e5 # energy from alphas emitted by radon + progeny [MeV/L] \nh = 60*12 # working hours\nwl = 1.3e5 # worker level in [MeV/L]\n\nprint((r/wl), \" working level \")\nprint((r/wl)*(h/170), \" working level months\")\n```\n\n 2.0 working level \n 8.470588235294118 working level months\n\n\n## Energy vs. Rate of decays \n\nRadiation energy is measured in **electronvolts (eV), megaelectronvolts (MeV)** for convenience, and **Joules (J)**:\n\n\\begin{align}\n1 J &= 6.242\\times10^{12} MeV\\\\\n1 \\frac{J}{s} &= 1 W\\\\\n\\end{align}\n\n**Becquerels (Bq)** or **Curies (Ci)** measure the rate of decays from a source : \n\\begin{align}\n1 Bq &= \\frac{\\mbox{emission}}{s}\\\\\n1 Ci &= 37 GBq\\\\ \n &= 37000 MBq\\\\\n1 Bq &= 27 pCi\\\\\n &= 27\\times10^{-12}Ci\\\\\n\\end{align}\n\n### Discussion: What is another name for this rate?\n\n\nTo convert between these, one must consider the energy per emission. \n\n### Calculation of Alpha Decay Energy\n\nCalculate the energy Q, in MeV, released during the alpha \ndecay $^{ZZZ}I_i \\stackrel{\\alpha}{\\longrightarrow} {^{YYY}}I_d$:\n\n\\begin{align}\n m_i &= \\mbox{initial mass }[u]\\nonumber\\\\\n m_f &= \\mbox{final mass }[u]\\nonumber\\\\\n &= \\mbox{mass of daughter + mass of alpha }[u]\\nonumber\\\\\n &= m_d + m_{\\alpha}\\\\\n m_d &= \\mbox{mass of daughter}[u]\\nonumber\\\\\n m_{\\alpha} &= \\mbox{mass of alpha }[u]\\nonumber\\\\\n Q\\left[\\frac{u\\cdot m^2}{s^2}\\right] &= m_ic^2 - m_fc^2\\nonumber\\\\\n\\end{align}\n\n\nThis equation will be used for all alpha decay calculations. These \nwill only vary in the masses. Masses, however, are typically expressed in units of amu (or, u).\n\n\n\\begin{align*}\n m_{\\alpha} &= m_{\\alpha} [u]\\\\\n m_i &= m_{I_i} [u]\\\\\n m_d &= m_{I_f} [u]\\\\\n Q[MeV] &= (m_i - m_f)c^2\\left(931.494 \\frac{MeV}{c^2u}\\right)\\\\ \n &= (m_i - m_d - m_{\\alpha})\\left(931.494\\right)\\\\\n Q[MeV] &= 931.494\\left(m_i - m_d - m_{\\alpha}\\right)\\\\ \n\\end{align*}\n\nThe energy released in alpha decay is converted into kinetic energy of the two final particles (daughter and alpha). Recall that kinetic energy is $\\frac{1}{2}mv^2$, so if the energy is split, the speed of the alpha particle will be significantly higher than the speed of the (much larger, typically) daughter particle.\n\n\n### A Note on Radiation Weighting Factors\n\nThe conversion from energy to biological effect is complex. First, one must calculate absorbed dose $D_T$, the amount of energy from ionizing radiation actually deposited in tissue. \n\n\\begin{align}\nD_T = \\frac{\\Delta \\epsilon}{\\Delta m}\\\\\n\\Delta \\epsilon = \\mbox{ energy deposited }\\\\\n\\Delta m = \\mbox{ mass of tissue }\n\\end{align}\n\n\n```python\ndef absorbed_dose(del_eps, del_m):\n return del_eps/del_m\n```\n\nThe biological effect is related to the dose and depends on the nature of the\nradiation.\n\n\n\n\nThe ICRP has suggested a quantifying factor that translates from energy to dose. \n\n- (1991). \"1990 Recommendations of the International Commission on Radiological Protection\". Annals of the ICRP 21 (1-3). Retrieved on 17 May 2012.\n- (2007). \"The 2007 Recommendations of the International Commission on Radiological Protection\". Annals of the ICRP 37 (2-4). Retrieved on 17 May 2012.\n\n| Radiation | Radiation Energy Weighting Factor WR (formerly Q) |\n|:-----------:|:-----------------------------------------------------------:|\n| x-rays, gammas, betas, muons | $1$ |\n| neutrons (< 1 MeV) | $2.5 + 18.2\\cdot e-\\frac{[ln(E)]^2}{6}$ |\n| neutrons (1 - 50 MeV) | $5.0 + 17.0\\cdot e-\\frac{[ln(2\\cdot E)]^2}{6}$ |\n| neutrons (> 50 MeV) | $2.5 + 3.25\\cdot e-\\frac{[ln(0.04\\cdot E)]^2}{6}$ |\n| protons, charged pions | 2 |\n| alphas, fission products, heavy nuclei | 20 |\n\n\n\n\n\n\nEpidemiological studies vary on the factors for both dose conversion and risk from dose from various sources. There is a nice recent study on what we know. [http://www.ncbi.nlm.nih.gov/pubmed/27334644](http://www.ncbi.nlm.nih.gov/pubmed/27334644)\n\n\n\n\n\n\n\n### Discussion: What are the key takeaways from this review of Underground Mining ?\n\n- .Radon gas is a big issue, so you have to be careful if you're a miner. \n- .Have a very dense lung... \n- .wear a mask\n- .keep in mind of the countries with thier underground mining and resources.\n- WL & WLM\n- you can calculate the energy of the alphas\n\n\n\n## In Situ Leaching\n\n\n\n\nFrom [WNA](http://www.world-nuclear.org/information-library/nuclear-fuel-cycle/mining-of-uranium/in-situ-leach-mining-of-uranium.aspx):\n\n> In 2013, 47% of world uranium mined was from ISL operations. Most uranium mining in the USA, Kazakhstan and Uzbekistan is now by in situ leach methods, also known as in situ recovery (ISR).\n\n\n\n### Discussion: What are some benefits and drawbacks of in situ leaching?\n\n\n### Uranium in Seawater\n\nGreat presentation by expert professor Erich Schneider. [http://www-pub.iaea.org/iaeameetings/cn216pn/Thursday/Session13/180-Schneider.pdf](http://www-pub.iaea.org/iaeameetings/cn216pn/Thursday/Session13/180-Schneider.pdf) .\n\n---\n\n\n\n---\n\n\n\n---\n\n\n\n---\n\n\\begin{align}\ny &= \\frac{\\beta_{max} t}{K_D + t}\\\\\ny &= \\mbox{uranium uptake} \\left[\\frac{g_U}{kg_{ads}}\\right]\\\\\n\\beta_{max} &= \\mbox{saturation capacity } \\left[\\frac{g_U}{kg_{ads}}\\right]\\\\\nK_D &= \\mbox{half saturation time }[d]\\\\\nt &= \\mbox{exposure time }[d]\\\\\n\\end{align}\n\n\n```python\ndef uptake(beta_max, k_d, t):\n return beta_max*t/(k_d+t)\n\nbeta_max = 48.9\nk_d = 28.0\n\nimport numpy as np\ny = np.arange(0.0,100.0)\n\nfor t in range(0, 100):\n y[t] = uptake(beta_max, k_d, t)\n \nplt.plot(y)\nplt.ylabel(r'Uranium uptake $\\left[\\frac{g_U}{kg_{ads}}\\right]$', fontsize=20)\nplt.xlabel(r'Time $\\left[d\\right]$', fontsize=20)\n\n\n```\n\n\n## Thorium Resources\n\n\n\n\n[Source: http://minerals.usgs.gov/minerals/pubs/commodity/thorium/690397.pdf](http://minerals.usgs.gov/minerals/pubs/commodity/thorium/690397.pdf): Where's Turkey?\n\n\n\n\n\n\n\n\n\nThis reading from the black monazite rich beach in Brazil, is in units of $\\frac{\\mu Sv}{h}$. Typical background radiation is around $0.3\\frac{\\mu Sv}{h}$.\n\n## Milling\n\nMilling is the process of concentrating uranium ore into a substance known as yellow cake, concentrated $U_3O_8$. \n\n\n\n\n\n\nFor open pit or underground mining, the first step is to crush the material. The second step is to dissolve out the uranium. This is not a pretty industrial process.\n\n\n\n\nHowever, for ISL, the material is already in liquid form (because the leaching chemistry already occurred underground.) \n\n\n\n\nISL Ion Exchange uses resin beads to separate the $U_3O_8$.\n\n\n\n\nAs an aside, united states mining & milling has declined. \n\n\n\n## Wrap-up\n\n- There is a great deal of both uranium and thorium available, depending on the price.\n- Certain nations have a great deal more resources than other nations (see: Canada, Khazakstan, Australia)\n- Prospecting uses biology, geology, radiology, and electromagnetism to identify uranium and thorium resources\n- Biological prospecting relies on indicator plants which seek out areas rich in indicative minerals\n- Aerial prospecting relies on gamma spectrometers and magnetometers\n- Surface prostpecting relies on handheld detectors\n- Well logging maps the subsurface vertically with detection in wells\n- Uranium can be extracted from the ground with open pit mines, underground mines, in situ leaching, and even seawater extraction. \n- Prospecting for mineral resources and the ability to extract those resources respond to market price.\n- The Radon decay chain is responsible for radiation dangers to mine workers and is measured in Working Level or Working Level Months.\n- The energy of radon daughter alphas can be calculated for each decay.\n- Radiation effects are expressed in many units and the weighting factors related to biological impacts are approximate and controversial.\n- Milling requires separation of the uranium via ion exchange with carbonates or acids. \n- The milling process associated with in situ leaching conducts chemistry underground and accordingly avoids tailings piles.\n- Concentrate, yellow, $U_3O_8$ is the results of milling operations and is known as 'yellowcake'.\n\n## References\n\nThis section was developed to complement Chapter 2 of [1]. You can find a video at [2].\n\n[1] N. Tsoulfanidis, The Nuclear Fuel Cycle. La Grange Park, Illinois, USA: American Nuclear Society, 2013.\n\n[2] The Heritage Foundation. Powering America: Uranium Mining and Milling. https://www.youtube.com/watch?v=oT2LHGG-9Ko\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "c91b0a5fba94aa06ac8128fbdba0b05e13d3a1bc", "size": 60282, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "mining-milling/mining-milling.ipynb", "max_stars_repo_name": "atomicaristides/NPRE412", "max_stars_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mining-milling/mining-milling.ipynb", "max_issues_repo_name": "atomicaristides/NPRE412", "max_issues_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mining-milling/mining-milling.ipynb", "max_forks_repo_name": "atomicaristides/NPRE412", "max_forks_repo_head_hexsha": "b2ae552303f3e4894628c8401d3bedd2db85a551", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.1440677966, "max_line_length": 16596, "alphanum_fraction": 0.7875651106, "converted": true, "num_tokens": 4238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.1957150135788278}} {"text": "\n# PHY321: Classical Mechanics 1\n\n \n**Solution Homework 7, due to March 22**\n\nDate: **Mar 24, 2021**\n\n### Introduction to homework 7\n\nIn this week's homework we will apply our insights about harmonic\noscillations and link this with our activity from the lecture on\nFriday March 12. The relevant material to survey is chapter 5 of Taylor.\n\nWe have also added an exercise (exercise 2) related to our discussion of two-body problems. \nThe relevant reading background for exercise 2 is sections 8.1-8.2 of Taylor.\n\n\n\n### Exercise 1 (80 pt), particle/object in a harmonic oscillator potential\n\nIn the midterm and in exercise 4 of homework 6, we looked at an\nobject/particle moving in a potential which resulted in harmonic\noscillations. The aim here is to summarize in more detail the\nmaterial from harmonic oscillations. See also the bonus exercise below\nhere (from the discussions of Friday March 12).\n\n\nRelevant reading here is Taylor chapter 5 and the lecture notes on oscillations. \n\nWe will consider a particle of mass $m$ moving in a one-dimensional potential,\n\n$$\nV(x)=k\\frac{x^2}{2},\n$$\n\nwhere $k$ is a parameter.\n\nWe will limit ourselves to a one-dimensional system. You will need to select values for the initial conditions and the various parameters $k$, $m$, $b$, $\\omega$ and $F_0$ discussed here.\n\n* 1a (20pt) Assume no driving force first and add a drag force $-bv$, where $v$ is the velocity. Find the forces acting on the object. Find the analytical solutions to the equations of motion. Discuss the three cases: **underdamping**, **critical damping** and **overdamping**.\n\nThe text here is taken from the lecture notes of week 9. We have made this text more extensive than needed. This is done for the sake of completeness.\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{2}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([2](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $\\exp{(rt)}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{7}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{8}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\n* 1b (5pt) Scale your equations of motion in terms of a dimensionless time $\\tau = \\omega_0 t$, where $t$ is time and $\\omega_0^2=k/m$ is the so-called natural frequency. \n\nTo scale the equations we start again with the full equation\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto6} \\tag{9}\n\\end{equation}\n$$\n\nWe divide by $m$ and get\n\n\n
\n\n$$\n\\begin{equation}\n\\ddot{x}+\\frac{b}{m}\\dot{x}+\\frac{k}{m}x=0.\n\\label{_auto7} \\tag{10}\n\\end{equation}\n$$\n\nDefining the natural frequency $\\omega_0^2=k/m$ we introduce a dimensionless time $\\tau = \\omega_0 t$ and replace $t$ with $\\tau$.\nThis leads to us rewriting\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2 x}{dt^2}+\\frac{b}{m}\\frac{dx}{dt}+\\frac{k}{m}x=0,\n\\label{_auto8} \\tag{11}\n\\end{equation}\n$$\n\nas\n\n\n
\n\n$$\n\\begin{equation}\n\\omega_0^2\\frac{d^2 x}{d\\tau^2}+\\frac{\\omega_0b}{m}\\frac{dx}{d\\tau}+\\omega_0^2x=0,\n\\label{_auto9} \\tag{12}\n\\end{equation}\n$$\n\nand dividing by $\\omega_0^2$ and defining $\\gamma = b/(2m\\omega_0)$ we have the final scaled equation\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2 x}{d\\tau^2}+2\\gamma\\frac{dx}{d\\tau}+x=0.\n\\label{_auto10} \\tag{13}\n\\end{equation}\n$$\n\nThis equation has dimension length only and time $\\tau$ is dimensionless. It means also that our solutions become now\n\nIn this case the variable $r$ becomes\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\gamma\\pm\\sqrt{\\gamma^2-1}.\n\\label{_auto11} \\tag{14}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1\\tau}+A_2e^{r_2\\tau},\n\\label{_auto12} \\tag{15}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nFor the roots listed above, $\\sqrt{\\gamma^2-1}$, will be\nimaginary if the damping is small and $\\gamma < 1$. In that case,\n$r$ is complex and the factor $\\exp{(rt)}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. For $\\gamma =1$, we have what we labeled as critical damping while for $\\gamma > 1$, we have over-critical damping.\n\nIn the codes below, we have implemented the dimensionless equations.\n\n\n\n* 1c (25pt) You can use your codes from either the first midterm or from homeworks 5 and/or 6. Study numerically the three cases from 1a, that is the underdamped motion, the critically damped one and finally the overdamped one. Compare your numerical results with the analytical ones from 1a. Discuss your results. You can use the Euler-Cromer method, or the Velocity-Verlet method or the Runge-Kutta methods discussed during the lectures, see for example . Alternatively, you could use the **odeint** solvers included functionality in Python, see . Give a short argument about the numerical algorithm you ended up using. \n\nWe have chosen to implement the Runge-Kutta4 method since this has a truncation error in terms of the step size $\\Delta t$ to the power of five. The codes are included after part 1d. \n\n\n\n* 1d (30pt) We add now a driving force $F=F_0\\cos{(\\omega t}$. Find the particular solution and its analytical solution. Include this force in your code (remember to scale the equations) and compare your numerical results with the analytical results. Discuss your results. How does the system evolve over time with a given frequency $\\omega$ for the driving force? Is energy conserved? If not, why? \n\nTo find a particular solution, one first guesses at the form,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{16}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$\n\nand rewrite the differential equation as\n\n\n
\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto13} \\tag{17}\n\\end{equation}\n$$\n\nOne can now use angle addition formulas to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$\n\nBoth the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$\n\nAfter dividing by $\\cos\\delta$, the lower expression leads to\n\n\n
\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto14} \\tag{18}\n\\end{equation}\n$$\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,\n\n$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$\n\nInserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{19}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$\n\nFor a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n\n\n\nLet us now for simplicty assume that our external force is given by\n\n$$\nF_{\\mathrm{ext}}(t) = F_0\\cos{(\\omega t)},\n$$\n\nwhere $F_0$ is a constant (what is its dimension?) and $\\omega$ is the frequency of the applied external driving force.\n**Small question:** would you expect energy to be conserved now?\n\n\nIntroducing the external force into our lovely differential equation\nand dividing by $m$ and introducing $\\omega_0^2=\\sqrt{k/m}$ we have\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =\\frac{F_0}{m}\\cos{(\\omega t)},\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$\nand a dimensionless frequency $\\tilde{\\omega}=\\omega/\\omega_0$. We have then\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\frac{F_0}{m\\omega_0^2}\\cos{(\\tilde{\\omega}\\tau)},\n$$\n\nIntroducing a new amplitude $\\tilde{F} =F_0/(m\\omega_0^2)$ (check dimensionality again) we have\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nOur final step, as we did in the case of various types of damping, is\nto define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nEenergy is not conserved since we have a time and velocity dependent total net force acting on the system.\n\nNote that here the forward Euler method does not know the specific force function to be called.\nIt receives just an input the name. We can easily change the force by adding another function.\n\n\n```python\ndef ForwardEuler(v,x,t,n,Force):\n for i in range(n-1):\n v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n```\n\n\n```python\ndef SpringForce(v,x,t):\n# note here that we have divided by mass and we return the acceleration\n return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)\n```\n\nIt is easy to add a new method like the Euler-Cromer\n\n\n```python\ndef ForwardEulerCromer(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n```\n\nand the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces))\n\n\n```python\ndef VelocityVerlet(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]+0.5*a*DeltaT*DeltaT\n anew = Force(v[i],x[i+1],t[i+1])\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK2(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Final result\n x[i+1] = x[i]+k2x\n v[i+1] = v[i]+k2v\n\t t[i+1] = t[i]+DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK4(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k3\n vv = v[i]+k2v*0.5\n xx = x[i]+k2x*0.5\n k3x = DeltaT*vv\n k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k4\n vv = v[i]+k3v\n xx = x[i]+k3x\n k4x = DeltaT*vv\n k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)\n# Final result\n x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.\n v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.\n t[i+1] = t[i] + DeltaT\n```\n\nThe code below uses the Runge-Kutta4 methods.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in dimensionless time\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions (can change to more than one dim)\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.2\nOmegatilde = 0.5\nFtilde = 1.0\n# Start integrating using Euler's method\n# Note that we define the force function as a SpringForce\nRK4(v,x,t,n,SpringForce)\n\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockRK4\")\nplt.show()\n```\n\n### Exercise 2 (20pt), Center-of-Mass and Relative Coordinates and Reference Frames\n\nWe define the two-body center-of-mass coordinate and relative coordinate by expressing the trajectories for\n$\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ into the center-of-mass coordinate\n$\\boldsymbol{R}_{\\rm cm}$\n\n$$\n\\boldsymbol{R}_{\\rm cm}\\equiv\\frac{m_1\\boldsymbol{r}_1+m_2\\boldsymbol{r}_2}{m_1+m_2},\n$$\n\nand the relative coordinate\n\n$$\n\\boldsymbol{r}\\equiv\\boldsymbol{r}_1-\\boldsymbol{r_2}.\n$$\n\nHere, we assume the two particles interact only with one another, so $\\boldsymbol{F}_{12}=-\\boldsymbol{F}_{21}$ (where $\\boldsymbol{F}_{ij}$ is the force on $i$ due to $j$.\n\n* 2a (5pt) Show that the equations of motion then become $\\ddot{\\boldsymbol{R}}_{\\rm cm}=0$ and $\\mu\\ddot{\\boldsymbol{r}}=\\boldsymbol{F}_{12}$, with the reduced mass $\\mu=m_1m_2/(m_1+m_2)$.\n\nThe first expression simply states that the center of mass coordinate $\\boldsymbol{R}_{\\rm cm}$ moves at a fixed velocity. The second expression can be rewritten in terms of the reduced mass $\\mu$.\n\n* 2b (5pt) Show that the linear momenta for the center-of-mass $\\boldsymbol{P}$ motion and the relative motion $\\boldsymbol{q}$ are given by $\\boldsymbol{P}=M\\dot{\\boldsymbol{R}}_{\\rm cm}$ with $M=m_1+m_2$ and $\\boldsymbol{q}=\\mu\\dot{\\boldsymbol{r}}$. The linear momentum of the relative motion is defined $\\boldsymbol{q} = (m_2\\boldsymbol{p}_1-m_1\\boldsymbol{p}_2)/(m_1+m_2)$.\n\n* 2c (5pt) Show then that the kinetic energy for two objects can then be written as\n\n$$\nK=\\frac{P^2}{2M}+\\frac{q^2}{2\\mu}.\n$$\n\n* 2d (5pt) Show that the total angular momentum for two-particles in the center-of-mass frame $\\boldsymbol{R}=0$, is given by\n\n$$\n\\boldsymbol{L}=\\boldsymbol{r}\\times \\mu\\dot{\\boldsymbol{r}}.\n$$\n", "meta": {"hexsha": "96051b823b9d96b8bb100dd1104a719e27418354", "size": 53030, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw7-checkpoint.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw7-checkpoint.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/src/Homeworks/Misc/.ipynb_checkpoints/solutionhw7-checkpoint.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 46.5583845478, "max_line_length": 18664, "alphanum_fraction": 0.6922308127, "converted": true, "num_tokens": 6759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.19335156022987357}} {"text": "```python\nfrom IPython.display import Image\nImage('../../Python_probability_statistics_machine_learning_2E.png',width=200)\n```\n\n# Conditional Expectation as Projection\n\nNow that we understand projection\nmethods geometrically, we can apply\nthem to conditional probability. This is the\n*key* concept that ties\nprobability to geometry, optimization, and linear\nalgebra. \n\n### Inner Product for Random Variables\n\n From our previous work on\nprojection for vectors in\n$\\mathbb{R}^n$, we have a good geometric grasp on how\nprojection is related to\nMinimum Mean Squared Error (MMSE). By one abstract\nstep, we can carry\nall of our geometric interpretations to the space of random\nvariables.\nFor example, we previously noted that at the point of projection, we\nhad the\nfollowing orthogonal (i.e., perpendicular vectors) condition,\n\n$$\n( \\mathbf{y} - \\mathbf{v}_{opt} )^T \\mathbf{v} = 0\n$$\n\n which by noting the inner product slightly more abstractly as\n$\\langle\\mathbf{x},\\mathbf{y} \\rangle = \\mathbf{x}^T \\mathbf{y}$, we can\nexpress\nas\n\n$$\n\\langle \\mathbf{y} - \\mathbf{v}_{opt},\\mathbf{v} \\rangle = 0\n$$\n\n and by defining the inner product for the random variables\n$X$ and $Y$ as\n\n$$\n\\langle X,Y \\rangle = \\mathbb{E}(X Y)\n$$\n\n we have the same relationship:\n\n$$\n\\langle X-h_{opt}(Y),Y \\rangle = 0\n$$\n\n which holds not for vectors in $\\mathbb{R}^n$, but for random\nvariables $X$ and\n$Y$ and functions of those random variables. Exactly why this\nis true is\ntechnical, but it turns out that one can build up the *entire theory\nof\nprobability* this way [[edward1987radically]](#edward1987radically), by using\nthe expectation as\nan inner product.\n\nFurthermore, by abstracting out the inner\nproduct concept, we have connected\nminimum-mean-squared-error (MMSE)\noptimization problems, geometry, and random\nvariables. That's a lot of mileage\nto get a out of an abstraction and it\nenables us to shift between these\ninterpretations to address real problems.\nSoon, we'll do this with some\nexamples, but first we collect the most important\nresult that flows naturally\nfrom this abstraction.\n\n### Conditional Expectation as Projection\n\nThe\nconditional expectation is the minimum mean squared error (MMSE) solution\nto the\nfollowing problem [^proof]:\n\n\n$$ \\min_h \\int_{\\mathbb{R}^2} (x - h(y) )^2 f_{X,Y}(x,y) dx dy $$\n\nwith the minimizing $h_{opt}(Y) $ as\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n[^proof]: See appendix for proof using the Cauchy-Schwarz inequality.\n\n which is\nanother way of saying that among all possible functions\n$h(Y)$, the one that\nminimizes the MSE is $ \\mathbb{E}(X|Y)$. From our previous discussion on\nprojection, we noted that\nthese MMSE solutions can be thought of as projections\nonto a subspace that\ncharacterizes $Y$. For example, we previously noted that at\nthe point of\nprojection, we have perpendicular terms,\n\n\n
\n\n$$\n\\begin{equation}\n\\langle X-h_{opt}(Y),Y \\rangle = 0\n\\end{equation}\n\\label{eq:ortho} \\tag{1}\n$$\n\n but since we know that the MMSE solution\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n we have by direct substitution,\n\n\n
\n\n$$\n\\begin{equation}\n\\mathbb{E}(X-\\mathbb{E}(X|Y),Y) = 0\n\\end{equation}\n\\label{eq:ortho_001} \\tag{2}\n$$\n\n That last step seems pretty innocuous, but it ties MMSE to\nconditional\nexpectation to the inner project abstraction, and in so doing,\nreveals the\nconditional expectation to be a projection operator for random\nvariables. Before\nwe develop this further, let's grab some quick dividends.\nFrom the previous\nequation, by linearity of the expectation, we obtain,\n\n$$\n\\mathbb{E}(X Y) = \\mathbb{E}(Y \\mathbb{E}(X|Y))\n$$\n\n which is the so-called *tower property* of the expectation. Note that\nwe could\nhave found this by using the formal definition of conditional\nexpectation,\n\n$$\n\\mathbb{E}(X|Y) = \\int_{\\mathbb{R}^2} x \\frac{f_{X,Y}(x,y)}{f_Y(y)} dx dy\n$$\n\n and brute-force direct integration,\n\n$$\n\\begin{align*}\n\\mathbb{E}(Y \\mathbb{E}(X|Y)) &= \\int_{\\mathbb{R}} y\n\\int_{\\mathbb{R}} x \\frac{f_{X,Y}(x,y)}{f_Y(y)} f_Y(y) dx dy \\\\\\\n&=\\int_{\\mathbb{R}^2} x y f_{X,Y}(x,y) dx dy \\\\\\\n&=\\mathbb{E}( X Y) \n\\end{align*}\n$$\n\n which is not very geometrically intuitive. This lack of geometric\nintuition\nmakes it hard to apply these concepts and keep track of these\nrelationships.\nWe can keep pursuing this analogy and obtain the length of the error term \nfrom\nthe orthogonality property of the MMSE solution as,\n\n$$\n\\langle X-h_{opt}(Y),X-h_{opt}(Y)\\rangle = \\langle X,X \\rangle - \\langle\nh_{opt}(Y),h_{opt}(Y) \\rangle\n$$\n\n and then by substituting all the notation we obtain\n\n$$\n\\mathbb{E}(X- \\mathbb{E}(X|Y))^2 = \\mathbb{E}(X)^2 -\n\\mathbb{E}(\\mathbb{E}(X|Y) )^2\n$$\n\n which would be tough to compute by direct integration. \n\nTo formally establish\nthat $\\mathbb{E}(X|Y)$ *is* in fact *a projection operator* we\nneed to show\nidempotency. Recall that idempotency means that once we project\nsomething onto\na subspace, further projections do nothing. In the space of\nrandom variables,\n$\\mathbb{E}(X|\\cdot$) is the idempotent projection as we can\nshow by noting that\n\n$$\nh_{opt} = \\mathbb{E}(X|Y)\n$$\n\n is purely a function of $Y$, so that\n\n$$\n\\mathbb{E}(h_{opt}(Y)|Y) = h_{opt}(Y)\n$$\n\n because $Y$ is fixed, this verifies idempotency. Thus, conditional\nexpectation\nis the corresponding projection operator for random variables. We\ncan continue\nto carry over our geometric interpretations of projections for\nvectors\n($\\mathbf{v}$) into random variables ($X$). With this important\nresult, let's\nconsider some examples of conditional expectations obtained by\nusing brute force\nto find the optimal MMSE function $h_{opt}$ as well as by\nusing our new\nperspective on conditional expectation.\n\n**Example.** Suppose we have a random\nvariable, $X$, then what constant is closest to $X$ in\nthe sense of the mean-\nsquared-error (MSE)? In other words, which $c \\in\n\\mathbb{R}$ minimizes the\nfollowing mean squared error:\n\n$$\n\\mbox{MSE} = \\mathbb{E}( X - c )^2\n$$\n\n we can work this out many ways. First, using calculus-based optimization,\n\n$$\n\\mathbb{E}(X-c)^2=\\mathbb{E}(c^2-2 c X + X^2)=c^2-2 c \\mathbb{E}(X) +\n\\mathbb{E}(X^2)\n$$\n\n and then take the first derivative with respect to $c$ and solve:\n\n$$\nc_{opt}=\\mathbb{E}(X)\n$$\n\n Remember that $X$ may potentially take on many values, but this says\nthat the\nclosest number to $X$ in the MSE sense is $\\mathbb{E}(X)$. This is\nintuitively\npleasing. Coming at this same problem using our inner product,\nfrom Equation\n[2](#eq:ortho_001) we know that at the point of projection\n\n$$\n\\mathbb{E}((X-c_{opt}) 1) = 0\n$$\n\n where the $1$ represents the space of constants \nwe are projecting onto. By\nlinearity of the expectation, gives\n\n$$\nc_{opt}=\\mathbb{E}(X)\n$$\n\n Using the projection approach, because $\\mathbb{E}(X|Y)$ is\nthe projection\noperator, with $Y=\\Omega$ (the entire underlying\nprobability space), we have,\nusing the definition of conditional\nexpectation:\n\n$$\n\\mathbb{E}(X|Y=\\Omega) = \\mathbb{E}(X)\n$$\n\n This is because of the subtle fact that a random variable over the entire\n$\\Omega$ space can only be a constant. Thus, we just worked the same problem\nthree ways (optimization, orthogonal inner products, projection).\n\n**Example.**\nLet's consider the following example with probability density\n$f_{X,Y}= x + y $\nwhere $(x,y) \\in [0,1]^2$ and compute the conditional\nexpectation straight from\nthe definition:\n\n$$\n\\mathbb{ E}(X|Y) = \\int_0^1 x \\frac{f_{X,Y}(x,y)}{f_Y(y)} dx= \\int_0^1 x\n\\frac{x+y}{y+1/2} dx =\\frac{3 y + 2}{6 y + 3}\n$$\n\n That was pretty easy because the density function was so simple. Now,\nlet's do\nit the hard way by going directly for the MMSE solution $h(Y)$. Then,\n\n$$\n\\begin{align*}\n\\mbox{ MSE } &= \\underset{h}\\min \\int_0^1\\int_0^1 (x - h(y)\n)^2 f_{X,Y}(x,y)dx dy \\\\\\\n &= \\underset{h}\\min \\int_0^1 y h^2 {\\left\n(y \\right )} - y h{\\left (y \\right )} + \\frac{1}{3} y + \\frac{1}{2} h^{2}{\\left\n(y \\right )} - \\frac{2}{3} h{\\left (y \\right )} + \\frac{1}{4} dy\n\\end{align*}\n$$\n\n Now we have to find a function $h$ that is going to minimize this.\nSolving for\na function, as opposed to solving for a number, is generally very,\nvery hard,\nbut because we are integrating over a finite interval, we can use\nthe Euler-\nLagrange method from variational calculus to take the derivative of\nthe\nintegrand with respect to the function $h(y)$ and set it to zero. Using\nEuler-\nLagrange methods, we obtain the following result,\n\n$$\n2 y h{\\left (y \\right )} - y + h{\\left (y \\right )} - \\frac{2}{3} =0\n$$\n\n Solving this gives\n\n$$\nh_{opt}(y)= \\frac{3 y + 2}{6 y + 3}\n$$\n\n which is what we obtained before. Finally, we can solve this\nusing our inner\nproduct in Equation [1](#eq:ortho) as\n\n$$\n\\mathbb{E}((X-h(Y)) Y)=0\n$$\n\n Writing this out gives,\n\n$$\n\\int_0^1\\int_0^1 (x-h(y))y(x+y) dx dy = \\int_0^1\\frac{1}{6}y(-3(2 y+1) h(y)+3\ny+2) dy=0\n$$\n\n and the integrand must be zero,\n\n$$\n2 y + 3 y^2 - 3 y h(y) - 6 y^2 h(y)=0\n$$\n\n and solving this for $h(y)$ gives the same solution:\n\n$$\nh_{opt}(y)= \\frac{3 y + 2}{6 y + 3}\n$$\n\n Thus, doing it by the brute force integration from the definition,\noptimization, or inner product gives us the same answer; but, in general, no\nmethod is necessarily easiest because they both involve potentially difficult\nor\nimpossible integration, optimization, or functional equation solving. The\npoint\nis that now that we have a deep toolbox, we can pick and choose which\ntools we\nwant to apply for different problems.\n\nBefore we leave this example, let's use\nSympy to verify the length of the error\nfunction we found earlier for this\nexample:\n\n$$\n\\mathbb{E}(X-\\mathbb{E}(X|Y))^2=\\mathbb{E}(X)^2-\\mathbb{E}(\\mathbb{E}(X|Y))^2\n$$\n\n that is based on the Pythagorean theorem. First, we \nneed to compute the\nmarginal densities,\n\n\n```python\nfrom sympy.abc import y,x\nfrom sympy import integrate, simplify\nfxy = x + y # joint density\nfy = integrate(fxy,(x,0,1)) # marginal density\nfx = integrate(fxy,(y,0,1)) # marginal density\n```\n\nThen, we need to write out the conditional expectation,\n\n\n```python\nEXY = (3*y+2)/(6*y+3) # conditional expectation\n```\n\nNext, we can compute the left side, $\\mathbb{E}(X-\\mathbb{E}(X|Y))^2$,\nas the\nfollowing,\n\n\n```python\n# from the definition\nLHS=integrate((x-EXY)**2*fxy,(x,0,1),(y,0,1)) \nLHS # left-hand-side\n```\n\n\n\n\n$\\displaystyle \\frac{1}{12} - \\frac{\\log{\\left(3 \\right)}}{144}$\n\n\n\nWe can similarly compute the right side,\n$\\mathbb{E}(X)^2-\\mathbb{E}(\\mathbb{E}(X|Y))^2$,\nas the following,\n\n\n```python\n# using Pythagorean theorem\nRHS=integrate((x)**2*fx,(x,0,1))-integrate((EXY)**2*fy,(y,0,1))\nRHS # right-hand-side\n```\n\n\n\n\n$\\displaystyle \\frac{1}{12} - \\frac{\\log{\\left(3 \\right)}}{144}$\n\n\n\nFinally, we can verify that the left and right sides match,\n\n\n```python\nprint(simplify(LHS-RHS)==0)\n```\n\n True\n\n\nIn this section, we have pulled together all the projection and least-squares\noptimization ideas from the previous sections to connect geometric notions of\nprojection from vectors in $\\mathbb{R}^n$ to random variables. This resulted in\nthe remarkable realization that the conditional expectation is in fact a\nprojection operator for random variables. Knowing this allows to approach\ndifficult problems in multiple ways, depending on which way is more intuitive\nor\ntractable in a particular situation. Indeed, finding the right problem to\nsolve\nis the hardest part, so having many ways of looking at the same concepts\nis\ncrucial.\n\nFor much more detailed development, the book by Mikosch\n[[mikosch1998elementary]](#mikosch1998elementary) has some excellent sections\ncovering much of this\nmaterial with a similar geometric interpretation.\nKobayashi\n[[kobayashi2011probability]](#kobayashi2011probability) does too.\nNelson [[edward1987radically]](#edward1987radically) also\nhas a similar\npresentation based on hyper-real numbers.\n\n## Appendix\n\nWe want to prove that we\nthe conditional expectation is the\nminimum mean squared error minimizer of the\nfollowing:\n\n$$\nJ= \\min_h \\int_{ \\mathbb{R}^2 } \\lvert X - h(Y) \\rvert^2 f_{X,Y}(x,y) dx dy\n$$\n\n We can expand this as follows,\n\n$$\n\\begin{multline*}\nJ=\\min_h \\int_{ \\mathbb{R}^2 } \\lvert X \\rvert^2\nf_{X,Y}(x,y) dx dy + \\int_{ \\mathbb{R}^2 } \\lvert h(Y) \\rvert^2 f_{X,Y}(x,y) dx\ndy \\\\\\\n- \\int_{ \\mathbb{R}^2 } 2 X h(Y) f_{X,Y}(x,y) dx dy\n\\end{multline*}\n$$\n\n To minimize this, we have to maximize the following:\n\n$$\nA=\\max_h \\int_{ \\mathbb{R}^2 } X h(Y) f_{X,Y}(x,y) dx dy\n$$\n\n Breaking up the integral using the definition of conditional expectation\n\n\n
\n\n$$\n\\begin{equation}\nA =\\max_h \\int_\\mathbb{R} \\left(\\int_\\mathbb{R} X f_{X|Y}(x|y)\ndx \\right)h(Y) f_Y(y) dy \n\\label{_auto1} \\tag{3}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \\\n=\\max_h \\int_\\mathbb{R} \\mathbb{E}(X|Y) h(Y)f_Y(Y) dy\n\\label{_auto2} \\tag{4}\n\\end{equation}\n$$\n\n From properties of the Cauchy-Schwarz inequality, we know that the\nmaximum\nhappens when $h_{opt}(Y) = \\mathbb{E}(X|Y)$, so we have found the\noptimal $h(Y)$\nfunction as:\n\n$$\nh_{opt}(Y) = \\mathbb{E}(X|Y)\n$$\n\n which shows that the optimal function is the conditional expectation.\n", "meta": {"hexsha": "b891024f160a1f5799c1d3dfcc3760b40e912747", "size": 196641, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapter/probability/Conditional_Expectation_Projection.ipynb", "max_stars_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_stars_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224, "max_stars_repo_stars_event_min_datetime": "2019-05-07T08:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:50:41.000Z", "max_issues_repo_path": "chapter/probability/Conditional_Expectation_Projection.ipynb", "max_issues_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_issues_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-08-27T12:57:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T15:45:13.000Z", "max_forks_repo_path": "chapter/probability/Conditional_Expectation_Projection.ipynb", "max_forks_repo_name": "derakding/Python-for-Probability-Statistics-and-Machine-Learning-2E", "max_forks_repo_head_hexsha": "9d12a298d43ae285d9549a79bb5544cf0a9b7516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73, "max_forks_repo_forks_event_min_datetime": "2019-05-25T07:15:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:22:37.000Z", "avg_line_length": 304.8697674419, "max_line_length": 176652, "alphanum_fraction": 0.9231798048, "converted": true, "num_tokens": 4144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.18987047091271927}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)//2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc as pm\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000, step=step, return_inferencedata=False)\n```\n\n /opt/homebrew/Caskroom/miniforge/base/envs/myenv/lib/python3.8/site-packages/pymc/model.py:984: FutureWarning: `Model.initial_point` has been deprecated. Use `Model.recompute_initial_point(seed=None)`.\n warnings.warn(\n /opt/homebrew/Caskroom/miniforge/base/envs/myenv/lib/python3.8/site-packages/pymc/model.py:984: FutureWarning: `Model.initial_point` has been deprecated. Use `Model.recompute_initial_point(seed=None)`.\n warnings.warn(\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [lambda_1]\n >Metropolis: [lambda_2]\n >Metropolis: [tau]\n /opt/homebrew/Caskroom/miniforge/base/envs/myenv/lib/python3.8/site-packages/pymc/model.py:984: FutureWarning: `Model.initial_point` has been deprecated. Use `Model.recompute_initial_point(seed=None)`.\n warnings.warn(\n\n\n\n\n
\n \n \n 100.00% [60000/60000 00:03<00:00 Sampling 4 chains, 0 divergences]\n
\n\n\n\n Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 12 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nprint(lambda_1_samples.mean())\nprint(lambda_2_samples.mean())\n```\n\n 17.757078422922426\n 22.72724294278267\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\nlambda_ratios = np.array([lambda_1 / lambda_2 for lambda_1, lambda_2 in zip(lambda_1_samples, lambda_2_samples)])\nlambda_ratios.mean()\n```\n\n\n\n\n 0.7825286272057218\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nlambda_1_cond = lambda_1_samples[np.where(tau_samples < 45)]\nprint(lambda_1_cond.mean())\n```\n\n 17.761947007992113\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "07eb9deb8be3d0f53d2fad74f83ed655e78c3c1d", "size": 293860, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "yashpatel5400/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "c88d86ec45b4590779f1b340547db50cfb2e2f51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "yashpatel5400/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "c88d86ec45b4590779f1b340547db50cfb2e2f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "yashpatel5400/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "c88d86ec45b4590779f1b340547db50cfb2e2f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 243.261589404, "max_line_length": 84132, "alphanum_fraction": 0.8962158851, "converted": true, "num_tokens": 11645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.18975572955309927}} {"text": "Between the text will be code such as the `import` statements below. Please note that the code is just there to support some graphs and numbers. You don't have to understand it to read the text so it can safely be ignored. \n\nIf there's something important happening in code then this will be made clear by the text surrounding it.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotutils as pu\nfrom sympy import S, solve, N\n%matplotlib inline\n```\n\n# complex numbers (are not complex)\nAs humans needed to solve more and more complex equations we had to move away from *whole numbers* through *rational numbers* arriving at a class of numbers that are nowadays mostly called **complex numbers**. \n\nThese numbers are also sometimes known as **imaginary numbers** which is actually a bit of misnomer because these numbers are just as real as any other number and they are essential to a solving a huge number of problems in science. In fact, the complex moniker is kinda stupid as well. They are not complex at all. Just a bit unconventional.\n\nBefore we explain complex numbers in more detail it might be useful and take a step back and see why we need them in the first place. We'll sidetrack a bit with *square roots* and *square numbers* get some concepts in place before we get to the really funky stuff.\n\n# the square root\nOne of the more nasty operations in math is taking the square root of a number. In fact, even before complex numbers people ran into problems with this operation due to the fact [how it's defined](https://en.wikipedia.org/wiki/Square_root):\n\n> In mathematics, a square root of a number $a$ is a number $y$ such that $y^2 = a$, in other words, a number $y$ whose square (the result of multiplying the number by itself, or $y \\times y$) is $a$.\n\nAs usual, the definition is correct but hard to understand if you're not used to the lingo and format of these things. As an aside, naming one of the variables $a$ doesn't increase the readability of the definition.\n\nAnother definition might be:\n\n> Given the hypervolume of some object $P$ in $n$ dimensions and given a hypercube $Q$ in the same $n$ dimensions. What length does each side of the hypercube needs to be represent the volume of $P$.\n\nAnd to be honest, I just made that up and I hope it's somewhat correct. But it seems to be true if we consider everythig a *hyperthing* where hyper just means its a thing that exists in one or more dimensions.\n\nIn math, the square root of a number $x$ is written as $\\sqrt{x}$ and the easiest way to understand it is with some examples:\n\n$$\n\\begin{align}\n1 \\times 1 = 1 & \\implies \\sqrt{1} = 1 \\\\\n2 \\times 2 = 4 & \\implies \\sqrt{4} = 2 \\\\\n3 \\times 3 = 9 & \\implies \\sqrt{9} = 3 \\\\\n\\cdots \\\\\nx \\times x = x^2 & \\implies \\sqrt{x^2} = x\n\\end{align}\n$$\n\nIn the table above we can see that if we take some number $x$ and multiply it with itself we get $x \\times x$ which in math is usually written as $x^2$ ($x$ squared). We can also see that if we proceed to take the square root of some number $x^2$ we get back the original number $x$. \n\nIn other words, it is the *inverse* of *squaring* a number (multiplying a number with itself). However just by this very definition we get into strange territory very quickly. As long as we are dealing with squares such as $x \\times x$ the world is wonderful and we can be sure that any square root we want to find is an *integer* (whole number) just by the way how the operation is defined.\n\n### squared?\nEspecially in the old times but even today when doing exploratory stuff it's not uncommon to look at things from a *geometric* perspective. Which basically means we try to to think about shapes. When we are dealing with what seemingly is only one dimension it's often useful to look at it from a two-dimensional point of view. Also we can try to understand things by *mapping* them to less dimensions. \n\n# square numbers\nSo what is a *square number* anyway? If we look at it from a geometric perspective we can say that a square is in fact a rectangle where both sides are equal. Now this is a bit of a recursive definition because we might as well say a rectangle is a square scaled along some kind of axis but lets stick with our basic explanation for now. We know that we can compute the *area* of a rectangle by multiplying its width $x$ and height $y$. So $area = x \\times y$. \n\nNow if we consider a number as being some kind of measurement for an abstract *area* we can say that a square number is a number such that we can write $area = x \\times y = x \\times x = y \\times y\\implies x = y$ where $area$ is just some number. Which in geometric terms means that some kind of area can either be defined by $x \\times y$ (the width times height) or by $x \\times x$ (width times width) and that this *implies* that $x$ is equal to $y$. Or in other words, both sides are equal and we're dealing with a square.\n\nThis square might be anything, it's not important, after all, with this definition the number $4$ is a square. It's a square of $2 \\times 2$ and what it actually represents even in this abstract form is too much to answer in this essay. It can be anything, the important fact is the property that it can be written as a *factor* of two numbers that are the same. \n\n### factor?\nA factor is basically when we take a thing and break it up in other using multiplication. So for example if we take $4$ we can factor this into $2 \\times 2$ or $1 \\times 4$ and we can say that $1$, $2$ and $4$ *are factors* of $4$. More generaly we can say that if a number $x$ can be represented with $n$ and $m$ so that $n \\times m = x$ then this number $x$ has factors $n$ and $m$.\n\nSo how would we plot square roots? One way is just to plot a graph but we can do something a bit more *geometric*. We can plot square roots (and any root as it turns out) as a rectangle as well.\n\n\n```python\ndef plot_rect(ax, p, fmt='b'):\n x, y = p\n ax.plot([0, x], [y, y], fmt) # horizontal line\n ax.plot([x, x], [0, y], fmt) # vertical line\n\nwith plt.xkcd():\n fig, axes = plt.subplots(1, 2, figsize=(8, 4))\n for ax in axes: pu.setup_axes(ax, xlim=(-1, 5), ylim=(-1, 5), tickdirection='out')\n for p in [(1, 1), (2, 2), (3, 3)]: plot_rect(axes[0], p)\n plot_rect(axes[0], (2+2/3, 2+2/3), 'r--')\n for p in [(1, 1), (2, 2)]: plot_rect(axes[1], p)\n plot_rect(axes[1], (3, 4), 'r--')\n```\n\nWe can clearly see all the *easy* roots of $x = 1, 2, 3, \\ldots$ but how do our other points compare? In the first case we are between $2$ and $3$ and our width equals our height so $x = y$ and this is still managable but in the second case, how do we find a cube that is the size of a $3 \\times 4$ rectangle?\n\n# taking square roots\nSo now that we have some concepts out of the we way we can look at the square root operation from a slightly different perspective and ask another question:\n\n> Assuming that number $x$ represents an area, how big does my square needs to be to be so its area equals $x$.\n\nThis is actually not that easy to answer (without invoking roots) and as such taking square roots is a bit of a funky operation. One thing is that it is somewhat hard for to do for humans. Another thing is that there are actually some people who might argue some square root numbers don't even exist because there is no way to write them down without involving the square root itself. We're not even considering *cube roots* and/or higher here but we should be able to see that finding some kind of number that can be multiplied with itself to make up *any* kind number is somewhat tricky.\n\n### perspective: not squares\nAfter all this talk of squares we could also look at it from a non-square perspective. Let's say we measure a rectangle of $3 \\times 4$. It's area would be $3 \\times 4 = 12$. Now we walk over to someone and request that we get a square that represents this area. So we request $\\sqrt{12}$. It would not be unreasonable to be unable to comply because there isn't much more reasonable ways to write $\\sqrt{12}$ in a different way.\n\nNow of course there are exceptions but for the average human finding the square root of some number is not something they can just do. There are various methods in order to get us close but that's the point, we can never ever really get to some actual number with these things. Take for example $\\sqrt{2}$ which we'll look at in more detail later. We simply cannot simplify this anymore without losing precision. We cannot write it as a rational number like $\\frac{2}{3}$ either. It's just a number that if we would try to write it down as a decimal we would just have to decide to stop somewhere because it has an infinite amount of decimals.\n\n### calculating square roots manually\nThere's lots of ways to calculate square roots manually and I'm not even sure if the way I'm about to describe is in any way an \"official\" or even good way but it does make the operation easy to understand if we keep considering a number as some kind of area.\n\nLet's get back to our square of $3 \\times 4$ and see if we can figure this out. There's a huge plot incoming but don't worry about it. It's not important to the problem we are trying to figure out, just focus on the graphs below.\n\n\n```python\nwith plt.xkcd():\n fig, axes = plt.subplots(1, 2, figsize=(10, 5))\n for ax in axes: pu.setup_axes(ax, xlim=(-1, 5), ylim=(-1, 5), tickdirection='out')\n plot_rect(axes[0], (3, 4), 'b')\n axes[0].plot([0, 3], [3, 3], 'b--')\n axes[0].yaxis.set_ticks([1, 2, 3, 4])\n axes[0].xaxis.set_ticks([1, 2, 3])\n axes[0].yaxis.set_ticklabels(['', '', '3', '4'])\n axes[0].xaxis.set_ticklabels(['', '', 3])\n axes[0].annotate('THE NUMBER 12', (0.5, 4.5))\n axes[0].annotate('A', (0.5, 3.35))\n plot_rect(axes[1], (3, 3), 'b')\n plot_rect(axes[1], (3.461, 3.461), 'b--')\n axes[1].plot([3, 3], [3, 4.2], 'b--')\n axes[1].plot([3, 4.2], [3, 3], 'b--')\n axes[1].yaxis.set_ticks([1, 2, 3, 3.461, 4])\n axes[1].xaxis.set_ticks([1, 2, 3, 3.461, 4])\n axes[1].xaxis.set_ticklabels(['', '', '3', 'x0', '4'])\n axes[1].yaxis.set_ticklabels(['', '', '3', 'x0', '4'])\n axes[1].annotate('THE SQUARE ROOT OF 12', (0.5, 4.5))\n axes[1].annotate('u', (1.5, 3.75))\n axes[1].annotate('w', (3.75, 3.75))\n axes[1].annotate('v', (3.75, 1.5))\n axes[1].annotate('A = u + v + w', (0.5, 1.5))\n```\n\nRemember, when we ask for a square root we are basically looking for a square that has an area equal to the number we give. Except this time we started with a non-square number. The area of our triangle is $3 \\times 4 = 12$. This is the number that is represented on the left, on the right is a square representing the answer we are looking for: $\\sqrt{12}$.\n\nLet's start on the left side and take a look at the area $A$. We can see that: \n\n$A = 3 \\times (4 - 3) = 3 \\times 1 = 3 \\implies A = 3$.\n\nFrom a geometric perspective we can see that if we want to calculate the biggest possible square we need to look at the shortest side of the rectangle. We can also imagine this holds up for a cube in three dimensions and our guts may tell us it will hold up for any shape in $n$ dimensions. We'll bother with this in a moment though. \n\nFor now let's focus on a bit on the right-hand plot. We have this number $x_0 - 3$ which is interesting. Logically we can deduce that in order to produce a square we need to add $(x_0 - 3) \\times 3$ to each side. So that's two times that quantity which is $2 \\times (x_0 - 3) \\times 3$. And then we are left with this little square in the corner and this is just $(x_0 - 3) \\times (x_0 - 3) = (x_0 - 3)^2$. \n\nWriting it all out we have:\n\n$$\n\\begin{align}\nA & = (x_0 - 3)^2 + (x_0 - 3) \\times 3 + (x_0 - 3) \\times 3 \\\\\n& = (x_0 - 3)^2 + 2 \\times 3 \\times (x_0 - 3) \\\\\n& = (x_0 - 3)^2 + 6 \\times (x_0 - 3) \\\\\n& = 3 \\\\\n& = A\n\\end{align}\n$$\n\nSo we defined $A$ in some other *terms* and then finally we got back $A$. What have we acomplished? Well first we have shown that $A = 3$ which is a known fact in *this case*. We are trying to find some formula to describe this. So then we composed $A$ in *ratios* of areas we can call $u$, $v$ and $w$.\n\nSo now we end up with:\n\n$$\n\\begin{align}\nu & = 3 \\times (x_0 - 3) \\\\\nv & = 3 \\times (x_0 - 3) \\\\\nw & = (x_0 - 3) \\times (x_0 - 3)\n\\end{align}\n$$\n\nWhat we're really interested in is this number $x_0 - 3$ whatever it might end up to be. And things are getting a bit unwieldly so let's just say $x = (x_0 - 3)$ and we might be able to rewrite this in a more friendly form.\n\n$A = w + u + v = x^2 + 3x + 3x = 3 = x^2 + 6x$\n\nIt might not seem much but we're getting somewhere because we can now say that:\n\n$A = x^2 + 6x = 3$.\n\nLet's call in `sympy` in order to try to solve this and see what we get.\n\n\n```python\nA = S('x^2 + 6*x - 3')\nsolve(A)\n```\n\n\n\n\n [-3 + 2*sqrt(3), -2*sqrt(3) - 3]\n\n\n\nOh great we got two possible answers of $2\\sqrt{3} - 3$ and $-2\\sqrt{3} - 3$ which doesn't really help us much calculating the square root manually. However the numbers do give a little bit more insight in what is happening. We can notice how prominent the $3$ is in there.\n\nBy now we can see that caculating square roots is not something trivial. In fact our best methods just depend on *guestimation*. For example we could just take a look at $x^2 + 6x - 3 = 0$ and by looking at the plot above and the range of the outcome we know it has to be between zero and one. So one way to start is just to put in some values between $0$ and $1$ and see what happens.\n\nLet $f(x) = x^2 + 6x - 3$.\n\n\n```python\nwith plt.xkcd():\n fig, axes = plt.subplots(1, 2, figsize=(8, 4))\n for ax in axes: pu.setup_axes(ax)\n f = lambda x: x**2 + (6 * x) - 3\n x1 = np.linspace(0, 1, 100)\n x2 = np.linspace(-50, 50, 1000)\n axes[0].plot(x1, f(x1))\n axes[1].plot(x2, f(x2))\n axes[1].set_xlim(-10, 5)\n axes[1].set_ylim(-15, 2)\n```\n\n\n```python\n\n```\n\n### calculating the biggest possible square\nWe easily see that the biggest square we can make is $3 \\times 3$ but is there a way to calculate this instead? If we have a number 12. What *is* the biggest actual square we can make where the side length is an integer number. Well we *know* that $\\sqrt{9} = 3$ so that's the square we are looking for. The next integer square is $4 \\times 4$ and that's too big. The number we are looking for is $3$ but how can we figure this out. \n\nOur rectangle is $3 \\times 4$ and the square we are looking for is $3 \\times 3$ or $3^2$. It seems that given a rectangle, the number we are looking for is the short side. But if we only know an area things are a bit harder, suppose we are only given the number $12$ and we know it's the area of a rectangle but not it's dimensions. The next question we could ponder is, does it even matter for the final outcome?\n\n# sandbox\nEverything below is just for playing around and should be deleted or cleaned-up for final publishing.\n\n### sanity check on calculating $\\sqrt{12}$\n\nEven though this is jjust a sanity check this is a pretty awesome curve if we consider what it is doing geometrically. How do the negative values even make sense?\n\n\n```python\n# this is the solution we found involing sqrt(12)\nf = lambda x: x**2 + 6*x - 3 \nx = np.linspace(-10, 10, 100)\n# let's plot it for sanity\nplt.plot(x, f(x))\n```\n\n\n```python\nx = 0.46410 # this is our manually calculated value of dx/spread\nprint(round((x**2) + (x*6) - 3, 2))\nprint(3 + x)\nprint(round(np.sqrt(12), 4))\n```\n\n -0.0\n 3.4641\n 3.4641\n\n", "meta": {"hexsha": "8b4ec137d5274f9a223a85bc7e4cf54dafa4f16e", "size": 89262, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "math_numbers.ipynb", "max_stars_repo_name": "basp/notes", "max_stars_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-12-09T13:58:13.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T13:58:13.000Z", "max_issues_repo_path": "math_numbers.ipynb", "max_issues_repo_name": "basp/notes", "max_issues_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math_numbers.ipynb", "max_forks_repo_name": "basp/notes", "max_forks_repo_head_hexsha": "8831f5f44fc675fbf1c3359a8743d2023312d5ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 200.1390134529, "max_line_length": 29732, "alphanum_fraction": 0.8730590845, "converted": true, "num_tokens": 4440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.18823829350082977}} {"text": "# Métodos Numéricos Aplicados à Transferência de Calor\n\n## Introdução\n\n### Sobre o material\n\n* O objetivo desta palestra é **introduzir os principais conceitos empregados em programação e Python**, mais especificamente, no contexto interativo da plataforma Jupyter Notebook;\n* Além de demonstrar como **solucionar problemas em transferência de calor** por meio de propostas computacionais;\n* Para tanto, o material inclui uma breve **revisão de conceitos fundamentais** e as principais bibliotecas científicas disponíveis. Para maiores detalhes, **pode-se consultar a documentação disponível** ou mesmo as diversas leituras recomendadas que aparecem no decorrer do texto.\n\n### Porque Python?\n\n\n\n> Leitura recomendada:\n> * [10 motivos para você aprender Python](https://www.hostgator.com.br/blog/10-motivos-para-voce-aprender-python/)\n\n### Porque Jupyter Notebooks?\n\n\n\n* Ferramenta web interativa, grátis e de código aberto;\n* Exploração de dados. Permite executar o código, ver o que acontece, modificar e repetir, onde temos uma *\"conversa\"* com os dados disponíveis;\n* Útil para a criação de tutoriais interativos;\n* Ele fala a nossa língua. Disponível para várias liguagens de programação, como Python, Julia, R, Fortran e muitas outras;\n* É possível combinar o código com células `Markdown`, para renderizar equações e tabelas, inserir figuras e explicações sobre o código;\n* Facilmente extensível para diversos formatos (PDF, HTML, $\\LaTeX$, slides e outros);\n* Disponível em [jupyter.org](https://jupyter.org), além de:\n - Acompanhar a instalação do [Anaconda](https://www.anaconda.com/);\n - Ferramenta colaborativa na nuvem com [Google colab](https://colab.research.google.com) ou [binder](https://mybinder.org/).\n\n> Leitura recomendada:\n> - [Mastering Markdown](https://guides.github.com/features/mastering-markdown/)\n> - [LaTeX/Mathematics](https://en.wikibooks.org/wiki/LaTeX/Mathematics)\n> - [Why Jupyter is data scientists’ computational notebook of choice](https://www.nature.com/articles/d41586-018-07196-1)\n> - [Why I write with LaTeX (and why you should too)](https://medium.com/@marko_kovic/why-i-write-with-latex-and-why-you-should-too-ba6a764fadf9)\n> - [New Developer? You should’ve learned Git yesterday](https://codeburst.io/number-one-piece-of-advice-for-new-developers-ddd08abc8bfa)\n> - [12 passos para Navier-Stokes](https://www.fschuch.com/blog/2020/01/12/cfd-com-python-12-passos-para-navier-stokes/)\n> - [Jupyter Notebook como uma Poderosa Ferramenta Educacional](https://www.fschuch.com/blog/2021/01/22/jupyter-notebook-como-uma-poderosa-ferramenta-educacional/#formas-de-acessarcompartilhar)\n\n\n## Programação em Python\n\nAs primeiras linhas de código interativas dessa aula (`Shift+Enter` executam o bloco):\n\n\n```python\n\"\"\"\nIsso é um comentário\n\"\"\"\n\nprint(\"Olá mundo\")\n\n# Isso também é um comentário\n```\n\n### Atribuição de variáveis:\n\n\n```python\ni = 5 # inteiro\nf = 6.7 # ponto flutuante\ng = 1e-2 # notação exponencial\ns = \"abcdef\" # string\nc = 5.0 + 6j # complexo\n```\n\n### Operações matemáticas\n\nOperador | Descrição | Exemplo | Resultado\n---------|-----------|---------|----------\n`+` | Soma | `1 + 1` | `2`\n`-` | Subtração | `2 - 1` | `1`\n`*` | Multiplicação | `6 * 7` | `42`\n`/` | Divisão | `8 / 4` | 2.0\n`//` | Divisão inteira | `10 // 3` | 3\n`%` | Resto da divisão | `10 % 3` | 1\n`**` | Potência | `2 ** 3` | 8\n\nTeste qualquer uma das operações no bloco abaixo:\n\n\n```python\n10 % 7.5\n```\n\n\n```python\na = 10.5\nb = 5\n\nc = a * b\nc\n```\n\n### Operações em laços\n\nComputadores são ótimos para a realização de tarefas repetitivas. Para isso, temos à nossa disposição laços (ou *loops*), que geralmente percorrem um espaço definido pelo seu `valor inicial`, `valor final`, e o tamanho do `incremento`. Veja o exemplo:\n\n\n```python\ninicio = 0 # opcional, será zero se não informado\nfinal = 5\nincremento = 1 # opcional, será um se não informado\n\nfor i in range(inicio, final, incremento):\n print(i)\n \"\"\"\n Aqui realizaríamos operações da nossa aplicação\n \"\"\"\n```\n\n**Nota**: Não precisamos indicar o final do laço em Python, porque isso é reconhecido por meio da identação.\n\n**Outra Nota:** sempre que precisar de ajuda para compreender qualquer objeto no Jupyter, digite seu nome seguido de uma interrogação `?`, ou use a função `help()`, veja só:\n\n\n```python\nrange?\n```\n\nObserve que, em Python:\n* **A contagem começa em zero**;\n* **O argumento inicial é inclusivo** (ele estará no espaço a percorrer);\n* Enquanto **o argumento final é exclusivo** (ele não estará no espaço a percorrer).\n\nCompreenda melhor esses conceitos com exemplos:\n\n\n```python\nfor i in range(10):\n print(i, end=\" \")\n```\n\n\n```python\nfor i in range(0, 10, 1):\n print(i, end=\" \")\n```\n\n\n```python\nfor i in range(15, 30, 5):\n print(i, end=\" \")\n```\n\n\n```python\nfor i in range(0, 10, 3):\n print(i, end=\" \")\n```\n\n\n```python\nfor i in range(0, -10, -1):\n print(i, end=\" \")\n```\n\n\n```python\nfor i in range(0):\n print(i, end=\" \")\n```\n\n**Nota**: Perceba que `range` é apenas uma das diferentes possibilidades que temos para contruir um laço em Python.\n\n### Testes lógicos\n\nOperador | Descrição | Exemplo | Resultado\n---------|-----------|---------|----------\n`==` | Igualdade | `1 == 2` | `False`\n`!=` | Diferença | `1 != 2` | `True`\n`>` | Maior que | `1 > 3` | `False`\n`<` | Menor que | `1 < 3` | `True`\n`>=` | Maior ou igual que | `1 >= 3` | `False`\n`=<` | Menor ou igual que | `1 <= 3` | `True`\n`and` | Operador lógico \"e\" | `True and False` | `False`\n`or` | Operador lógico \"ou\" | `True or False` | `True`\n`not` | Operador lógico \"não\" | `not False` | `True`\n\n\n```python\nif 5 <= 3.0:\n \"\"\"\n Aqui realizaríamos operações da nossa aplicação\n \"\"\"\n print(\"Estou no bloco if\")\nelif 4 != 0:\n \"\"\"\n Aqui realizaríamos operações da nossa aplicação\n \"\"\"\n print(\"Estou no bloco elif\")\nelse:\n \"\"\"\n Aqui realizaríamos operações da nossa aplicação\n \"\"\"\n print(\"estou no blobo else\")\n```\n\n### Funções\n\nFunções são uma forma de encapsular trechos de código que você porventura queira executar diversas vezes. Argumentos são parâmetros opcionais de entrada, que podem alterar ou controlar o comportamento no interior da função. E elas podem ou não retornar algum valor.\n\nNo bloco a seguir, definimos um exemplo didático. Uma função que testa se um dado número de entrada é ímpar, retornando `True`, ou não, retornando `False`. Veja o exemplo:\n\n\n```python\ndef testa_se_impar(numero):\n return bool(numero % 2)\n```\n\nAgora invocamos e testamos a nossa função:\n\n\n```python\ntesta_se_impar(4)\n```\n\n\n```python\ntesta_se_impar(5)\n```\n\nPodemos incrementar a apresentação de nossa função com recursos extras. Por exemplo, atribuir valores padrões aos argumentos, caso eles não sejam informados ao invocar a função. Além disso temos o *type hint*, ou uma dica do tipo, onde podemos anotar na função a tipagem dos argumentos de entrada e saída, para auxiliar quem estiver utilizando nossa função. Finalmente, o comentário inicial é conhecido como *Docstring*, o lugar ideal para uma documentação rápida, que também estará disponível para nossos usuários:\n\n\n```python\ndef testa_se_impar_v2(numero: int = 0) -> bool:\n \"\"\"\n Dado um número inteiro como argumento de entrada,\n retorna True se ele é ímpar e False se ele é par\n \"\"\"\n return bool(numero % 2)\n```\n\nQuando invocada sem argumentos, número será o valor definido como padrão, zero nesse caso, então a função é executada sem erros:\n\n\n```python\ntesta_se_impar_v2()\n```\n\nO nome dos argumentos podem estar presentes na chamada, oferecendo legibilidade extra ao seu código:\n\n\n```python\ntesta_se_impar_v2(numero=67)\n```\n\nNote que o *Docstring* é exibido na tela quando solicitamos ajuda:\n\n\n```python\ntesta_se_impar_v2?\n```\n\nMaterial complementar:\n\n* [More Control Flow Tools](https://docs.python.org/3/tutorial/controlflow.html)\n* [The Python Tutorial - Modules](https://docs.python.org/3/tutorial/modules.html)\n* [Data Structures](https://docs.python.org/3/tutorial/datastructures.html)\n* [Classes](https://docs.python.org/2/tutorial/classes.html)\n\n### Principais Pacotes\n\nUma das grandes forças do Python é a enorme gama de pacotes que estão disponíveis, e em contínuo desenvolvimento, nas mais diversas áreas do conhecimento.\n\nA seguir, veremos algumas que são particularmente úteis para aplicações em transferência de calor.\n\n#### SciPy\n\n\n\nFerramentas de computação científica para Python. SciPy refere-se a várias entidades relacionadas, mas distintas:\n\n* O ecossistema SciPy, uma coleção de software de código aberto para computação científica em Python;\n* A comunidade de pessoas que usam e desenvolvem essa biblioteca;\n* Várias conferências dedicadas à computação científica em Python - SciPy, EuroSciPy e SciPy.in;\n* Fazem parte da família os pacotes, que serão melhor descritos a seguir:\n * Numpy;\n * Matplotlib;\n * Sympy;\n * IPython;\n * Pandas.\n\n* Além disso, a própria biblioteca SciPy, um componente do conjunto SciPy, fornecendo muitas rotinas numéricas:\n * Funções especiais;\n * Integração numérica;\n * Diferenciação numérica;\n * Otimização;\n * Interpolação;\n * Transformada de Fourier;\n * Processamento de sinal;\n * Algebra linear e Algebra linear esparsa;\n * Problema de autovalor esparso com ARPACK;\n * Algoritmos e estruturas de dados espaciais;\n * Estatistica;\n * Processamento de imagem multidimensional;\n * I/O de arquivos;\n\n\n```python\nimport scipy as sp\nimport scipy.optimize\nimport scipy.integrate\n```\n\nMaterial complementar:\n* [SciPy](https://www.scipy.org/)\n* [Getting Started](https://www.scipy.org/getting-started.html)\n* [Scipy Lecture Notes](http://scipy-lectures.org/index.html)\n\n#### Numpy\n\n\n\nNumpy é um pacote fundamental para a **computação científica em Python**. Entre outras coisas, destaca-se:\n* Objetos em arranjos N-dimensionais\n* Funções sofisticadas\n* Ferramentas para integrar código C/C++ e Fortran\n* Conveniente álgebra linear, transformada de Fourier e capacidade de números aleatórios\n\nAlém de seus usos científicos óbvios, o NumPy também pode ser usado como um contêiner multidimensional eficiente de dados genéricos. Tipos de dados arbitrários podem ser definidos. Isso permite que o NumPy integre-se de forma fácil e rápida a uma ampla variedade de bancos de dados.\n\n\n```python\nimport numpy as np # Importando a biblioteca numpy e definindo-a com o codnome de np\n```\n\n\n```python\nmatriz = np.arange(15).reshape(3, 5)\n\n# exibe na tela\nmatriz\n```\n\n\n```python\nmatriz.shape\n```\n\n\n```python\nmatriz.ndim\n```\n\n\n```python\nmatriz.dtype.name\n```\n\n\n```python\nmatriz.size\n```\n\n\n```python\ntype(matriz)\n```\n\n##### Construção e Seleção de Dados\n\n* Criar matrizes completas com valores iniciais em zero ou um:\n\n\n```python\nnp.zeros(shape=(3, 4), dtype=np.float64)\n```\n\n\n```python\nnp.ones(shape=(2, 3, 4), dtype=np.int16)\n```\n\n* Definição inicial de um intervalo, de maneira similar a função `range` do Python:\n\n\n```python\nnp.arange(10, 30, 5)\n```\n\n\n```python\nnp.arange(0, 2, 0.3)\n```\n\n* Ou ainda um espaço linear:\n\n\n```python\nvetor = np.linspace(start=0.0, stop=2.0, num=9)\nvetor\n```\n\nA seleção dos dados ocorre de maneira similar às listas, com o número inteiro representando a localização, começando a contagem em zero. Veja os exemplos:\n\n\n```python\nvetor[0]\n```\n\n\n```python\nvetor[2]\n```\n\n\n```python\nvetor[0:4:2]\n```\n\n\n```python\nvetor[-1]\n```\n\nNo caso em que temos mais dimensões, como na matriz que definimos anteriormente, a mesma ideia se aplica, e separamos cada dimensão por vírgulas:\n\n\n```python\nmatriz\n```\n\n\n```python\nmatriz[0, 0], matriz[0, 1], matriz[1, 0]\n```\n\n\n```python\nmatriz[0, :]\n```\n\n\n```python\nmatriz[:, -1]\n```\n\n**Cuidado**, pois o sinal de igualdade não cria novas cópias dos tensores, e isso pode confundir os iniciantes:\n\n\n```python\noutro_vetor = vetor\noutro_vetor\n```\n\n\n```python\noutro_vetor is vetor\n```\n\n\n```python\noutro_vetor *= 0\n\nprint(vetor)\n```\n\nTemos agora duas maneiras de acessar o mesmo vetor na memória, pois tanto `vetor` quanto `outro_vetor` apontam para a mesma posição na memória.\n\n##### Operações Tensoriais\n\nOperações aritméticas e lógicas estão disponíveis para os objetos Numpy, e são propagados para todos os elementos do tensor. Veja os exemplos:\n\n\n```python\na = np.array([20, 30, 40, 50])\nb = np.array([0, 1, 2, 3])\n```\n\n\n```python\na - b\n```\n\n\n```python\nb ** 2\n```\n\n\n```python\n10 * np.sin(a)\n```\n\n\n```python\na < 35\n```\n\n> Leitura recomendada:\n> * [NumPy Documentation](https://numpy.org/doc/)\n> * [NumPy quickstart](https://numpy.org/doc/1.20/user/quickstart.html)\n> * [NumPy: the absolute basics for beginners](https://numpy.org/doc/1.20/user/absolute_beginners.html)\n> * [Tutorial: Linear algebra on n-dimensional arrays](https://numpy.org/doc/1.20/user/tutorial-svd.html)\n>\n> Outros pacotes Python para manipulação de dados:\n> * [Pandas](https://pandas.pydata.org/) é uma pacote Python especializado na processamento eficiente de dados tabelados, podendo lidar com arquivos CSV, Excel, SQL, arranjos Numpy e outros;\n> * [Xarray](http://xarray.pydata.org/) introduz rótulos na forma de dimensões, coordenadas e atributos sobre os dados brutos dos arranjos em formato NumPy, permitindo uma experiência de desenvolvimento mais intuitiva, consistente e a prova de falhas;\n> * [Dask](https://dask.org/) fornece paralelismo avançado para análises, permitindo desempenho em escala para as ferramentas que você adora.\n\n#### **Pandas**\n\n\n\nO pandas é um pacote Python que fornece **estruturas de dados rápidas, flexíveis e expressivas**, projetadas para tornar o trabalho com dados “relacionais” ou “rotulados” fáceis e intuitivos. O objetivo é ser o alicerce fundamental de alto nível para a análise prática de dados do mundo real em Python. Além disso, tem o objetivo mais amplo de se tornar a mais poderosa e flexível ferramenta de análise / manipulação de dados de código aberto disponível em qualquer linguagem.\n\nPandas é bem adequado para muitos tipos diferentes de dados:\n* Dados tabulares com colunas de tipos heterogêneos, como em uma **tabela SQL, arquivo `.csv` ou planilha do Excel**;\n* Dados de **séries temporais** ordenados e não ordenados (não necessariamente de frequência fixa);\n* Dados de matriz arbitrária (homogeneamente digitados ou heterogêneos) com rótulos de linha e coluna;\n* Qualquer outra forma de conjuntos de dados observacionais / estatísticos. Os dados realmente não precisam ser rotulados para serem colocados em uma estrutura de dados de pandas.\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\ndf2 = pd.DataFrame({'A': 1.,\n 'B': pd.Timestamp('20130102'),\n 'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n 'D': np.array([3] * 4, dtype='int32'),\n 'E': pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n 'F': 'foo'})\n```\n\n\n```python\ndf2\n```\n\n> Material complementar:\n> * [Pandas](https://pandas.pydata.org/)\n> * [10 minutes to pandas](https://pandas.pydata.org/pandas-docs/version/0.25.0/getting_started/10min.html)\n\n#### Tqdm\n\nProduz uma barra de progresso. Recurso puramente estético, mas ainda assim, muito útil:\n\n\n```python\nfrom tqdm.notebook import tqdm\n```\n\n\n```python\nfor i in tqdm(range(100)):\n ...\n```\n\n#### Sympy\n\n\n\nSymPy é uma biblioteca Python para **matemática simbólica**. O objetivo é tornar-se um sistema de álgebra computacional (CAS) completo, mantendo o código o mais simples possível para ser compreensível e facilmente extensível. SymPy é escrito inteiramente em Python.\n\n\n```python\nimport sympy as sm\n\nsm.init_printing(use_latex=\"mathjax\") # Para escrever equações na tela\n```\n\n\n```python\nx, t = sm.symbols(\"x t\") # Criando símbolos\n```\n\n\\begin{equation}\n\\text{calcular } \\int (e^x \\sin(x) + e^x \\cos(x)) dx\n\\end{equation}\n\n\n```python\nsm.integrate(sm.exp(x) * sm.sin(x) + sm.exp(x) * sm.cos(x), x)\n```\n\n\\begin{equation}\n\\text{calcular a derivada de }\\sin(x)e^x\n\\end{equation}\n\n\n```python\nsm.diff(sm.sin(x) * sm.exp(x), x)\n```\n\n\\begin{equation}\n\\text{calcular } \\int_{-\\infty}^{\\infty} \\sin(x^2)\n\\end{equation}\n\n\n```python\nsm.integrate(sm.sin(x ** 2), (x, -sm.oo, sm.oo))\n```\n\n\\begin{equation}\n\\text{calcular } \\lim_{x \\to 0} \\dfrac{\\sin(x)}{x}\n\\end{equation}\n\n\n```python\nsm.limit(sm.sin(x) / x, x, 0)\n```\n\n\\begin{equation}\n\\text{resolver } x^2 - 2 = 0\n\\end{equation}\n\n\n```python\nsm.solve(x ** 2 - 2, x)\n```\n\n\\begin{equation}\n\\text{resolver a equação diferencial } y'' - y = e^t\n\\end{equation}\n\n\n```python\ny = sm.Function(\"y\")\neq1 = sm.dsolve(sm.Eq(y(t).diff(t, t) - y(t), sm.exp(t)), y(t))\neq1\n```\n\n\n```python\n# Bônus\nprint(sm.latex(eq1))\n```\n\nMaterial complementar:\n* [Sympy](https://www.sympy.org/en/index.html)\n* [Documentation](https://docs.sympy.org/latest/index.html)\n\n#### Matplotlib\n\n\n\nA Matplotlib é uma biblioteca de plotagem 2D do Python, que produz figuras de qualidade de publicação em uma variedade de formatos impressos e ambientes interativos entre plataformas. O Matplotlib pode ser usado em scripts Python, nos shells do Python e do IPython, no notebook Jupyter, nos servidores de aplicativos da web e em quatro kits de ferramentas de interface gráfica do usuário.\n\nA **Matplotlib tenta tornar as coisas fáceis simples e as coisas difíceis possíveis**. Você pode gerar gráficos, histogramas, espectros de potência, gráficos de barras, gráficos de erros, diagramas de dispersão, etc., com apenas algumas linhas de código.\n\nComo sempre, começamos importando a biblioteca:\n\n\n```python\nimport matplotlib.pyplot as plt\n```\n\nAgora fazemos nossa primeira figura:\n\n\n```python\nx = np.linspace(start=0, stop=10, num=100)\nplt.plot(x, np.sin(x));\n```\n\nO nome dos eixos são indispensáveis se você quiser mostrar sua figura para terceiros, um título pode ajudar também. Outro exemplo é como podemos definir os limites de cada eixo do gráfico. Veja nossa nova figura:\n\n\n```python\nx = np.linspace(0, 10, 100)\nplt.plot(x, np.sin(x))\n\nplt.xlim([0, 2 * np.pi])\nplt.ylim([-2, 2])\n\nplt.xlabel(r\"eixo x $\\sigma^2$\")\nplt.ylabel(\"eixo y\")\n\nplt.title(\"Minha figura\");\n```\n\n> Leitura recomendada:\n> * [Matplotlib](https://matplotlib.org/)\n> * [Style sheets reference](https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html)\n> * [Gallery](https://matplotlib.org/stable/gallery/index.html)\n> * [Gráficos com qualidade de publicação em Python com Matplotlib](https://www.fschuch.com/blog/2020/10/14/graficos-com-qualidade-de-publicacao-em-python-com-matplotlib/)\n\n#### Plotly\n\nA biblioteca de gráficos Python do Plotly cria **gráficos interativos** com qualidade de publicação. As possibilidades de como fazer gráficos são inumeras: de linha, gráficos de dispersão, gráficos de área, gráficos de barras, barras de erro, gráficos de caixa, histogramas, mapas de calor, subplots, eixos múltiplos, gráficos polares e gráficos de bolhas.\n\n\n```python\nimport plotly.express as px\nimport plotly.graph_objects as go\n```\n\n\n```python\npx.defaults.template = \"ggplot2\"\npx.defaults.height = 600\n```\n\n\n```python\ndf = px.data.iris()\nfig = px.scatter(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\")\nfig.show()\n```\n\n\n```python\nfig = go.Figure(data =\n go.Contour(\n z=[[10, 10.625, 12.5, 15.625, 20],\n [5.625, 6.25, 8.125, 11.25, 15.625],\n [2.5, 3.125, 5., 8.125, 12.5],\n [0.625, 1.25, 3.125, 6.25, 10.625],\n [0, 0.625, 2.5, 5.625, 10]],\n x=[-9, -6, -5 , -3, -1], # horizontal axis\n y=[0, 1, 4, 5, 7] # vertical axis\n ))\nfig.show()\n```\n\n> Leitura recomendada:\n> * [Plotly](https://plotly.com/python/)\n> * [Plotly Express in Python](https://plotly.com/python/plotly-express/)\n> * [Dash App Gallery](https://dash-gallery.plotly.host/Portal/)\n\n#### Handcalcs\n\nHandcalcs é uma biblioteca para renderizar o código de cálculo Python automaticamente em $\\LaTeX$. Como o handcalcs mostra a substituição numérica, os cálculos se tornam significativamente mais fáceis de visualizar e verificar manualmente. A ferramenta é extremamente útil em vários contextos, mas pode-se destacar seu destaque na ramo do ensino, podendo ser empregada tanto por professores produzindo material didático, quanto por alunos preparando trabalhos e relatórios.\n\n\n```python\nimport handcalcs.render\n```\n\nNós vamos ver a biblioteca na prática logo mais, caracterizada pelos blocos de código que começam com o comando mágico `%%render`:\n\n\n```python\n%%render\na = 2 # Eu sou um exemplo\nb = 3\nc = 2 * a + b / 3 # Olhe esse resultado!\n```\n\n> Leitura complementar:\n> * [Veja no GitHub](www.github.com/connorferster/handcalcs).\n\n#### Pint\n\nPint é um pacote Python para definir, operar e manipular quantidades físicas: o produto de um valor numérico e uma unidade de medida. Ele permite operações aritméticas entre eles e conversões de e para diferentes unidades.\n\n\n```python\nimport pint\n```\n\n\n```python\nureg = pint.UnitRegistry()\n```\n\nVeja o exemplo com a combinação de diferentes unidades de medida:\n\n\n```python\ndistancia = 3 * ureg(\"meter\") + 4 * ureg(\"centimeter\")\ndistancia\n```\n\nPodemos agora converter essa distância facilmente para outras unidades:\n\n\n```python\ndistancia.to(\"inch\")\n```\n\nVamos para um exemplo mais aplicado, com as propriedados do material (prata):\n\n\n```python\n%%render\nk = ( 429 * ureg(\"W/(m*K)\") ) # Condutividade térmica\nrho = ( 10.5e3 * ureg(\"kg/m**3\") ) # Massa específica\nc_p = ( 235 * ureg(\"J/(kg*K)\") ) # Calor específico\n```\n\nAgora calculamos a difusividade térmica (perceba a combinação com o Handcalcs):\n\n\n```python\n%%render\nalpha = k / (rho * c_p) # Difusividade térmica\n```\n\nNem sempre a simplificação de unidades é automática, mas podemos acionar manualmente:\n\n\n```python\nalpha.to_base_units()\n```\n\nNote que o uso de unidades também é compatível com os arranjos numéricos do NumPy:\n\n\n```python\nnp.linspace(0, 10, num=11) * ureg(\"hour\")\n```\n\n> Leitura recomendada:\n> * [Pint: makes units easy](https://pint.readthedocs.io/en/stable/)\n\n-----\n\n> **Felipe N. Schuch**,
\n> Pesquisador em Fluidodinâmica Computacional na PUCRS, com interesse em: Escoamentos turbulentos, transferência de calor e massa, e interação fluido-estrutura; Processamento e visualização de dados em Python; Jupyter Notebook como uma ferramenta de colaboração, pesquisa e ensino.
\n> [felipeschuch@outlook.com](mailto:felipeschuch@outlook.com \"Email\") [@fschuch](https://twitter.com/fschuch \"Twitter\") [Aprenda.py](https://fschuch.github.io/aprenda.py \"Blog\") [@aprenda.py](https://www.instagram.com/aprenda.py/ \"Instagram\")
\n\n-----\n", "meta": {"hexsha": "3acb593b0d0bd437dcded4a0a61b198aee9560d7", "size": 44944, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Aulas/01-Introducao.ipynb", "max_stars_repo_name": "fschuch/Python-Transferencia-de-Calor", "max_stars_repo_head_hexsha": "4504639af92a19940f99b5b171739bc960cc9400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-14T22:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T22:22:34.000Z", "max_issues_repo_path": "Aulas/01-Introducao.ipynb", "max_issues_repo_name": "fschuch/Python-Transferencia-de-Calor", "max_issues_repo_head_hexsha": "4504639af92a19940f99b5b171739bc960cc9400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Aulas/01-Introducao.ipynb", "max_forks_repo_name": "fschuch/Python-Transferencia-de-Calor", "max_forks_repo_head_hexsha": "4504639af92a19940f99b5b171739bc960cc9400", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3634311512, "max_line_length": 521, "alphanum_fraction": 0.5536000356, "converted": true, "num_tokens": 6739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.18667597642079725}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n#####Version 0.1\nWelcome to *Bayesian Methods for Hackers*. The full Github repository, and additional chapters, is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are a Bayesian practitioner! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n\n###The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty* about our beliefs. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist* methods assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these universes, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is clear how we can speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either heads or tails. Now what is *your* belief that the coin is heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease.\n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial evidence. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being heads. $P(A | X):\\;\\;$ You look at the coin, observe a heads has landed, denote this information $X$, and trivially assign probability 1.0 to heads and 0.0 to tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*.\n\n\n\n###Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: a probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools like Least Squares linear regression, LASSO regression, EM algorithm etc. are all very powerful and incredibly fast. Bayesian methods are a compliment to solve the problems these solutions cannot or to gain further insight into the underlying system by offering more flexibility in modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for matplotlib plots.\nIf executing this book, and you wish to use the book's styling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the book's styles/ dir.\n See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to update the styles\n in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n#the code below can be passed over, as it is currently not important.\n%pylab inline\nfigsize( 11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0,1,2,3,4,5,8,15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size = n_trials[-1] )\nx = np.linspace(0,1,100)\n\nfor k, N in enumerate(n_trials):\n sx = subplot( len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") if k in [0,len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads )\n plt.plot( x, y, label= \"observe %d tosses,\\n %d heads\"%(N,heads) )\n plt.fill_between( x, 0, y, color=\"#348ABD\", alpha = 0.4 )\n plt.vlines( 0.5, 0, 4, color = \"k\", linestyles = \"--\", lw=1 )\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight = True)\n\n\nplt.suptitle( \"Bayesian updating of posterior probabilities\", \n y = 1.02,\n fontsize = 14);\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our confidence is proportional to the height of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will lump closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5. As more data accumulates, we would see more and more probability being assigned at $p=0.5$.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n#####Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize(12.5,4)\np = np.linspace( 0,1, 50)\nplt.plot( p, 2*p/(1+p), color = \"#348ABD\", lw = 3 )\n#plt.fill_between( p, 2*p/(1+p), alpha = .5, facecolor = [\"#A60628\"])\nplt.scatter( 0.2, 2*(0.2)/1.2, s = 140, c =\"#348ABD\" )\nplt.xlim( 0, 1)\nplt.ylim( 0, 1)\nplt.xlabel( \"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title( \"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a graph of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize( 12.5, 4 )\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar( [0,.7], prior ,alpha = 0.70, width = 0.25, \\\n color = colours[0], label = \"prior distribution\",\n lw = \"3\", edgecolor = colours[0])\n\n\nplt.bar( [0+0.25,.7+0.25], posterior ,alpha = 0.7, \\\n width = 0.25, color = colours[1], \n label = \"posterior distribution\",\n lw = \"3\", edgecolor = colours[1])\n\nplt.xticks( [0.20,.95], [\"Bugs Absent\", \"Bugs Present\"] )\nplt.title(\"Prior and Posterior probability of bugs present, prior = 0.2\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\nWhat is $\\lambda$? It is called the parameter, and it describes the shape of the distribution. For the Poisson random variable, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne very useful property of the Poisson random variable, given we know $\\lambda$, is that its expected value is equal to the parameter, ie.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's something useful to remember. Below we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$ we add more probability to larger values occurring. Secondly, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize( 12.5, 4)\n\nimport scipy.stats as stats\na = np.arange( 16 )\npoi = stats.poisson\nlambda_ = [1.5, 4.25 ]\n\nplt.bar( a, poi.pmf( a, lambda_[0]), color=colours[0],\n label = \"$\\lambda = %.1f$\"%lambda_[0], alpha = 0.60,\n edgecolor = colours[0], lw = \"3\")\n\nplt.bar( a, poi.pmf( a, lambda_[1]), color=colours[1],\n label = \"$\\lambda = %.1f$\"%lambda_[1], alpha = 0.60,\n edgecolor = colours[1], lw = \"3\")\n\nplt.xticks( a + 0.4, a )\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with a *exponential density*. The density function for an exponential random variable looks like:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike the Poisson random variable, an exponential random variable can only take on non-negative values. But unlike a Poisson random variable, the exponential can take on *any* non-negative values, like 4.25 or 5.612401. This makes it a poor choice for count data, which must be integers, but a great choice for time data, or temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. Below are two probability density functions with different $\\lambda$ value. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0,4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l,c in zip(lambda_,colours):\n plt.plot( a, expo.pdf( a, scale=1./l), lw=3, \n color=c, label = \"$\\lambda = %.1f$\"%l)\n plt.fill_between( a, expo.pdf( a, scale=1./l), color=c, alpha = .33)\n \nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We only see $Z$, and must go backwards to try and determine $\\lambda$. The problem is so difficult because there is not a one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is better! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ is. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first: after all, $\\lambda$ is fixed, it is not (necessarily) random! How can we assign probabilities to a non-random event. Ah, we have fallen for the frequentist interpretation. Recall, under our Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, concerning text-message rates:\n\n> You are given a series of text-message counts from a user of your system. The data, plotted over time, appears in the graph below. You are curious if the user's text-messaging habits changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize( 12.5, 3.5 )\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar( np.arange( n_count_data ), count_data, color =\"#348ABD\" )\nplt.xlabel( \"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim( 0, n_count_data );\n```\n\nBefore we begin, with respect to the plot above, would you say there was a change in behaviour\nduring the time period? \n\nHow can we start to model this? Well, as I conveniently already introduced, a Poisson random variable would be a very appropriate model for this *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure about what the $\\lambda$ parameter is though. Looking at the chart above, it appears that the rate might become higher at some later date, which is equivalently saying the parameter $\\lambda$ increases at some later date (recall a higher $\\lambda$ means more probability on larger outcomes, that is, higher probability of many texts.).\n\nHow can we mathematically represent this? We can think, that at some later date (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we create two $\\lambda$ parameters, one for behaviour before the $\\tau$, and one for behaviour after. In literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\n If, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, the $\\lambda$'s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda_i, \\; i=1,2,$ can be any positive number. The *exponential* random variable has a density function for any positive number. This would be a good choice to model $\\lambda_i$. But, we need a parameter for this exponential distribution: call it $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter*, or a *parent-variable*, literally a parameter that influences other parameters. The influence is not too strong, so we can choose $\\alpha$ liberally. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data, since we're modeling $\\\\lambda$ using an Exponential distribution we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAlternatively, and something I encourage the reader to try, is to have two priors: one for each $\\lambda_i$; creating two exponential distributions with different $\\alpha$ values reflects a prior belief that the rate changed after some period.\n\nWhat about $\\tau$? Well, due to the randomness, it is too difficult to pick out when $\\tau$ might have occurred. Instead, we can assign an *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it would be an ugly, complicated, mess involving symbols only a mathematician would love. And things would only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution. We next turn to PyMC, a Python library for performing Bayesian analysis, that is agnostic to the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that documentation can be lacking in areas, especially the bridge between beginner to hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the above problem using the PyMC library. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random. The title is given because we create probability models using programming variables as the model's components, that is, model components are first-class primitives in this framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nDue to its poorly understood title, I'll refrain from using the name *probabilistic programming*. Instead, I'll simply use *programming*, as that is what it really is. \n\nThe PyMC code is easy to follow along: the only novel thing should be the syntax, and I will interrupt the code to explain sections. Simply remember we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as mc\n\n\n\nalpha = 1.0/count_data.mean() #recall count_data is \n #the variable that holds our txt counts\n\nlambda_1 = mc.Exponential( \"lambda_1\", alpha )\nlambda_2 = mc.Exponential( \"lambda_2\", alpha )\n\ntau = mc.DiscreteUniform( \"tau\", lower = 0, upper = n_count_data )\n```\n\nIn the above code, we create the PyMC variables corresponding to $\\lambda_1, \\; \\lambda_2$. We assign them to PyMC's *stochastic variables*, called stochastic variables because they are treated by the backend as random number generators. We can test this by calling their built-in `random()` method.\n\n\n```\nprint \"Random output:\", tau.random(),tau.random(), tau.random()\n```\n\n Random output: 58 31 17\n\n\n\n```\n@mc.deterministic\ndef lambda_( tau = tau, lambda_1 = lambda_1, lambda_2 = lambda_2 ):\n out = np.zeros( n_count_data ) \n out[:tau] = lambda_1 #lambda before tau is lambda1\n out[tau:] = lambda_2 #lambda after tau is lambda2\n return out\n```\n\nThis code is creating a new function `lambda_`, but really we think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet. The `@mc.deterministic` is a decorator to tell PyMC that this is a deterministic function, i.e., if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = mc.Poisson( \"obs\", lambda_, value = count_data, observed = True)\n\nmodel = mc.Model( [observation, lambda_1, lambda_2, tau] )\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we try to retrieve the results.\n\nThe below code will be explained in the Chapter 3, but this is where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (which I delay explaining until Chapter 3). It returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distribution looks like. Below, we collect the samples (called *traces* in MCMC literature) in histograms.\n\n\n```\n### Mysterious code to be explained in Chapter 3.\nmcmc = mc.MCMC(model)\nmcmc.sample( 40000, 10000, 1 )\n```\n\n [****************100%******************] 40000 of 40000 complete\n\n\n\n```\nlambda_1_samples = mcmc.trace( 'lambda_1' )[:]\nlambda_2_samples = mcmc.trace( 'lambda_2' )[:]\ntau_samples = mcmc.trace( 'tau' )[:]\n```\n\n\n```\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_1_samples, histtype='stepfilled', bins = 30, alpha = 0.85, \n label = \"posterior of $\\lambda_1$\", color = \"#A60628\",normed = True )\nplt.legend(loc = \"upper left\")\nplt.title(r\"Posterior distributions of the variables $\\lambda_1,\\;\\lambda_2,\\;\\tau$\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda_1$ value\")\nplt.ylabel(\"probability\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_2_samples,histtype='stepfilled', bins = 30, alpha = 0.85, \n label = \"posterior of $\\lambda_2$\",color=\"#7A68A6\", normed = True )\nplt.legend(loc = \"upper left\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda_2$ value\")\nplt.ylabel(\"probability\")\n\nplt.subplot(313)\n\n\nw = 1.0/ tau_samples.shape[0] * np.ones_like( tau_samples )\nplt.hist( tau_samples, bins = n_count_data, alpha = 1, \n label = r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth =2. )\nplt.xticks( np.arange( n_count_data ) )\n\nplt.legend(loc = \"upper left\");\nplt.ylim([0,.75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that the Bayesian methodology returns a *distribution*, hence we now have distributions to describe the unknown $\\lambda$'s and $\\tau$. What have we gained? Immediately we can see the uncertainty in our estimates: the more variance in the distribution, the less certain our posterior belief should be. We can also say what a plausible value for the parameters might be: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. What other observations can you make? Look at the data again, do these seem reasonable? The distributions of the two $\\\\lambda$s are positioned very differently, indicating that it's likely there was a change in the user's text-message behaviour.\n\nAlso notice that the posterior distributions for the $\\lambda$'s do not look like any exponential distributions, though we originally started modeling with exponential random variables. They are really not anything we recognize. But this is OK. This is one of the benefits of taking a computational point-of-view. If we had instead done this mathematically, we would have been stuck with a very analytically intractable (and messy) distribution. Via computations, we are agnostic to the tractability.\n\nOur analysis also returned a distribution for what $\\tau$ might be. Its posterior distribution looks a little different from the other two because it is a discrete random variable, hence it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance the users behaviour changed. Had no change occurred, or the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many values are likely candidates for $\\tau$. On the contrary, it is very peaked. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say we can perform amazingly useful things. For now, let's end this chapter with one more example. We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le70$? Recall that the expected value of a Poisson is equal to its parameter $\\lambda$, then the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, we are calculating the following: Let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change hadn't occurred yet), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n\n\n\n```\nfigsize( 12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\" \n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed, \n # and therefore lambda (the poisson parameter) is the expected value of \"message count\"\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum() \n + lambda_2_samples[~ix].sum() ) /N\n\n \nplt.plot( range( n_count_data), expected_texts_per_day, lw =4, color = \"#E24A33\", \n label = \"expected number of text-messages recieved\")\nplt.xlim( 0, n_count_data )\nplt.xlabel( \"Day\" )\nplt.ylabel( \"Expected # text-messages\" )\nplt.title( \"Expected number of text-messages received\")\nplt.ylim( 0, 50 )\nplt.bar( np.arange( len(count_data) ), count_data, color =\"#348ABD\", alpha = 0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and the change was sudden rather then gradual (demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-2-text subscription, or a new relationship. (The 45th day corresponds to Christmas, and I moved away to Toronto the next month leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** we know $\\tau$ is less than 45. That is, suppose we have new information as we know for certain that the change in behaviour occurred before day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part, just consider all instances where `tau_samples<45`. )\n\n\n```\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. .\n- [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "18b40753892c632f593f403690ee93d23fd8895e", "size": 417509, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "davharris/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "da484971cff5a9c7920e0c90761f29a46208d0bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T04:20:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T04:20:16.000Z", "max_issues_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "djv/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "ff9ee06a677efa522939f25d95ac87b9804440dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "djv/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "ff9ee06a677efa522939f25d95ac87b9804440dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2015-05-18T11:13:16.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-20T14:13:00.000Z", "avg_line_length": 403.000965251, "max_line_length": 112156, "alphanum_fraction": 0.9048499553, "converted": true, "num_tokens": 10963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.18654183934774518}} {"text": "# Plotting in the notebook\n\n### Aron Ahmadia (US Army ERDC) and David Ketcheson (KAUST)\n\n### Teaching Numerical Methods with IPython Notebooks, SciPy 2014\n\n
This lecture by Aron Ahmadia and David Ketcheson is licensed under a Creative Commons Attribution 4.0 International License. All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\n\n```\nfrom IPython.core.display import HTML\ncss_file = './example.css'\nHTML(open(css_file, \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nOne of the major advantages of the notebook over a traditional textbook is that **plots** of numerical solutions can be included with the **code** that produces them -- and the student can modify and execute that code, to see how the result changes! Better yet, **animations** and **interactive widgets** can be included to show the evolution of time-dependent solutions, or the dependence of results on some parameter(s). Here we'll explore some of the tools for producing such plots and animations. Some of these are very new and are still evolving rapidly.\n\nIn order to make things more interesting and relevant, we'll demonstrate these options in the context of a PDE solution.\n\n# The model\n\nWe'll solve a system of reaction-diffusion PDEs in two dimensions:\n\n\\begin{align}\nu_t & = \\delta D_1 \\nabla^2 u + f(u,v) \\\\\nv_t & = \\delta D_2 \\nabla^2 v + g(u,v)\n\\end{align}\n\nwhere $\\nabla^2 u = u_{xx} + u_{yy}$ denotes the Laplacian and $f,g$ represent reaction terms.\n\nFor simplicity, we'll consider the square domain $[-1,1]\\times[-1,1]$ with periodic boundary conditions; i.e., the conditions on $u(x,y,t)$ are\n\n\\begin{align}\nu(-1,y,t) & = u(1,y,t) \\\\\nu(x,-1,t) & = u(x,1,t)\n\\end{align}\n\nwith corresponding conditions on $v$. The reaction terms we will use are\n\n\\begin{align}\nf(u,v) & = \\alpha u (1-\\tau_1 v^2) + v(1-\\tau_2 u) \\\\\ng(u,v) & = \\beta v + \\alpha \\tau_1 u v^2 + u (\\gamma + \\tau_2 v).\n\\end{align}\n\n\n```\nimport numpy as np\nimport scipy.optimize\nimport scipy.sparse\n\ndef f(u,v):\n return alpha*u*(1-tau1*v**2) + v*(1-tau2*u);\n\ndef g(u,v):\n return beta*v*(1+alpha*tau1/beta*u*v) + u*(gamma+tau2*v);\n\ndef five_pt_laplacian_sparse_periodic(m,a,b):\n \"\"\"Construct a sparse matrix that applies the 5-point laplacian discretization\n with periodic BCs on all sides.\"\"\"\n e=np.ones(m**2)\n e2=([1]*(m-1)+[0])*m\n e3=([0]+[1]*(m-1))*m\n h=(b-a)/(m+1)\n A=scipy.sparse.spdiags([-4*e,e2,e3,e,e],[0,-1,1,-m,m],m**2,m**2)\n # Top & bottom BCs:\n A_periodic = scipy.sparse.spdiags([e,e],[m-m**2,m**2-m],m**2,m**2).tolil()\n # Left & right BCs:\n for i in range(m):\n A_periodic[i*m,(i+1)*m-1] = 1.\n A_periodic[(i+1)*m-1,i*m] = 1.\n A = A + A_periodic\n A/=h**2\n A = A.todia()\n return A\n\ndef one_step(u,v,k,A,delta,D1=0.5,D2=1.0):\n u_new = u + k * (delta*D1*A*u + f(u,v))\n v_new = v + k * (delta*D2*A*v + g(u,v))\n \n return u_new, v_new\n\ndef step_size(h,delta):\n return h**2/(5.*delta)\n```\n\n## Matplotlib: static plots\n\nAs a first example of a plot, let's just look at the sparsity structure of the numerical laplacian matrix produced by the provided function above. By default, matplotlib plots will open in a separate window, just as they would if we were plotting from an IPython command line. To get them to appear in the notebook, we use an IPython magic function\n\n\n```\n%matplotlib inline\n```\n\n\n```\nA = five_pt_laplacian_sparse_periodic(4,-1.,1.)\nimport matplotlib.pyplot as plt\nplt.spy(A)\n```\n\nNow let's solve the reaction-diffusion PDE and plot the solution (note that the methods we're using here are not very accurate or efficient, but they're good enough to give a qualitatively correct solution in reasonable time on a small grid).\n\n\n```\ndelta=0.0021; tau1=3.5; tau2=0; alpha=0.899; beta=-0.91; gamma=-alpha;\n\ndef set_up(m, T, a=-1., b=1.):\n # Set up the grid\n a=-1.; b=1.\n h=(b-a)/m; # Grid spacing\n x = np.linspace(a,b,m) # Coordinates\n y = np.linspace(a,b,m)\n\n # Initial data\n u=np.random.randn(m,m)/2.;\n v=np.random.randn(m,m)/2.;\n\n plt.clf(); plt.hold(False)\n plt.pcolormesh(x,y,u); plt.colorbar(); plt.axis('image');\n plt.draw()\n \n u=u.reshape(-1)\n v=v.reshape(-1)\n\n A=five_pt_laplacian_sparse_periodic(m,-1.,1.)\n\n k = step_size(h,delta) # Time step size\n N = int(round(T/k)) # Number of steps to take\n \n return x, y, u, v, A, k, N\n \ndef pattern_formation(m,T):\n r\"\"\"Model pattern formation by solving a reaction-diffusion PDE on a periodic\n square domain with an m x m grid.\"\"\"\n x, y, u, v, A, k, N = set_up(m,T)\n t=0. # Initial time\n \n #Now step forward in time\n for j in range(N):\n\n u,v = one_step(u,v,k,A,delta) \n t = t+k;\n\n # Plot the final solution\n U=u.reshape((m,m))\n\n plt.pcolormesh(x,y,U)\n plt.colorbar()\n plt.axis('image')\n plt.show()\n```\n\n\n```\npattern_formation(m=100,T=200)\n```\n\nHaving the plot in the notebook is nice, but there are major drawbacks:\n\n- We can't zoom or pan the plot interactively\n- If a single cell produces multiple plots, only the last one appears (try it)\n- Thus we only see the final state of a time-dependent solution\n\nThere are straightforward ways to get multiple plots from one cell, and even to plot several snapshots of a time-dependent solution. But it would be much nicer if the solution plot actually evolved in time. Here's a crude way to accomplish that:\n\n\n```\nimport time\nfrom IPython.display import display, clear_output\n\ndef pattern_formation(m,T):\n x, y, u, v, A, k, N = set_up(m,T)\n t=0. # Initial time\n \n #Now step forward in time\n next_plot = 0\n for j in range(N):\n\n u,v = one_step(u,v,k,A,delta) \n t = t+k;\n\n #Plot every t=5 units\n if t>next_plot:\n clear_output(wait=True)\n next_plot = next_plot + 5\n U=u.reshape((m,m))\n time.sleep(0.2)\n plt.pcolormesh(x,y,U); plt.axis('image'); plt.title(str(t))\n fig=plt.gcf(); display(fig)\n \n return U\n```\n\n\n```\nU = pattern_formation(m=100,T=50)\nplt.close('all')\n```\n\nSee [this notebook for more examples of using `clear_output`](http://nbviewer.ipython.org/github/ipython/ipython/blob/2.x/examples/Notebook/Animations%20Using%20clear_output.ipynb).\n\n## Interactive plots\n\nWhat if we want to be able to zoom and pan? That's a bit harder, but there are multiple solutions either just developed or in the works. \n\n### Plotly\n\nOne is [Plotly](https://plot.ly/plot), a web-based service that generates interactive plots and allows them to be embedded in the notebook. To use it, you should set up an account. But for this tutorial, you can just run the following code using my account.\n\n\n```\nimport plotly\nimport plotly.plotly as py \npy.sign_in('DavidKetcheson','mgs2lgb203')\n\npy.iplot([plotly.graph_objs.Heatmap(z=U)],width=500,height=500)\n```\n\nNotice that you can get actual data values by hovering over the plot. You can also adjust the plot's look interactively on the Plotly website. For many more examples of using Plotly in the IPython notebook, see [this notebook](http://nbviewer.ipython.org/gist/chriddyp/7628933) and [this notebook](http://nbviewer.ipython.org/github/plotly/IPython-plotly/blob/master/Plotly%20Quickstart.ipynb), both of which are introductions to Plotly. For a few more examples of plotting numerical simulation results with Plotly, look at [my notebook on Stegotons](http://nbviewer.ipython.org/gist/ketch/8554686).\n\nImportantly, usage of Plotly requires an internet connection.\n\n### Bokeh\n\nAnother package that can produce interactive plots in the notebook (this time without needing an internet connection) is [Bokeh](http://bokeh.pydata.org/). I couldn't get a `pcolor` plot example working with Bokeh (I think it's possible, but it's in beta and changing rapidly). Here is a very simple line plot example.\n\n\n```\nfrom bokeh.plotting import output_notebook, scatter, show, line\noutput_notebook()\n```\n\n\n```\nx = np.linspace(0, 4*np.pi, 100)\ny = np.sin(x)\nline(x,y, color=\"#FF00FF\", tools=\"pan,wheel_zoom,box_zoom,reset,resize\")\nshow()\n```\n\nAnimated plots are also possible with Bokeh, but we won't spend more time on it because the interface will change in the near future (they plan to integrate with IPython widgets).\n\n### Other prospects\n\nSome other projects that allow (or may soon allow) for interactive plots in the browser include:\n\n- [mpld3](http://mpld3.github.io/): a combination of matplotlib and [D3js](http://d3js.org/). See [examples here](http://mpld3.github.io/examples/index.html#example-gallery).\n- [Vincent](http://vincent.readthedocs.org/en/latest/index.html)\n- [Vispy](http://vispy.org/)\n\nThe last two are still too new to go into in this tutorial, but may be useful soon.\n\n## JSAnimation: animated plots\n\nThanks to Jake Vanderplas' [JSAnimation](http://nbviewer.ipython.org/github/jakevdp/JSAnimation/blob/master/animation_example.ipynb) library, we have a much better way to include animations of time-dependent solutions. I've been using JSAnimation heavily in my teaching notebooks, but it will soon be replaced by tools based on IPython widgets.\n\n### Installing JSAnimation\n\nIf you're running on SageMathCloud, you already have access to JSAnimation through Clawpack, via\n\n from clawpack.visclaw.JSAnimation import IPython_display\n \nIf you're working locally, the easiest way to get it is\n\n git clone https://github.com/jakevdp/JSAnimation.git\n cd JSAnimation\n python setup.py install\n \nafter which you can\n\n from JSAnimation import IPython_display\n\n\n```\ndef pattern_formation(m=10,T=1000):\n # Set up the grid\n a=-1.; b=1.\n h=(b-a)/m; # Grid spacing\n x = np.linspace(a,b,m) # Coordinates\n y = np.linspace(a,b,m)\n Y,X = np.meshgrid(y,x)\n\n # Initial data\n u=np.random.randn(m,m)/2.;\n v=np.random.randn(m,m)/2.;\n\n frames = [u]\n \n u=u.reshape(-1)\n v=v.reshape(-1)\n\n A=five_pt_laplacian_sparse_periodic(m,-1.,1.)\n\n t=0. # Initial time\n k = step_size(h,delta) # Time step size\n N = int(round(T/k)) # Number of steps to take\n \n #Now step forward in time\n next_plot = 0\n for j in range(N):\n #Plot every t=5 units\n if t>=next_plot:\n next_plot = next_plot + 5\n U=u.reshape((m,m))\n frames.append(U)\n \n u,v = one_step(u,v,k,A,delta)\n t = t+k;\n \n return x,y,frames\n```\n\n\n```\nx, y, frames = pattern_formation(m=100,T=200)\n```\n\n\n```\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt\n#from clawpack.visclaw.JSAnimation import IPython_display # Works on SMC\nfrom JSAnimation import IPython_display\nimport numpy as np\n\nfig = plt.figure(figsize=[4,4])\n\nU = frames[0]\n\n# This essentially does a pcolor plot, but it returns the appropriate object\n# for use in animation. See http://matplotlib.org/examples/pylab_examples/pcolor_demo.html.\n# Note that it's necessary to transpose the data array because of the way imshow works.\nplot_handle = plt.imshow(U.T, vmin=U.min(), vmax=U.max(),\n extent=[x.min(), x.max(), y.min(), y.max()],\n interpolation='nearest', origin='lower')\n\ndef fplot(frame_number):\n U = frames[frame_number]\n plot_handle.set_data(U.T)\n return plot_handle,\n\nanimation.FuncAnimation(fig, fplot, frames=len(frames), interval=20)\n```\n\nNotice that `FuncAnimation` takes three arguments:\n\n- A matplotlib figure\n- A plotting function\n- A list of frame indices\n\nUsing JSAnimation can be a little tricky, because we need to provide a function (called `fplot` here) that returns a handle to a plot of one frame of the solution. It's not enough for `fplot` to simply plot the solution. That's why we first get a handle to the plot and then use `set_data` to modify the plot each time `fplot` is called.\n\nAlso, notice that the `frames` argument can be any list. Typically, it would be a list of numbers, but more generally it is just the list of argument values that need to be passed to `fplot`.\n\nSee also: IPython widgets (up next)\n", "meta": {"hexsha": "9e6ad04c7b73e001cce3754b4f24f16c7fb172ca", "size": 24985, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Plotting in the notebook.ipynb", "max_stars_repo_name": "ketch/teaching-numerics-with-notebooks", "max_stars_repo_head_hexsha": "f38dcbbf2bde1bec534ba66c450017b3e570fd9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2015-01-30T12:14:23.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-02T21:58:48.000Z", "max_issues_repo_path": "Plotting in the notebook.ipynb", "max_issues_repo_name": "ketch/teaching-numerics-with-notebooks", "max_issues_repo_head_hexsha": "f38dcbbf2bde1bec534ba66c450017b3e570fd9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plotting in the notebook.ipynb", "max_forks_repo_name": "ketch/teaching-numerics-with-notebooks", "max_forks_repo_head_hexsha": "f38dcbbf2bde1bec534ba66c450017b3e570fd9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-02-19T13:54:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T16:42:19.000Z", "avg_line_length": 34.7013888889, "max_line_length": 695, "alphanum_fraction": 0.5129877927, "converted": true, "num_tokens": 4290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.18587306596160413}} {"text": "\n\n## Data-driven Design and Analyses of Structures and Materials (3dasm)\n\n## Lecture 7\n\n### Miguel A. Bessa | M.A.Bessa@tudelft.nl | Associate Professor\n\n**What:** A lecture of the \"3dasm\" course\n\n**Where:** This notebook comes from this [repository](https://github.com/bessagroup/3dasm_course)\n\n**Reference for entire course:** Murphy, Kevin P. *Probabilistic machine learning: an introduction*. MIT press, 2022. Available online [here](https://probml.github.io/pml-book/book1.html)\n\n**How:** We try to follow Murphy's book closely, but the sequence of Chapters and Sections is different. The intention is to use notebooks as an introduction to the topic and Murphy's book as a resource.\n* If working offline: Go through this notebook and read the book.\n* If attending class in person: listen to me (!) but also go through the notebook in your laptop at the same time. Read the book.\n* If attending lectures remotely: listen to me (!) via Zoom and (ideally) use two screens where you have the notebook open in 1 screen and you see the lectures on the other. Read the book.\n\n**Optional reference (the \"bible\" by the \"bishop\"... pun intended 😆) :** Bishop, Christopher M. *Pattern recognition and machine learning*. Springer Verlag, 2006.\n\n**References/resources to create this notebook:**\n* [Car figure](https://korkortonline.se/en/theory/reaction-braking-stopping/)\n\nApologies in advance if I missed some reference used in this notebook. Please contact me if that is the case, and I will gladly include it here.\n\n## **OPTION 1**. Run this notebook **locally in your computer**:\n1. Confirm that you have the 3dasm conda environment (see Lecture 1).\n\n2. Go to the 3dasm_course folder in your computer and pull the last updates of the [repository](https://github.com/bessagroup/3dasm_course):\n```\ngit pull\n```\n3. Open command window and load jupyter notebook (it will open in your internet browser):\n```\nconda activate 3dasm\njupyter notebook\n```\n4. Open notebook of this Lecture.\n\n## **OPTION 2**. Use **Google's Colab** (no installation required, but times out if idle):\n\n1. go to https://colab.research.google.com\n2. login\n3. File > Open notebook\n4. click on Github (no need to login or authorize anything)\n5. paste the git link: https://github.com/bessagroup/3dasm_course\n6. click search and then click on the notebook for this Lecture.\n\n\n```python\n# Basic plotting tools needed in Python.\n\nimport matplotlib.pyplot as plt # import plotting tools to create figures\nimport numpy as np # import numpy to handle a lot of things!\nfrom IPython.display import display, Math # to print with Latex math\n\n%config InlineBackend.figure_format = \"retina\" # render higher resolution images in the notebook\nplt.style.use(\"seaborn\") # style for plotting that comes from seaborn\nplt.rcParams[\"figure.figsize\"] = (8,4) # rescale figure size appropriately for slides\n```\n\n## Outline for today\n\n* Understanding the Posterior Predictive Distribution (PPD)\n - Solution and discussion of Homework of Lecture 6\n\n**Reading material**: This notebook\n\n## Solution to Homework of Lecture 6\n\n### Summary of the model\n\n1. The **observation distribution**:\n\n$$\np(y|z) = \\mathcal{N}\\left(y | \\mu_{y|z}=w z+b, \\sigma_{y|z}^2\\right) = \\frac{1}{C_{y|z}} \\exp\\left[ -\\frac{1}{2\\sigma_{y|z}^2}(y-\\mu_{y|z})^2\\right]\n$$\n\nwhere $C_{y|z} = \\sqrt{2\\pi \\sigma_{y|z}^2}$ is the **normalization constant** of the Gaussian pdf, and where $\\mu_{y|z}=w z+b$, with $w$, $b$ and $\\sigma_{y|z}^2$ being constants.\n\n2. but now assuming a different **prior distribution**: $p(z) = \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle <}{\\mu}_z=3, \\overset{\\scriptscriptstyle <}{\\sigma}_z^2=2^2\n\\right)$\n\nAs in Lecture 6, we start by using Bayes' rule applied to data to determine the posterior:\n\n$\\require{color}$\n$$\n{\\color{green}p(z|y=\\mathcal{D}_y)} = \\frac{ {\\color{blue}p(y=\\mathcal{D}_y|z)}{\\color{red}p(z)} } {p(y=\\mathcal{D}_y)}\n$$\n\nThe likelihood is the same as in Lecture 6:\n\n$$\n{\\color{blue}p(y=\\mathcal{D}_y | z)} = \\frac{1}{|w|^N} \\cdot C \\cdot \\frac{1}{\\sqrt{2\\pi \\sigma^2}} \\exp\\left[ -\\frac{1}{2\\sigma^2}(z-\\mu)^2\\right]\n$$\n\nwhere $\\mu = \\frac{w^2\\sigma^2}{\\sigma_{y|z}^2} \\sum_{i=1}^N \\mu_i = \\frac{\\sum_{i=1}^N y_i}{w N}-\\frac{b}{w}$\n\n$\\sigma^2 = \\frac{\\sigma_{y|z}^2}{w^2 N}$, and\n\n$C = \\frac{1}{2\\pi^{(N-1)/2}} \\sqrt{\\frac{\\sigma^2}{\\left( \\frac{\\sigma_{y|z}^2}{w^2}\\right)^N}}\n$\n\nBut now the marginal likelihood is different from Lecture 6 because we have a different prior:\n\n$$\np(y=\\mathcal{D}_y) = \\frac{C\\cdot C_M}{|w|^N}\n$$\n\nwhere $C_M = \\frac{1}{\\sqrt{2\\pi\\left(\\sigma^2+\\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)}} \\exp\\left[-\\frac{1}{2\\left(\\sigma^2+\\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)}\\left(\\mu - \\overset{\\scriptscriptstyle <}{\\mu}_z\\right)^2 \\right]$.\n\n(Algebra to get this result is in the notes below.)\n\n#### Note: calculation of the marginal likelihood for Homework of Lecture 6\n\n$$\\begin{align}\np(y=\\mathcal{D}_y) &= \\int p(y=\\mathcal{D}_y | z) p(z) dz \\\\\n&= \\int \\frac{1}{|w|^N} C \\cdot \\mathcal{N}(z|\\mu, \\sigma^2)\\cdot \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle <}{\\mu}_z, \\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right) dz\\\\\n&= \\frac{C}{|w|^N} \\int C_M\\mathcal{N}\\left(z\\left|\\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right), \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\right.\\right) dz = \\frac{C\\cdot C_M}{|w|^N} \\\\\n\\end{align}\n$$\n\nwhere $C_M = \\frac{1}{\\sqrt{2\\pi\\left(\\sigma^2+\\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)}} \\exp\\left[-\\frac{1}{2\\left(\\sigma^2+\\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)}\\left(\\mu - \\overset{\\scriptscriptstyle <}{\\mu}_z\\right)^2 \\right]$\n\nTherefore, the posterior will also be different:\n\n$$\\require{color}\\begin{align}\n{\\color{green}p(z|y=\\mathcal{D}_y)} &= \\frac{ p(y=\\mathcal{D}_y|z)p(z) } {p(y=\\mathcal{D}_y)} \\\\\n&= \\frac{|w|^N}{C\\cdot C_M} \\cdot \\frac{1}{|w|^N} C \\cdot \\mathcal{N}(z|\\mu,\\sigma^2) \\cdot \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle <}{\\mu}_z, \\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right) \\\\\n&= \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle >}{\\mu}_z, \\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right)\n\\end{align}\n$$\n\nwhere $\\overset{\\scriptscriptstyle >}{\\mu}_z = \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right)$\n\nand $\\overset{\\scriptscriptstyle >}{\\sigma}_z^2 = \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}$\n\nare the parameters of the posterior distribution, symbolized by the superscript $\\overset{\\scriptscriptstyle >}{(\\cdot)}$.\n\nReflection on the differences between the posterior we obtain for the two different priors we considered.\n\n* When using the noninformative Uniform prior $p(z) = \\frac{1}{C_z}$ (Lecture 6):\n\n$$\\require{color}\\begin{align}\n{\\color{green}p(z|y=\\mathcal{D}_y)}\n&= \\mathcal{N}(z|\\mu, \\sigma^2)\n\\end{align}\n$$\n\n* When using a Gaussian prior $p(z) = \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle <}{\\mu}_z, \\overset{\\scriptscriptstyle <}{\\sigma}_z^2\\right)$ (this Lecture):\n\n$$\\require{color}\\begin{align}\n{\\color{green}p(z|y=\\mathcal{D}_y)} &= \\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle >}{\\mu}_z, \\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right) = \\mathcal{N}\\left(z\\left|\\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right), \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\right.\\right)\n\\end{align}\n$$\n\nThe posterior is still a Gaussian but its mean and variance have been updated by the influence of the prior!\n\nFinally, the goal of calculating the posterior is to use it to determine the Posterior Predictive Distribution (PPD) :\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\int \\underbrace{p(y|z)}_{\\text{observation}\\\\ \\text{distribution}} \\overbrace{p(z|y=\\mathcal{D}_y)}^{\\text{posterior}} dz\n$$\n\nConsidering the terms we found before, we get:\n\n$$\\begin{align}\np(y|\\mathcal{D}_y) &= \\int \\underbrace{\\frac{1}{|w|}\\frac{1}{\\sqrt{2\\pi \\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}} \\exp\\left\\{ -\\frac{1}{2\\left(\\frac{\\sigma_{y|z}}{w}\\right)^2}\\left[z-\\left(\\frac{y-b}{w}\\right)\\right]^2\\right\\} }_{\\text{observation}\\\\ \\text{distribution}} \\overbrace{\\mathcal{N}\\left(z| \\overset{\\scriptscriptstyle >}{\\mu}_z, \\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right)}^{\\text{posterior}} dz\n\\end{align}\n$$\n\nThe calculation of this integral is similar to what we did in Lecture 6! The difference is that the posterior has a different mean and variance (indicated with the superscript) that originated from the choice of different prior!\n\nSo, we can fast forward to the result we obtained before! We just need to replace the symbols $\\mu_z$ by $\\overset{\\scriptscriptstyle >}{\\mu}_z$, and $\\sigma_z^2$ for $\\overset{\\scriptscriptstyle >}{\\sigma}_z^2$:\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\frac{\\tilde{C}}{|w|} \n$$\n\nwhere\n\n$$\\tilde{C} = \\frac{1}{\\sqrt{2\\pi \\left( \\overset{\\scriptscriptstyle >}{\\sigma}_z^2 + \\frac{\\sigma_{y|z}^2}{w^2} \\right)}}\\exp\\left[ - \\frac{\\left(\\overset{\\scriptscriptstyle >}{\\mu}_z - \\frac{y-b}{w}\\right)^2}{2\\left( \\overset{\\scriptscriptstyle >}{\\sigma}_z^2+\\frac{\\sigma_{y|z}^2}{w^2}\\right)}\\right]$$\n\nis the same constant as $C^*$ in Lecture 6, but replacing $\\mu_z$ by $\\overset{\\scriptscriptstyle >}{\\mu}_z$, and $\\sigma_z^2$ for $\\overset{\\scriptscriptstyle >}{\\sigma}_z^2$.\n\nAfter a bit of algebra, we get to the following expression for the PPD:\n\n$$\\require{color}\n\\begin{align}\n{\\color{orange}p(y|\\mathcal{D}_y)} &= \\frac{1}{\\sqrt{2\\pi \\left( \\sigma_{y|z}^2 + w^2\\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right)}}\\exp\\left\\{ - \\frac{1}{2\\left( \\sigma_{y|z}^2 + w^2\\overset{\\scriptscriptstyle >}{\\sigma}_z^2\\right)}\\left[y-\\left(w\\overset{\\scriptscriptstyle >}{\\mu}_z+b\\right)\\right]^2\\right\\} \\\\\n&= \\mathcal{N}\\left(y \\left| w\\overset{\\scriptscriptstyle >}{\\mu}_z+b , \\sigma_{y|z}^2 + w^2\\overset{\\scriptscriptstyle >}{\\sigma}_z^2 \\right.\\right) \\\\\n\\end{align}\n$$\n\nwhere all of the terms have been defined before (for convenience, see them in the next cell as notes).\n\n#### Note: PPD when using a Gaussian prior (Homework of Lecture 6)\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\mathcal{N}\\left(y \\left| w\\overset{\\scriptscriptstyle >}{\\mu}_z+b , \\sigma_{y|z}^2 + w^2\\overset{\\scriptscriptstyle >}{\\sigma}_z^2 \\right.\\right)$$\n\n$b = \\mu_{z_2} x^2 = 0.1 \\cdot 75^2 = 562.5$\n\n$w = x = 75$\n\n$\\sigma_{y|z}^2 = (x^2 \\sigma_{z_2})^2=(75^2\\cdot0.01)^2=56.25^2$.\n\n$\\overset{\\scriptscriptstyle >}{\\mu}_z = \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right) = \\frac{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2 \\sigma^2}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2+\\sigma^2} \\left( \\frac{\\mu}{\\sigma^2} + \\frac{\\overset{\\scriptscriptstyle <}{\\mu}_z}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\right) = \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2+\\sigma^2}\\left( \\mu \\overset{\\scriptscriptstyle <}{\\sigma}_z^2 + \\overset{\\scriptscriptstyle <}{\\mu}_z \\sigma^2\\right)$\n\n$\\overset{\\scriptscriptstyle >}{\\sigma}_z^2 = \\frac{1}{\\frac{1}{\\sigma^2} + \\frac{1}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}} = \\frac{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2 \\sigma^2}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2+\\sigma^2}$\n\n$\\sigma^2 = \\frac{\\sigma_{y|z}^2}{w^2 N} = \\frac{(x^2\\cdot\\sigma_{z_2})^2}{x^2 N} = \\frac{x^2\\cdot\\sigma_{z_2}^2}{N} $\n\n$\\mu = \\frac{w^2 \\sigma^2}{\\sigma_{y|z}^2} \\sum_{i=1}^{N} \\mu_i = \\cdots = \\frac{\\sum_{i=1}^N y_i}{w N}-\\frac{b}{w}$\n\nIn order to see the explicit dependence on the observed data $\\mathcal{D}_y$, we can also rewrite the PPD as:\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\mathcal{N}\\left(y \\left| \\mu^*, \\sigma^* \\right.\\right)\n$$\n\nwhere\n\n$\n\\mu^* = \\frac{1}{1+\\frac{x^2\\sigma_{z_2}^2}{N \\overset{\\scriptscriptstyle <}{\\sigma}_z^2}}\\left[\\frac{\\sum_{i=1}^N y_i}{N} + \\frac{x^2\\sigma_{z_2}^2}{N \\overset{\\scriptscriptstyle <}{\\sigma}_z^2}\\left( w \\overset{\\scriptscriptstyle <}{\\mu}_z + b\\right) \\right]\n$\n\n$\n\\left(\\sigma^*\\right)^2 = \\sigma_{y|z}^2 + \\frac{w^2\\sigma^2\\overset{\\scriptscriptstyle <}{\\sigma}_z^2}{\\overset{\\scriptscriptstyle <}{\\sigma}_z^2+\\sigma^2} = \\sigma_{y|z}^2 + \\frac{w^2 x^2 \\sigma_{z_2}^2 \\overset{\\scriptscriptstyle <}{\\sigma}_z^2}{N \\overset{\\scriptscriptstyle <}{\\sigma}_z^2 + x^2 \\sigma_{z_2}^2}\n$\n\n* What happens when $N \\rightarrow \\infty$ ?\n\nWhen $N \\rightarrow \\infty$ the mean and variance of the PPD become:\n\n$$\n\\mu^* = \\frac{\\sum_{i=1}^N y_i}{N} \\equiv \\text{Empirical mean}\n$$\n\n$$\n\\left(\\sigma^*\\right)^2 = \\sigma_{y|z}^2 = (x^2 \\sigma_{z_2})^2 \\equiv \\text{Variance caused only from } z_2 \\text{ rv}\n$$\n\nSo, in this limit of the PPD is simply:\n\n$$\\require{color}\n{\\color{orange}p(y|\\mathcal{D}_y)} = \\mathcal{N}\\left(y \\left| \\frac{\\sum_{i=1}^N y_i}{N}, \\sigma_{y|z}^2 \\right.\\right) \\quad \\text{when } N\\rightarrow \\infty\n$$\n\n* This means that in the limit of $N \\rightarrow \\infty$ we have exactly the same result obtained when we used the noninformative Uniform prior! Were you expecting this? Let's debate!\n\n\n```python\n# This cell is hidden during presentation. It's just to define a function to plot the governing model of\n# the car stopping distance problem. Defining a function that creates a plot allows to repeatedly run\n# this function on cells used in this notebook.\ndef car_fig_2rvs(ax):\n x = np.linspace(3, 83, 1000)\n mu_z1 = 1.5; sigma_z1 = 0.5; # parameters of the \"true\" p(z_1)\n mu_z2 = 0.1; sigma_z2 = 0.01; # parameters of the \"true\" p(z_2)\n mu_y = mu_z1*x + mu_z2*x**2 # From Homework of Lecture 4\n sigma_y = np.sqrt( (x*sigma_z1)**2 + (x**2*sigma_z2)**2 ) # From Homework of Lecture 4\n ax.set_xlabel(\"x (m/s)\", fontsize=20) # create x-axis label with font size 20\n ax.set_ylabel(\"y (m)\", fontsize=20) # create y-axis label with font size 20\n ax.set_title(\"Car stopping distance problem with two rv's\", fontsize=20); # create title with font size 20\n ax.plot(x, mu_y, 'k:', label=\"Governing model $\\mu_y$\")\n ax.fill_between(x, mu_y - 1.9600 * sigma_y,\n mu_y + 1.9600 * sigma_y,\n color='k', alpha=0.2,\n label='95% confidence interval ($\\mu_y \\pm 1.96\\sigma_y$)') # plot 95% credence interval\n ax.legend(fontsize=15)\n```\n\n\n```python\n# This cell is hidden during the presentation\nfrom scipy.stats import norm # import the normal dist, as we learned before!\ndef samples_y_with_2rvs(N_samples,x): # observations/measurements/samples for car stop. dist. prob. with 2 rv's\n mu_z1 = 1.5; sigma_z1 = 0.5;\n mu_z2 = 0.1; sigma_z2 = 0.01;\n samples_z1 = norm.rvs(mu_z1, sigma_z1, size=N_samples) # randomly draw samples from the normal dist.\n samples_z2 = norm.rvs(mu_z2, sigma_z2, size=N_samples) # randomly draw samples from the normal dist.\n samples_y = samples_z1*x + samples_z2*x**2 # compute the stopping distance for samples of z_1 and z_2\n return samples_y # return samples of y\n```\n\n\n```python\n# This cell is hidden during presentation\ndef HW_Lec6_PPD_comparison(N_samples): # PLOT PPD for Homework and compare it to data and PPD of Lecture 6\n fig_car_PPD, ax_car_PPD = plt.subplots(1,2)\n x = 75\n mu_z2 = 0.1; sigma_z2 = 0.01\n # Observation of N_samples from the true data:\n empirical_y = samples_y_with_2rvs(N_samples, x) # Empirical measurements of N_samples at x=75\n # Empirical mean and std directly calculated from observations:\n empirical_mu_y = np.mean(empirical_y); empirical_sigma_y = np.std(empirical_y); \n #\n # Now define all the constants needed in the calculation of the PPD's obtained with each prior.\n w = x\n b = mu_z2*x**2\n sigma_yGIVENz = np.sqrt((x**2*sigma_z2)**2) # sigma_y|z (comes from the stochastic influence of the z_2 rv)\n sigma = np.sqrt(sigma_yGIVENz**2/(w**2*N_samples)) # std arising from the likelihood\n mu = empirical_mu_y/w - b/w # mean arising from the likelihood (product of Gaussian densities for the data)\n #\n # Now, calculate PPD when using a UNIFORM prior (Lecture 6):\n PPD_mu_y_UniformPrior = mu*w + b # same result if using: np.mean(empirical_y)\n PPD_sigma_y_UniformPrior = np.sqrt(w**2*sigma**2+sigma_yGIVENz**2) # same as: np.sqrt((x**2*sigma_z2)**2*(1/N_samples + 1))\n \n # Now, calcualte PPD when using the GAUSSIAN prior (Homework of Lecture 6):\n mu_prior_z = 3; sigma_prior_z = 2 # parameters of the Gaussian prior distribution \n sigma_posterior_z = np.sqrt( (sigma_prior_z**2*sigma**2)/(sigma_prior_z**2+sigma**2) )# std of posterior\n mu_posterior_z = sigma_posterior_z**2*( mu/(sigma**2) + mu_prior_z/(sigma_prior_z**2) ) # mean of posterior\n PPD_mu_y_GaussianPrior = mu_posterior_z*w + b\n PPD_sigma_y_GaussianPrior = np.sqrt(w**2*sigma_posterior_z**2+sigma_yGIVENz**2)\n #\n car_fig_2rvs(ax_car_PPD[0]) # a function I created to include the background plot of the governing model\n for i in range(2): # create two plots (one is zooming in on the error bar)\n ax_car_PPD[i].errorbar(x , empirical_mu_y,yerr=1.96*empirical_sigma_y, fmt='m*',\n markersize=30, elinewidth=9);\n ax_car_PPD[i].errorbar(x , PPD_mu_y_UniformPrior,yerr=1.96*PPD_sigma_y_UniformPrior,\n color='#F39C12', fmt='*', markersize=15, elinewidth=6);\n ax_car_PPD[i].errorbar(x , PPD_mu_y_GaussianPrior,yerr=1.96*PPD_sigma_y_GaussianPrior,\n fmt='b*', markersize=10, elinewidth=3);\n ax_car_PPD[i].scatter(x*np.ones_like(empirical_y),empirical_y, s=150,facecolors='none',\n edgecolors='k', linewidths=2.0)\n print(\"Ground truth : mean[y] = 675 & std[y] = 67.6\")\n print(\"Empirical values (purple) : mean[y] = %.2f & std[y] = %.2f\" % (empirical_mu_y,empirical_sigma_y) )\n print(\"PPD with Uniform Prior (orange): mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_UniformPrior, PPD_sigma_y_UniformPrior))\n print(\"PPD with Gaussian Prior (blue) : mean[y] = %.2f & std[y] = %.2f\" % (PPD_mu_y_GaussianPrior,PPD_sigma_y_GaussianPrior))\n fig_car_PPD.set_size_inches(15, 6) # scale figure to be wider (since there are 2 subplots)\n```\n\n\n```python\nHW_Lec6_PPD_comparison(N_samples=2) # Plot data and the two PPD's considering different priors\n```\n\n### See you next class\n\nHave fun!\n", "meta": {"hexsha": "68fe9b16fbfa36acd0e767fc99ea28f9511e2de6", "size": 161870, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lectures/Lecture7/3dasm_Lecture7.ipynb", "max_stars_repo_name": "shushu-qin/3dasm_course", "max_stars_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2022-02-07T18:45:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T21:45:27.000Z", "max_issues_repo_path": "Lectures/Lecture7/3dasm_Lecture7.ipynb", "max_issues_repo_name": "shushu-qin/3dasm_course", "max_issues_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Lecture7/3dasm_Lecture7.ipynb", "max_forks_repo_name": "shushu-qin/3dasm_course", "max_forks_repo_head_hexsha": "a53ce9f8d7c692a9b1356946ec11e60b35b7bbcd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2022-02-07T18:45:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T19:30:17.000Z", "avg_line_length": 247.886676876, "max_line_length": 134132, "alphanum_fraction": 0.8968987459, "converted": true, "num_tokens": 6501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.18587306003330337}} {"text": "\n\n##**Chapter 10 – Introduction to Neural Networks with Keras**\n\n
\n
Photo Credits: Galaxy's Edge by Rod Long licensed under the Unsplash License \n\n> *The defnition of AI is a highly contested concept. It often refers to technologies that demonstrate levels of independent intelligence from humans. By its very\ndefnition, it is an intelligence that is differentiated from natural intelligence; it is\na constructed, artificial, or machine intelligence.*
\n$\\quad$Ryan, M. (2020). In AI we trust: ethics, artificial intelligence, and reliability. Science and Engineering Ethics, 26(5), 2749-2767.\n\nThis notebook will be used in the lab session for week 5 of the course, covers Chapters 10 of Géron, and builds on the [notebooks made available on _Github_](https://github.com/ageron/handson-ml2).\n\nNeed a reminder of last week's labs? Click [_here_](https://colab.research.google.com/github/tbeucler/2022_ML_Earth_Env_Sci/blob/main/Lab_Notebooks/Week_4_Dimensionality_Reduction_Clustering.ipynb) to go to notebook for week 4 of the course.\n\n## Notebook Setup\n\nFirst, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed (although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead), as well as Scikit-Learn ≥0.20 and TensorFlow ≥2.0.\n\n\n```python\n# Python ≥3.5 is required\nimport sys\nassert sys.version_info >= (3, 5)\n\n# Scikit-Learn ≥0.20 is required\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n\n# TensorFlow ≥2.0 is required\nimport tensorflow as tf\nassert tf.__version__ >= \"2.0\"\n\n# Common imports\nimport numpy as np\nimport os\n\n# to make this notebook's output stable across runs\nrnd_seed = 42\nrnd_gen = np.random.default_rng(rnd_seed)\n\n# To plot pretty figures\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"ann\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)\n\n# Initialize the run_index\nrun_index = None\n\n# Loading Tensorboard\n%load_ext tensorboard\n```\n\n## Data Setup\n\nToday, we'll once again be working on the MNIST handwritten digit database - we're becoming experts in typography! ✍ \n\nLet's begin by importing the dataset from the keras dataset library.\n\n### **Q1) Load the MNIST dataset from Keras. Divide it into a training, validation, and test dataset**\n\n*Hint 1: To access the Keras library, you can either reimport keras (e.g., `import tensorflow.keras as keras`), or you can access it from the instance of tensorflow we imported during setup (i.e., using `tf.keras`)*\n\n*Hint 2: [Here is the documentation](https://keras.io/api/datasets/mnist/) for the Keras implementation of the MNIST dataset*\n\n*Hint 3: If you use the `mnist.load_data()` method, what will be returned will be a set of tuples: (training_data, testing_data), where training_data and testing_data are tuples of inputs and labels (X, y)*\n\n*Hint 4: You can break down the training dataset from the `.load()` method into a training and validation dataset. Since the full training dataset includes 60 000 samples, try using 50 000 samples as training data and 10 000 samples as validation data.*\n\n\n```python\n# Load the keras dataset data\n( (X_train_full, y_train_full) , (X_testing, y_testing) ) = tf.keras.datasets.mnist.load_data()\n```\n\n Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n 11493376/11490434 [==============================] - 0s 0us/step\n 11501568/11490434 [==============================] - 0s 0us/step\n\n\n\n```python\n# Split the data\nfrom sklearn.model_selection import train_test_split\n\n(X_train,X_valid,y_train,y_valid) = train_test_split(X_train_full,y_train_full, test_size=10000, train_size=50000,random_state=42)\n```\n\nWhat does our data look like? Let's get an idea of the values and figure out what kind of preprocessing we should do before training our neural network.\n\n### **Q2) Print the shape of the training, validation, and test sets. Then, print the maximum and minimum input values.**\n\n\n*Hint 1: You loaded the data as numpy arrays. Thus, you can rely on the built-in methods for finding the shape and min/max values.*\n\n*Hint 2: Click for the documentation on [`ndarray.max()`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html), [`ndarray.min()`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html), and [`ndarray.shape`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html)*\n\n\n```python\n#Write your code here\nprint('Shape of training inputs:',X_train.shape)\nprint('Shape of training outputs:',y_train.shape)\nprint('Shape of testinf inputs:',X_testing.shape)\nprint('Shape of testing outputs:',y_testing.shape)\nprint('Shape of validation inputs:',X_valid.shape)\nprint('Shape of validation outputs:',y_valid.shape)\nprint('Min of X values from ',X_train_full.min(),' to ',X_train_full.max())\nprint('Min of y values from ',y_train_full.min(),' to ',y_train_full.max())\n```\n\n Shape of training inputs: (50000, 28, 28)\n Shape of training outputs: (50000,)\n Shape of testinf inputs: (10000, 28, 28)\n Shape of testing outputs: (10000,)\n Shape of validation inputs: (10000, 28, 28)\n Shape of validation outputs: (10000,)\n Min of X values from 0 to 255\n Min of y values from 0 to 9\n\n\nIf you used the same train/validation split as we did, you should have 50k samples in the training set, 10k in the validation set, and 10k in the test set. \n\nSince the data represents grayscale image values, data values should vary between 0 and 255; Normalize the data by dividing it by 255.\n### **Q3) Normalize the input data for the training, validation, and testing sets**\n\n*Hint 1: The datasets are stored as simple numpy arrays, so you can perform arithmetic operations on them!*\n\n\n```python\nX_train = X_train / 255\nX_testing = X_testing/255\nX_valid = X_valid/255\n```\n\nWe now have the normalized training, validation, and testing data that we'll use to train our neural network. Before moving on, it might be worth it to make a small visualiation of samples in our data to ensure that everything worked out correctly.\n\n### **Q4) Write a function that:
1) Takes in an input dataset and its labels, a number of rows, and a number of columns
2) Prints out a random n_rows by n_columns sample of images with their labels
**\n\n*Hint 1: You can use the `rnd_seed.integers()` generator to generate a set of integers between 0 and the number of samples, with a size of (rows,columns). [Here is some documentation that can help](https://numpy.org/doc/stable/reference/random/generator.html#simple-random-data). It's best practice to take in the random generator as an argument for your function.*\n\n*Hint 2: You can use matplotlib's `fig, axes = plt.subplots()` to make a grid of axes and call the `imshow()` method on each ax in order to plot the digit. It is recommended that you use the `cmap='binary'` argument in imshow to print the digits in black and white*. Click on the links for the documentation to [`plt.sublopts()`](https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.pyplot.subplots.html), [`plt.imshow()`](https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.pyplot.imshow.html), and [the colormaps (i.e., cmap values)](https://matplotlib.org/stable/gallery/color/colormap_reference.html) available in matplotlib.\n\n*Hint 3: You can iterate using numpy `ndenumerate()` method, which will return the n-dimensional index of the array and the element located there. This will be useful when iterating through the indices you generated and plotting the corresponding digit and label*\n\n*Hint 4: Feeling stuck? [Here is sample code for a way this function can be implemented.](https://unils-my.sharepoint.com/:t:/g/personal/tom_beucler_unil_ch/ERT6Sl_NHp5Nt2YjzkDPzLwB0RQ7_rVAl3RDx4BfHI047g?download=1)*\n\n\n```python\ndef sample_plotter(X, y, n_rows, n_columns, rnd_gen):\n assert type(X) == type(np.empty(0))\n indices = rnd_gen.integers(0,X.shape[0], size=(n_rows, n_columns))\n \n fig, axes = plt.subplots(n_rows, n_columns, figsize=(8,6))\n\n for idx, element in np.ndenumerate(indices):\n axes[idx].imshow(X[element], cmap='binary')\n axes[idx].axis('off')\n axes[idx].title.set_text(y[element])\n return\n```\n\nNow that our function is defined, let's go ahead and print out a 4 row by 8 column sample from each dataset.\n\n### **Q5) Grab a 4x8 sample of digits from each dataset and print out the image and labels**\n\n\n```python\n#Write your code here!\n\nsample_plotter(X_train,y_train,4,8,rnd_gen)\n```\n\nWe're now ready to start developing our neural network. The first thing that we want to do is figure out an appropriate learning rate for our model - after all, we want to choose one that converges to a solution *and* is the least computationally expensive possible.\n\nLet's start by setting up a keras *callback* [(click here for the documentation)](https://keras.io/api/callbacks/), a type of object that will allow us to change the learning rate after every iteration (i.e., after every batch of data). We will set up what is called an exponential learning rate (that is, the learning will increase by a factor of $k$ after each iteration). Expressed mathematically,\n\\begin{align}\n\\eta_{\\scriptsize{t}} = \\eta_{\\scriptsize{0}} \\, \\cdot \\, k^{\\scriptsize{t}}\n\\end{align}\nwhere $t$ is the current iteration. \n\nAs a reminder, an epoch is an iteration through the entire training dataset, while a batch is an iteration through a predefined subset of . It's important to make this distinction, as ML algorithms are often trained in batches when dealing with large datasets, and we *normally* do not want to change the learning rate in between batches during model training. However, we will do so during this evaluation phase in order to determine an adequate learning rate.\n\nWe will therefore set a callback that will do two things after the end of each batch:\n\n> 1) Keep a track of the losses
2) Adjust the learning rate by multiplying it by a predefined factor\n\n### **Q5) Set up an *Exponential_Learning_Rate* callback that, after each batch, logs the value of the loss function and learning rate, and then multiplies the learning rate by a factor of $k$** \n\n*Hint 1: Multiple backend options are available with Keras. We will be using tensorflow, but the code is thought to be written in such a way that a different backend **could** be used. `tf.keras.backend` has a `.backend()` method that allows you to check what backend is being used.*\n\n*Hint 2: You should extend the `tf.keras.callbacks.Callback` class. (Confused about extending classes? [Here is a question on stack overflow](https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python) that could provide some context) *\n\n*Hint 3: The ExponentialLearningRate callback we will implement will need to take in the $k$ factor durint its initialization ([here's a quick overview](https://stackoverflow.com/questions/625083/what-do-init-and-self-do-in-python) on the __init__ contructor method and **self** arguments in classes, with a focus on python.). You will also need to save an empty list as an attribute for both the losses and the learning rates*\n\n*Hint 4: Keras model optimizers have an attribute where the learning rate is stored: `model.optimizer.learning_rate`. In order to read the value, you will have to use the keras backend's `.get_value()` method with the model's learning rate as an argument*\n\n*Hint 5: the on_train_batch_end method pass the `logs` argument into the function. You can access the loss function by using `logs['loss']`*\n\n*Hint 6: In order to set the learning rate to a different value, you will have to depend on the keras backend's `.set_value()` method. This method takes in two arguments: the first is the value that will be set (e.g., the learning rate in the model's optimizer) and the value that it will be set to (e.g., the learning rate multiplied by the k factor).*\n\n*Hint 7: Unlike in other documentations we've seen, `backend.get_value()` and `backend.set_value()` don't yet have their own page. However, [here is the link](https://www.tensorflow.org/guide/keras/custom_callback#learning_rate_scheduling) to an example where both methods are used in a learning rate scheduler.*\n\n\n```python\n# We'll start by making it easier to access the keras backend. See hint #1 for\n# more details\nK = tf.keras.backend\n\n# Use the .backend() method to determine what backend we're running \nK.backend()\n```\n\n\n\n\n 'tensorflow'\n\n\n\n\n```python\n# Remember that you can access the keras.backend using K, which we defined in \n# the code cell above!\n\nclass ExponentialLearningRate(tf.keras.callbacks.Callback): #define the ExponentialLearningRate class\n # Start \n def __init__(self, factor):\n self.factor = factor # set the factor\n self.losses = [] # initialize the losses list\n self.Lrate = [] # initialize the learning rates list\n \n def on_batch_end(self, batch, logs):\n # Add the value of the learning rate to the list\n self.Lrate.append(K.get_value(self.model.optimizer.learning_rate))\n\n # Add the value of the loss\n self.losses.append(logs['loss'])\n\n # Set the value of the learning rate\n K.set_value(self.model.optimizer.learning_rate, self.model.optimizer.learning_rate * self.factor)\n```\n\nNow that we've defined out callback, we can go ahead and start thinking about our neural network. For consistency's sake, let's start by clearing the Keras backend and setting our random state.\n\n\n```python\n# Run this cell\nK.clear_session()\nnp.random.seed(rnd_seed)\ntf.random.set_seed(rnd_seed)\n```\n\nLet's make a simple neural network model using Keras. For this, we will rely on a [*Sequential model*](https://keras.io/guides/sequential_model/), since we will want all of the inputs of one layer to be fed into the next layer. We recommend using the architecture described in the diagram below, but feel free to define your own architecture!\n\n
\n\n### **Q6) Write a sequential Keras model that will predict the digit class.**\n\n\n\n*Hint 1: You can add the layers in the sequential model when initializing the model. It expects the layers in a list. Alternatively, you can add them one by one using the model's `.add()` method. [Check out the documentation here](https://keras.io/guides/sequential_model/#creating-a-sequential-model).*\n\n*Hint 2: The input images should be flattened before feeding them into any densely connected layers. [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Flatten) for the flatten layer.*\n\n*Hint 3: You want to use simple, densely connected layers for this exercise. [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense) for the dense layer.*\n\n*Hint 4: Using a dense layer with the number of units set to the number of classes (e.g., the number of different digits in the MNIST dataset: 10) using a softmax activation unit can be interpreted as a probability of the input belonging to a given class. [Here is the documentation](https://keras.io/api/layers/activations/#softmax-function) for the softmax activation function in Keras*\n\n\n```python\n# Create your model! Feel free to use our outline, or make your own from scratch\n\nmodel = tf.keras.models.Sequential([ # call the keras sequential model class\n tf.keras.layers.Flatten(), # 1st Layer\n tf.keras.layers.Dense(300, activation = 'relu'), # 2nd Layer\n tf.keras.layers.Dense(100, activation = 'relu'), # 3rd Layer\n tf.keras.layers.Dense(10, activation= 'softmax')]) # 4th Layer\n```\n\nNow that we have a model defined, we need to run its `.compile()' method, in which we will give the model the following hyper-parameters:\n> 1) Loss function will be set to sparse categorical cross entropy
2) The optimizer will be set to Stochastic Gradient Descent with a learning rate of 1e-3
3) The model metrics will include the accuracy score \n\n### **Q7) Compile the model with the given hyperparameters (i.e., loss function, optimizer, and metrics) and instantiate the callback we defined previously using a $k$ factor of 1.005 (i.e., a 0.5% increase in learning rate per batch)**\n\n\n\n*Hint 1: [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/metrics/sparse_categorical_crossentropy) for the sparse categorical cross entropy loss function in keras. You can simply reference the function using `loss='sparse_categorical_cross_entropy'` when compiling.*\n\n*Hint 2: [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD) for the Stochastic Gradient Descent optimizer in keras*\n\n*Hint 3: [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Accuracy) for the accuracy score implementation in keras. Like with the sparse_categorical_cross_entropy loss, you can reference the accuracy score in the metrics list, e.g. by setting `metrics=['accuracy']` when compiling.*\n\n\n\n```python\nmodel.compile(loss='sparse_categorical_crossentropy', # Set the loss function\n optimizer=tf.keras.optimizers.SGD(learning_rate=1e-3), # Set the optimizer and learning rate\n metrics=['accuracy']) # Set the metrics\n```\n\n\n```python\nexponential_lr_callback = ExponentialLearningRate(factor=1.005)\n```\n\nLet's go ahead and train the compiled model for a single epoch. \n\n\n### **Q8) Fit the model for a single epoch, using the exponential learning rate callback we defined in the previous code cell. Then, plot the Loss vs Learning rate.**\n\n*Hint 1: Just like in scikit-learn, the keras model includes a `.fit()` method to train the algorithm! [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit).*\n\n*Hint 2: After training, you can access the recorded losses and corresponding learning rates using the attributes we defined when we defined the class in Q5!*\n\n\n```python\nhistory = model.fit(X_train, # set the training inputs\n y_train, # set the training labels\n epochs=1, # set the number of epochs\n validation_data=(X_valid, y_valid), # set validation input/labels\n callbacks=[exponential_lr_callback]) # Set the callback\n```\n\n 1563/1563 [==============================] - 7s 4ms/step - loss: nan - accuracy: 0.6380 - val_loss: nan - val_accuracy: 0.0984\n\n\n\n```python\n# Plotting\nfig, ax = plt.subplots()\n\nax.plot(exponential_lr_callback.Lrate, # learning rates\n exponential_lr_callback.losses) # losses\n\n# Define a tuple with (min_learning_rate, max_learn_rate)\nx_limits = ( min(exponential_lr_callback.Lrate), 10 )\n\n# Set the xscale to logarithmic \nax.set_xscale('log')\n\n# Draw a horizontal line at the minimum loss value\nax.hlines(min(exponential_lr_callback.losses), #Find the minimum loss value to draw a horizontal line\n *x_limits, # the star unpacks x_limits to the expected num of args\n 'g') \n\n# Set the limits for drawing the curves\nax.set_xlim(x_limits)\nax.set_ylim(0, exponential_lr_callback.losses[0]) # use the initial loss as the top y boundary \n\n# Display gridlines to see better\nax.grid(which='both')\n\nax.set_xlabel(\"Learning rate\")\nax.set_ylabel(\"Loss\")\n```\n\nIf you used the architecture we defined above with the learning rate we defined above, you should produce a graph that looks like this:\n
\n\nIn this graph, you can see that the loss reaches a minimum at around 6e-1 and then begins to shoot up violently. Let's avoid that by using half that value (e.g., 3e-1). \n\nIf you have a different curve, try setting your learning rate to half of the learning rate with the minimum loss! 😃\n\n\nNow that we have an idea of what the learning rate should be, let's go ahead and start from scratch once more.\n\n\n```python\n# Run this cell - let's go back to a clean slate!\nK.clear_session()\nnp.random.seed(rnd_seed)\ntf.random.set_seed(rnd_seed)\n```\n\nWe also want to instantiate the model again - the weights in our current model are quite bad and if we use it as is it won't be able to learn since the weights are too far away from the solution. There are other ways to do this, but since our model is quite simple it's worth it to just redefine and recompile it.\n\n### **Q9) Redefine and re-compile the model with the learning rate you found in Q8.**\n\n\n```python\n# redefine the model\nmodel = tf.keras.models.Sequential([ # call the sequential model class\n tf.keras.layers.Flatten(), # flatten the data\n tf.keras.layers.Dense(300, activation = 'relu'), # densely connected ReLU layer, 300 units\n tf.keras.layers.Dense(100, activation = 'relu'), # densely connected ReLU layer, 100 units\n tf.keras.layers.Dense(10, activation = 'softmax')]) # densely connected Softmax layer, 10 units\n```\n\n\n```python\nmodel.compile(loss='sparse_categorical_crossentropy', # Set the loss function\n optimizer=tf.keras.optimizers.SGD(learning_rate=3e-1), # Set the optimizer and learning rate\n metrics=['accuracy']) # Set the metrics\n```\n\nWe're now going to set up a saving directory in case you want to try running the model with different learning rates or other hyper-parameters!\n\n\n```python\n#Change this number and rerun this cell whenever you want to change runs\nrun_index = 1 \n\nrun_logdir = os.path.join(os.curdir, \"my_mnist_logs\", \"run_{:03d}\".format(run_index))\n\nprint(run_logdir)\n```\n\n ./my_mnist_logs/run_001\n\n\nWe'll also set up some additional callbacks.\n> 1) An early stopping callback ([documentation here](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping)). This callback will stop the training if no improvement is found after a `patience` number of epochs.
2) A model checkpoint callback ([documentation here](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint)). This callback will ensure that only the best version of the model is kept (in case your model's performance reaches a maximum and then deteriorates after a certain number of epochs)
3) A tensorboard callback ([documentation here](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/TensorBoard)). This callback will enable using Tensorboard to visualize learning curves, metrics, etc. Handy 🙌!\n\n\n```python\nearly_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=20)\ncheckpoint_cb = tf.keras.callbacks.ModelCheckpoint(\"my_mnist_model.h5\", save_best_only=True)\ntensorboard_cb = tf.keras.callbacks.TensorBoard(run_logdir)\n```\n\nLet's go ahead and fit the model again!\n\n### **Q10) Fit the updated model for 100 epochs** \n\n\n```python\nhistory = model.fit(X_train, # inputs\n y_train, # labels\n epochs=100, #epochs\n validation_data=(X_valid, y_valid),\n callbacks=[checkpoint_cb, early_stopping_cb, tensorboard_cb])\n```\n\n Epoch 1/100\n 1563/1563 [==============================] - 6s 3ms/step - loss: 0.2415 - accuracy: 0.9513 - val_loss: 0.1419 - val_accuracy: 0.9578\n Epoch 2/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0872 - accuracy: 0.9719 - val_loss: 0.1025 - val_accuracy: 0.9711\n Epoch 3/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0625 - accuracy: 0.9799 - val_loss: 0.1586 - val_accuracy: 0.9527\n Epoch 4/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0452 - accuracy: 0.9854 - val_loss: 0.0963 - val_accuracy: 0.9722\n Epoch 5/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0365 - accuracy: 0.9880 - val_loss: 0.0913 - val_accuracy: 0.9770\n Epoch 6/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0261 - accuracy: 0.9916 - val_loss: 0.0913 - val_accuracy: 0.9793\n Epoch 7/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0209 - accuracy: 0.9929 - val_loss: 0.0980 - val_accuracy: 0.9789\n Epoch 8/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0194 - accuracy: 0.9940 - val_loss: 0.0929 - val_accuracy: 0.9795\n Epoch 9/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0126 - accuracy: 0.9960 - val_loss: 0.1096 - val_accuracy: 0.9783\n Epoch 10/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0157 - accuracy: 0.9944 - val_loss: 0.1120 - val_accuracy: 0.9772\n Epoch 11/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0172 - accuracy: 0.9943 - val_loss: 0.1989 - val_accuracy: 0.9528\n Epoch 12/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0136 - accuracy: 0.9955 - val_loss: 0.1749 - val_accuracy: 0.9655\n Epoch 13/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0126 - accuracy: 0.9964 - val_loss: 0.1339 - val_accuracy: 0.9757\n Epoch 14/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0111 - accuracy: 0.9967 - val_loss: 0.1036 - val_accuracy: 0.9801\n Epoch 15/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0080 - accuracy: 0.9973 - val_loss: 0.1105 - val_accuracy: 0.9806\n Epoch 16/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0045 - accuracy: 0.9985 - val_loss: 0.1032 - val_accuracy: 0.9823\n Epoch 17/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0043 - accuracy: 0.9989 - val_loss: 0.1141 - val_accuracy: 0.9819\n Epoch 18/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0039 - accuracy: 0.9988 - val_loss: 0.1135 - val_accuracy: 0.9803\n Epoch 19/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0055 - accuracy: 0.9983 - val_loss: 0.1536 - val_accuracy: 0.9745\n Epoch 20/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0154 - accuracy: 0.9955 - val_loss: 0.1281 - val_accuracy: 0.9798\n Epoch 21/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0073 - accuracy: 0.9977 - val_loss: 0.1290 - val_accuracy: 0.9796\n Epoch 22/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0083 - accuracy: 0.9975 - val_loss: 0.1104 - val_accuracy: 0.9823\n Epoch 23/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0071 - accuracy: 0.9978 - val_loss: 0.1405 - val_accuracy: 0.9781\n Epoch 24/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0066 - accuracy: 0.9981 - val_loss: 0.1156 - val_accuracy: 0.9829\n Epoch 25/100\n 1563/1563 [==============================] - 5s 3ms/step - loss: 0.0075 - accuracy: 0.9976 - val_loss: 0.1398 - val_accuracy: 0.9787\n\n\nFinally, we need to evaluate the performance of our model. Go ahead and try it out on the test set!\n\n### **Q11) Evaluate the model on the test set.**\n\n*Hint 1: Keras models include an `evaluate()` method that takes in the test set inputs/labels. [Here is the documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#evaluate).*\n\n\n```python\n# Rollback to best model, which was saved by the callback\nmodel = tf.keras.models.load_model(\"my_mnist_model.h5\") # rollback to best model\n\n# Evaluate the model\nmodel.evaluate(X_testing, y_testing)\n```\n\n 313/313 [==============================] - 1s 2ms/step - loss: 0.0862 - accuracy: 0.9768\n\n\n\n\n\n [0.08622584491968155, 0.9768000245094299]\n\n\n\nFinally, we can use tensorboard to check out our model's performance! Note that the tensorboard extension was loaded in the notebook setup cell.\n\n\n```python\n%tensorboard --logdir=./my_mnist_logs --port=6008\n```\n\n\n \n\n\nAn enthusiastic (albeit somewhat sick 😷) TA noted that during the development of the notebook the accuracy reached on the test dataset was 97.84%. Additionally, the tensorboard curves from the test run is given below:\n
\n", "meta": {"hexsha": "f18f37a432e11adfd3d5abd48acfdfa45273ece0", "size": 132203, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "S5_1_NNs_with_Keras_exercises_Vincenzo.ipynb", "max_stars_repo_name": "VGuzz/2022_ML_Earth_Env_Sci", "max_stars_repo_head_hexsha": "9d92976a269b45e4059307cd3f637c4f6653ca63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "S5_1_NNs_with_Keras_exercises_Vincenzo.ipynb", "max_issues_repo_name": "VGuzz/2022_ML_Earth_Env_Sci", "max_issues_repo_head_hexsha": "9d92976a269b45e4059307cd3f637c4f6653ca63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "S5_1_NNs_with_Keras_exercises_Vincenzo.ipynb", "max_forks_repo_name": "VGuzz/2022_ML_Earth_Env_Sci", "max_forks_repo_head_hexsha": "9d92976a269b45e4059307cd3f637c4f6653ca63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 118.2495527728, "max_line_length": 70093, "alphanum_fraction": 0.8167136903, "converted": true, "num_tokens": 7665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.1850156629693553}} {"text": "\n\n# メモ\n\nmatplotlib tutorials を利用した matplotlib の実験学習\n\nhttps://matplotlib.org/stable/tutorials/index.html\n\n \n\n\n# 日本語が使えるようにする\n\n\n```\n# 現在20210325 import japanize_matplotlib のために、下記が必要\n%%capture\n!pip install japanize_matplotlib\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport japanize_matplotlib\nplt.text(0.5, 0.5, 'matplotlibで\\n日本語が\\n使える!!!!'\n , fontsize=40\n , horizontalalignment='center'\n , verticalalignment='center')\nplt.show()\n```\n\n# 環境 スタイル\nmatplotlib.style.use で スタイルが選べる。\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.style.use('ggplot') # ここでスタイル名を指定する\ndata = np.random.randn(50)\nplt.plot(data) # x,y形式でなくてもplotできる\nplt.show()\n```\n\n\n```\n# print(plt.style.available) とすればstyleのリストが得られる\n```\n\n ['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']\n\n\n\n```\n# styleによってなにをしているかが違うので事前に使ったstyleの影響を受ける。使い物にならないのではないか\n# それぞれのstyleの内容を知りたい。まあいいか\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.style.use('dark_background')\nplt.style.use('fivethirtyeight')\nplt.figure(figsize=(4,4),facecolor='pink')\nplt.style.use('Solarize_Light2')\nplt.style.use('classic')\nplt.style.use('seaborn')\nplt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')\nplt.show()\n```\n\nplt.plot の中で 'r-o' とか指定できる。\n\nplt.rcParamsで細かく指定できる。\n\nrcParamsで指定したもののセットが style なのだろう。\n  \n  \nplt.figure(figsize=(4,4),facecolor='pink')\n\nとかで指定すると、rcParamsにかかわらず優先されるので、plt.plotを使う限りではrcParamsをあまり細かく学ぶ必要はないのかもしれない。 古い仕様なのかもしれない。\n  \n  \nsympyのplotを使う場合、rcParamsの環境だけを使うようなので、知っておく必要はある。\n\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\ndata = np.random.randn(50)\nplt.rcParams['lines.linewidth'] = 2\nplt.rcParams['lines.linestyle'] = '--'\nplt.plot(data)\nplt.show()\n# from sympy import *\n# x =symbols('x')\n# plot(x**2,(x,-0.5,0.5))\n```\n\nグラフの色は勝手に選ばれるのを変えるには axes.prop_cycle を変えるとあるが、次のプログラムはエラーになった。\n  \n  \n  \ncolorについて調べる\n\ncyclerについて調べる\n\n\n\n\n```\n# import matplotlib as mpl\n# mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']\n# plt.plot(data) # first color is red\n# plt.show()\n```\n\nグラフのスタイルを設定するのに `style.use`, `rcParams` 以外に `rc` でキーワード引数をつかってまとめて設定する方法がある。\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\ndata = np.random.randn(50)\n# plt.rcParams['lines.linewidth'] = 8\nplt.rc('lines', linewidth=4, linestyle='-.')\nplt.plot(data)\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\ndata = np.random.randn(50)\nplt.rcdefaults() # defaultはcolabのdefaultではない\nplt.rcParams['figure.figsize']=[4.2,2.8] # 反映する\n# plt.figure(figsize=(4,4),facecolor='pink') # 反映する。優先される\nplt.rcParams['figure.facecolor']='yellow' # 反映するが、弱い\nplt.rcParams['lines.color']='black' # 反映しない\n# plt.plot(data, 'k--') # 反映する\nplt.plot(data)\nplt.show()\n```\n\n\n```\n# rcParamsの内容を知る方法\nimport matplotlib.pyplot as plt\n# print(plt.rcParams) # lines.color:C0 , figure.figsize: [6.4, 4.8], C0 は cycler の 0番目の意味か?\n```\n\n`matplotlib.rcdefaults` Matplotlib のデフォルトに戻る。\n\ncolab のデフォルトはランタイムを中断すればわかる => 違いを比較してみよう。 => 違いはほとんどなかった\n  \n  \n\nrcParams の設定の validation については `matplotlib.rcsetup` にかかれているとか。 \n\n=> 例 >>> c = cycler(color=['red', 'green', 'blue']) とか。 わからない。\n\n  \n  \n\nmatplotlibの設定は `matplotlibrc` というファイルにあります、とか。\n\n\n\n```\nimport matplotlib.pyplot as plt\n# print(plt.rcParams)\n```\n\n# Usage Guide\n\n\nmatplotlibはfigureというエリアに設定されたaxという座標にデータを描画する。\n\naxを持ったfigureを作る最も簡単な方法は\n\nfig, ax = plt.subplots()\n\nである。\n\n\n\n```\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots() # 1つの座標axを持つfigureを作る\nax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # axにplotする\n```\n\nMATLABを含め他のグラフ作成ライブラリーは座標を明示的に作る必要がない。\n\nmatplotlibでも、axを作る手間を省いて、次のようにすると現在(current)の座標にグラフを書くことができる。\n\n\n```\nimport matplotlib.pyplot as plt\nplt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot.\n```\n\n\n```\nimport matplotlib\n# help(matplotlib.figure.Figure)\n# dir(matplotlib.figure.Figure)\ndir(matplotlib.axes.Axes)\n# help(matplotlib.axes.Axes)\n```\n\nplotで使うのは `numpy.array` なので、次のように変換する必要があるかもしれない。\n\npandas.Dataframe の場合: \n\n a = pandas.DataFrame(np.random.rand(4, 5), columns = list('abcde')) \n a_asarray = a.values \n\nnumpy.matrix の場合: \n\n b = np.matrix([[1, 2], [3, 4]]) \n b_asarray = np.asarray(b) \n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 2, 100) # 0,2の間を100に刻む\nfig, ax = plt.subplots() # figure と ax を作る\nax.plot(x, x, label='linear') # プロットする\nax.plot(x, x**2, label='quadratic') # y=x^2のグラフ\nax.plot(x, x**3, label='cubic') # y=x^3のグラフ\nax.set_xlabel('x label') # x軸のラベル\nax.set_ylabel('y label') # y軸のラベル\nax.set_title(\"Simple Plot\") # グラフにタイトルをつける\nax.legend() # レジェンドを加える\n```\n\nor (pyplot-style)\n\n\n\n\n```\n# fgとaxを作らない場合の例\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 2, 100)\nplt.plot(x, x, label='linear') # 明示されていない座標にプロットする\nplt.plot(x, x**2, label='quadratic') \nplt.plot(x, x**3, label='cubic')\nplt.xlabel('x label')\nplt.ylabel('y label')\nplt.title(\"Simple Plot\")\nplt.legend()\nplt.show()\n```\n\nfig,axを作ってオブジェクトに関数を使っていくいわゆるOO型のプログラミングのメリットは、違うデータセットで同じグラフを繰り返し書く際に現れる。\n\nそのような場合の関数の書き方の例を次に示す。\n\n\n\n```\ndef my_plotter(ax, data1, data2, param_dict):\n \"\"\"\n A helper function to make a graph\n\n Parameters\n ----------\n ax : Axes\n The axes to draw to\n\n data1 : array\n The x data\n\n data2 : array\n The y data\n\n param_dict : dict\n Dictionary of kwargs to pass to ax.plot\n\n Returns\n -------\n out : list\n list of artists added\n \"\"\"\n out = ax.plot(data1, data2, **param_dict)\n return out\n```\n\nこの関数は次のように使う\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\ndata1, data2, data3, data4 = np.random.randn(4, 100)\nfig, ax = plt.subplots(1, 1)\nmy_plotter(ax, data1, data2, {'marker': 'x'})\n```\n\n違うデータで同じ関数を使って2枚のグラフを描くことができる。\n\n\n\n```\nfig, (ax1, ax2) = plt.subplots(1, 2)\nmy_plotter(ax1, data1, data2, {'marker': 'x'})\nmy_plotter(ax2, data3, data4, {'marker': 'o'})\n```\n\nメモ randomについて\n\ntable | 意味\n--- | ---\nrand() | 0.0以上、1.0未満の乱数を1個生成 \nrand(3) | 0.0以上、1.0未満の乱数を3個生成 \nrand(2,3) | 0.0以上、1.0未満の乱数で 2x3 の行列を生成 \n(b-a) * np.random.rand() + a |([a, b): a以上、b未満)の乱数 \nrandn() | 標準正規分布 (平均0, 標準偏差1) \nrandn(10) | 標準正規分布を10個生成 \nrandn(10,10) | 標準正規分布による 10x10 の行列 \nnormal(50,10) | 平均50、標準偏差10の正規分布 \nbinomial(n=100, p=0.5) | 二項分布 \npoisson(lam=10) | λ=10 のポアソン分布 \nbeta(a=3, b=5) | a=3, b=5 のベータ分布 \nrandint(100) | 0〜99 の整数を1個生成 \nrandint(30,70) | 30〜69 の整数を1個生成 \nrandint(0,100,20) | 0〜99 の整数を20個生成 \nrandint(0,100,(5,5)) | 0〜99 の整数で5x5の行列を生成 \nrandom_integers(100) | 1〜100 の整数を1個生成 \nrandom_integers(30,70) | 30〜70 の整数を1個生成 \nrandom.choice(city) | 1個をランダム抽出 \nrandom.choice(city,10) | 10個をランダム抽出(重 \nrandom.choice(city,5,replace=False) | 5個をランダム抽出(重複なし) \nrandom.choice(city, p=weight) | 指定した確率で1個を抽出 \nseed(100) | 数値はなんでもいい \nnumpy.random.random_sample((2,3)) | 0.0以上、1.0未満の乱数で 2x3 の行列を生成\n | np.random.random、np.random.ranf、\n | np.random.sampleはぜんぶ同じ \nnumpy.random.gamma(5,1,10) | 形状母数shape, 尺度母数scale, size \nnumpy.random.chisquare() | カイ二乗分布 自由度df, size \n\n# バックエンド backend\n\n\nバックエンドとはなにか。 \n\nグラフを出力する時、colab (jupyter) のように inline でプロットする場合だけでなく、さまざまな状況で matplotlib は使われる。 そのような様々な出力に対応する部分をバックエンドと呼ぶ。 \n\n例えば、次のようなユースケースがある。 \n- Pythonシェルからインタラクティブにmatplotlibを使用し、コマンドを入力するとプロットウィンドウがポップアップする \n- wxpythonやpygtkなどのグラフィカルユーザーインターフェイスに埋め込んで、アプリケーションを構築する\n- バッチスクリプトで数値シミュレーションからポストスクリプト画像を生成する\n- Webアプリケーションサーバーを実行してグラフを動的に提供する\n\nバックエンドには2つのタイプがある。 \n1. pygtk、wxpython、tkinter、qt4、macosx で使用するためのユーザーインターフェイスバックエンド。ユーザーインターフェイスバックエンドはインタラクティブバックエンド、対話型バックエンドとも呼ばれる\n2. PNG、SVG、PDF、PS などの画像ファイルを作成するためのハードコピーバックエンド。非対話型バックエンドとも呼ばれる\n\nバックエンドの設定は3通りの方法がある。\n1. `matplotlibrc` ファイルで パラメーター `backend` で指定する\n2. 環境変数 envvar:`MPLBACKEND` を使う\n3. 関数 `matplotlib.use` を使う\n\n\n# pyplot\n\npyplot は matplotlib で画像を描くための関数の集合である。\n\n画像を描く座標のことを ax, axes というが、ここでいう ax, axes は厳密な数学用語ではなく、matplotlib.pyplot の用語と思ってもらいたい。 pyplot が作用するのはこの ax, axes に対してである。 \n\n\n\n```\nimport matplotlib.pyplot as plt\nplt.plot([1, 2, 3, 4])\nplt.ylabel('some numbers')\nplt.show()\n```\n\n上のグラフでなぜ x軸が 0-3 で、y軸が 1-4 なのか。\n\nなにも指定しないで 1つのリストを plot に与えると、pyplot はそれを y の値とみなして、対応する x を自動生成する。 自動生成される x のリストが 0 ベースなので、この場合 [0,1,2,3] になる。\n\n\nplot に 2 つのリストを与えると次のようになる。\n\n\n\n```\nimport matplotlib.pyplot as plt\nplt.plot([1, 2, 3, 4], [1, 4, 9, 16])\n```\n\npyplot.plt はリストだけではなく、numpy.array を処理する。 list は numpy array に変換されて処理されている。\n\n次の例では plot におけるさまざまなフォーマットを示す。\n\n\n```\nimport numpy as np\n\n# evenly sampled time at 200ms intervals\nt = np.arange(0., 5., 0.2)\n\n# red dashes, blue squares and green triangles\nplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')\nplt.show()\n```\n\nnumpy.recarray と pandas.DataFrame については文字列で変数にアクセスすることができる。\n\nそのようなオブジェクトは `data`キーワードを用いると、変数に対応するグラフを描くことができる。\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = {'a': np.arange(50),\n 'c': np.random.randint(0, 50, 50),\n 'd': np.random.randn(50)}\ndata['b'] = data['a'] + 10 * np.random.randn(50)\ndata['d'] = np.abs(data['d']) * 100\n\nplt.scatter('a', 'b', c='c', s='d', data=data)\nplt.xlabel('entry a')\nplt.ylabel('entry b')\nplt.show()\n```\n\nカテゴリー変数 categorical variables\n\nカテゴリー変数で直接プロットすることができる。\n\n\n\n```\nnames = ['group_a', 'group_b', 'group_c']\nvalues = [1, 10, 100]\n\nplt.figure(figsize=(9, 3))\n\nplt.subplot(131)\nplt.bar(names, values)\nplt.subplot(132)\nplt.scatter(names, values)\nplt.subplot(133)\nplt.plot(names, values)\nplt.suptitle('Categorical Plotting')\nplt.show()\n```\n\n\n```\nラインプロパティの制御\n\nキーワードargsを使用する\n\n```\n\n\n```\nx = np.arange(10) # [0,1,2,3,4,5,6,7,8,9] <= 10個\ny = np.random.rand(10)*10 # [0..10) のランダムな実数\nplt.plot(x, y, linewidth=10.0)\n```\n\n\n```\nline, = plt.plot(x, y, '-')\nline.set_antialiased(False) # turn off antialiasing\n```\n\n\n```\nx1 = np.random.rand(10)\nx2 = np.random.rand(10)\ny1 = np.random.rand(10)\ny2 = np.random.rand(10)\n# lines = plt.plot(x1, y1, x2, y2)\nline1 = plt.plot(x1, y1)\nline2 = plt.plot(x2, y2)\n# use keyword args\nplt.setp(line1, color='k', linewidth=10.0)\n# or MATLAB style string value pairs\nplt.setp(line2, 'color', 'g', 'linewidth', 10.0)\nplt.show()\n```\n\n\n```\n# line2D のプロパティのリストは line を引数に plt.setp でも得られる\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nline = plt.plot(np.random.rand(7),np.random.rand(7))\nplt.setp(line, linewidth=15, color='red')\n# plt.setp(line)\n```\n\n\n```\n複数のグラフを扱う方法\n```\n\n\n```\nplt.gca は current axes (a matplotlib.axes.Axes instance) を返す\n\nplt.gcf は current figure (a matplotlib.figure.Figure instance) を返す\n```\n\n\n```\ndef f(t):\n return np.exp(-t) * np.cos(2*np.pi*t)\n\nt1 = np.arange(0.0, 5.0, 0.1)\nt2 = np.arange(0.0, 5.0, 0.02)\n\nplt.figure()\nplt.subplot(211)\nplt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')\n\nplt.subplot(212)\nplt.plot(t2, np.cos(2*np.pi*t2), 'r--')\nplt.show()\n```\n\nplt.figure は省略可能。\n\n座標軸が1つだけのときは subplot(111)も省略可能。\n\nplt.subplot の引数は 3桁の数字で 行数、列数、プロット番号の順。 \n\nsubplot(211)はsubplot(2、1、1)と同じ。\n  \n  \n\n格子状でなく自由な位置に座標を作成するには plt.axes([left, bottom, width, height]) を使う。 数字は 0から1の有理数 fractional である。\n\nhttps://matplotlib.org/3.3.3/gallery/subplots_axes_and_figures/axes_demo.html\n\nhttps://matplotlib.org/3.3.3/gallery/subplots_axes_and_figures/subplot_demo \n\nを参照。\n\n\n\n```\n# 上記のサイトの例\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Data for plotting\nx1 = np.linspace(0.0, 5.0)\nx2 = np.linspace(0.0, 2.0)\ny1 = np.cos(2 * np.pi * x1) * np.exp(-x1)\ny2 = np.cos(2 * np.pi * x2)\n\n# Create two subplots sharing y axis\nfig, (ax1, ax2) = plt.subplots(2, sharey=True)\n\nax1.plot(x1, y1, 'ko-')\nax1.set(title='A tale of 2 subplots', ylabel='Damped oscillation')\n\nax2.plot(x2, y2, 'r.-')\nax2.set(xlabel='time (s)', ylabel='Undamped')\n\nplt.show()\n```\n\n\n```\n# 上記のサイトの例\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(19680801) # Fixing random state for reproducibility.\n\n# create some data to use for the plot\ndt = 0.001\nt = np.arange(0.0, 10.0, dt)\nr = np.exp(-t[:1000] / 0.05) # impulse response\nx = np.random.randn(len(t))\ns = np.convolve(x, r)[:len(x)] * dt # colored noise\n\nfig, main_ax = plt.subplots()\nmain_ax.plot(t, s)\nmain_ax.set_xlim(0, 1)\nmain_ax.set_ylim(1.1 * np.min(s), 2 * np.max(s))\nmain_ax.set_xlabel('time (s)')\nmain_ax.set_ylabel('current (nA)')\nmain_ax.set_title('Gaussian colored noise')\n\n# this is an inset axes over the main axes\nright_inset_ax = fig.add_axes([.65, .6, .2, .2], facecolor='k')\nright_inset_ax.hist(s, 400, density=True)\nright_inset_ax.set(title='Probability', xticks=[], yticks=[])\n\n# this is another inset axes over the main axes\nleft_inset_ax = fig.add_axes([.2, .6, .2, .2], facecolor='k')\nleft_inset_ax.plot(t[:len(r)], r)\nleft_inset_ax.set(title='Impulse response', xlim=(0, .2), xticks=[], yticks=[])\n\nplt.show()\n```\n\nフィギュア番号を増やしながら複数の\nplt.figure を使うことにより\n複数のフィギュアを作成できる。\n\n\n\n```\n# 下の例は現在 20210329 警告 warning が出る。 将来は OO-style で書く方法のみになる\nimport matplotlib.pyplot as plt\nplt.figure(1) # the first figure\nplt.subplot(211) # the first subplot in the first figure\nplt.plot([1, 2, 3])\nplt.subplot(212) # the second subplot in the first figure\nplt.plot([4, 5, 6])\n\nplt.figure(2) # a second figure\nplt.plot([4, 5, 6]) # creates a subplot(111) by default\n\nplt.figure(1) # figure 1 current; subplot(212) still current\nplt.subplot(211) # make subplot(211) in figure1 current\nplt.title('Easy as 1, 2, 3') # subplot 211 title\n\nplt.show()\n```\n\nplt.clf, plt.cla, plt.close について\n\nfigure や axes を plt.clf, plt.cla でクリアできる。\n\nplt.close でメモリーを解放する。\n\nとのこと。\n\n\nテキスト処理\n\nplt.textを使用して任意の場所にテキストを追加できる。\n\nplt.xlabel、plt.ylabel、plt.titleを使用して、指定された場所にテキストを追加できる。\n\nより詳細な例は\n\nhttps://matplotlib.org/stable/tutorials/text/text_intro.html\n\n\n```\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.add_subplot()\nfig.subplots_adjust(top=0.85)\n\n# Set titles for the figure and the subplot respectively\nfig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')\nax.set_title('axes title')\n\nax.set_xlabel('xlabel')\nax.set_ylabel('ylabel')\n\n# Set both x- and y-axis limits to [0, 10] instead of default [0, 1]\nax.axis([0, 10, 0, 10])\n\nax.text(3, 8, 'boxed italics text in data coords', style='italic',\n bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})\n\nax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)\n\nax.text(3, 2, 'unicode: Institut für Festkörperphysik')\n\nax.text(0.95, 0.01, 'colored text in axes coords',\n verticalalignment='bottom', horizontalalignment='right',\n transform=ax.transAxes,\n color='green', fontsize=15)\n\nax.plot([2], [1], 'o')\nax.annotate('annotate', xy=(2, 1), xytext=(3, 4),\n arrowprops=dict(facecolor='black', shrink=0.05))\n\nplt.show()\n```\n\n\n```\nmu, sigma = 100, 15\nx = mu + sigma * np.random.randn(10000)\n\n# the histogram of the data\nn, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)\n\n\nplt.xlabel('Smarts')\nplt.ylabel('Probability')\nplt.title('Histogram of IQ')\nplt.text(60, .025, r'$\\mu=100,\\ \\sigma=15$')\nplt.axis([40, 160, 0, 0.03])\nplt.grid(True)\nplt.show()\n```\n\nすべてのplt.text関数は、matplotlib.text.Textインスタンスを返します。 キーワード引数をテキスト関数に渡すか、plt.setp を使用して、プロパティをカスタマイズできる。\n\n\n```\nimport matplotlib.pyplot as plt\nfig,ax=plt.subplots(figsize=(6,3))\nt = plt.xlabel('my data', fontsize=14, color='red')\nplt.setp(t, color='blue')\nplt.show()\n```\n\n# テキストで数式を使用する\n\n次の例でテキストの前の `r` は `raw` の意味で省略してはいけない。 なぜなら `r` のついたテキストの中では python のテキストのエスケープを扱わないことになっているから。\n\n\n```\nimport matplotlib.pyplot as plt\nfig,ax=plt.subplots(figsize=(6,3))\nax.set_title(r'$\\sigma_i=15$', color='red')\nplt.text(0.5, 0.5, 'No Japanese\\nIn Matplotlib!'\n , fontsize=40\n , horizontalalignment='center'\n , verticalalignment='center')\nplt.show()\n```\n\n\n```\nplt.text?\n```\n\n# 注釈 Annotating text\n\n上記の plt.text 関数で好きな位置に、テキストを配置できる。 \n\nplt.annotateメソッドは、注釈を簡単にするためのヘルパー機能を提供する。 \n\n引数 xyで表される注釈を付ける場所と、xytext で表されるテキストの場所を\n両方とも(xy)タプルで指定する。\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\nax = plt.subplot(111)\n\nt = np.arange(0.0, 5.0, 0.01)\ns = np.cos(2*np.pi*t)\nline, = plt.plot(t, s, lw=2)\n\nplt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),\n arrowprops=dict(facecolor='black', shrink=0.05),\n )\n\nplt.ylim(-2, 2)\nplt.show()\n```\n\n上の例では xy が矢印の先端の座標で、xytext がテキストの場所の座標である。\n\nその他の例は\n\nhttps://matplotlib.org/stable/gallery/text_labels_and_annotations/annotation_demo.html\n\nを参照する。\n\n# 対数グラフ Logarithmic and other nonlinear axes\n\n対数スケールのグラフにするのは簡単で\n\nplt.xscale('log')\n\nとするだけ。\n\n以下に例を示す。\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n# make up some data in the open interval (0, 1)\ny = np.random.normal(loc=0.5, scale=0.4, size=1000)\ny = y[(y > 0) & (y < 1)]\ny.sort()\nx = np.arange(len(y))\n\n# plot with various axes scales\nplt.figure()\n\n# linear\nplt.subplot(221)\nplt.plot(x, y)\nplt.yscale('linear')\nplt.title('linear')\nplt.grid(True)\n\n# log\nplt.subplot(222)\nplt.plot(x, y)\nplt.yscale('log')\nplt.title('log')\nplt.grid(True)\n\n# symmetric log\nplt.subplot(223)\nplt.plot(x, y - y.mean())\nplt.yscale('symlog', linthresh=0.01) # linthresh は deprecated という warning が出る\nplt.title('symlog')\nplt.grid(True)\n\n# logit\nplt.subplot(224)\nplt.plot(x, y)\nplt.yscale('logit')\nplt.title('logit')\nplt.grid(True)\n# Adjust the subplot layout, because the logit one may take more space\n# than usual, due to y-tick labels like \"1 - 10^{-3}\"\nplt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,\n wspace=0.35)\n\nplt.show()\n```\n\n自分で作ったスケールを加えることもできる。 詳細は adding-new-scales を参照。\n\n# サンプルグラフについて\n\n折れ線グラフ\n\n複数のグラフを一度に扱う\n\n画像\n\n2次元グラフのカラー処理\n\nヒストグラム\n\n自由曲線 path patch\n\n3次元グラフ\n\n流線グラフ、流線描画 streamplot\n\n楕円 ellipse\n\n棒グラフ bar chart\n\n円グラフ pie chart\n\n表 table\n\n散布図 scatter plot\n\nGUI部品 スライダー、ラジオボタンなど\n\n塗りつぶされた曲線、ポリゴン\n\n日付処理\n\n対数グラフ\n\n極座標\n\n凡例 legend\n\n数式処理 (内部プログラム、外部プログラム)\n\n外部ツールキットへの出力 Qt, GTK, Tk, or wxWidgets, EEG viewer pbrain\n\nスケッチ風グラフ XKCD-style sketch plot\n\n複数の処理の組み合わせ subplot example\n\n\n\n\n\n\n\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(19680801)\ndata = np.random.randn(2, 100)\n\nfig, axs = plt.subplots(2, 2, figsize=(5, 5))\naxs[0, 0].hist(data[0])\naxs[1, 0].scatter(data[0], data[1])\naxs[0, 1].plot(data[0], data[1])\naxs[1, 1].hist2d(data[0], data[1])\n\nplt.show()\n```\n\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.random.randn(2, 3)\nprint(type(data))\nprint(data)\n```\n\n \n [[-1.60179006 0.432704 -0.16409604]\n [ 0.81880165 0.95616235 -0.10459382]]\n\n\n# 画像処理 \n\nColab の環境ではチュートリアルの例が使えないので、この章は飛ばす。\n\n表題のみ。\n\n\n画像処理モジュールの import\n```\nimport matplotlib.image as mpimg\n```\n\n画像データを numpy array に import する \nmatplotlib は画像データをロードするために pillow ライブラリーを使っている。\n```\nimg = mpimg.imread('../../doc/_static/stinkbug.png')\nprint(img)\n```\n\nnumpy array を画像グラフとして plot する\n```\nimgplot = plt.imshow(img)\n```\n\n画像グラフにカラースキーム pseudocolor schemes を適用する\n\n\n\n\n\n```\n# lum_img = img[:, :, 0]\n\n# This is array slicing. You can read more in the `Numpy tutorial\n# `_.\n\n# plt.imshow(lum_img)\n```\n\n\n```\n# plt.imshow(lum_img, cmap=\"hot\")\n```\n\n\n```\n# imgplot = plt.imshow(lum_img)\n# imgplot.set_cmap('nipy_spectral')\n```\n\n\n```\n# カラーバーを表示する\n# imgplot = plt.imshow(lum_img)\n# plt.colorbar()\n```\n\n\n```\n# 色データの範囲をヒストグラムにする\n# plt.hist(lum_img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')\n```\n\n\n```\n# ピーク周辺にズームインする\n# imgplot = plt.imshow(lum_img, clim=(0.0, 0.7))\n```\n\n\n```\n# 返り値をつかって clim を指定する方法\n\n# fig = plt.figure()\n# ax = fig.add_subplot(1, 2, 1)\n# imgplot = plt.imshow(lum_img)\n# ax.set_title('Before')\n# plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')\n# ax = fig.add_subplot(1, 2, 2)\n# imgplot = plt.imshow(lum_img)\n# imgplot.set_clim(0.0, 0.7)\n# ax.set_title('After')\n# plt.colorbar(ticks=[0.1, 0.3, 0.5, 0.7], orientation='horizontal')\n```\n\n\n```\n# 色補完スキーム Array Interpolation scheme\n# 画像を縮小すると失われる情報がある。 拡大する際には補間する必要がある。\n# 画像をロードしりサイズするのに Pillow ライブラリーを使う\n# from PIL import Image\n\n# img = Image.open('../../doc/_static/stinkbug.png')\n# img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place\n# imgplot = plt.imshow(img)\n```\n\n上のコードではデフォルトの補間スキーム bilinear が使われている。\n\n次のコードでは \"nearest\" を指定しているが、これは補間を行わない。\n\n\n\n\n```\n# imgplot = plt.imshow(img, interpolation=\"nearest\")\n```\n\n次のコードでは \"bicubic\" を使っている。\n\n\"bicubic\" は写真の拡大にしばしば使われる。 ピクセルが見えるよりもボケて見える方が好まれるからである。\n\n\n\n\n```\n# imgplot = plt.imshow(img, interpolation=\"bicubic\")\n```\n\n# グラフ描画のライフサイクル\n\n次にグラフを描いて、加工して、保存する手順の中で、参考になるベストプラスティスを示したい。\n\nこの章は \n `_\n by Chris Moffitt \nをベースに作成した。\n\n\n\n## Our data\n\nWe'll use the data from the post from which this tutorial was derived.\nIt contains sales information for a number of companies.\n\n\n\n```\n# 以下のサンプルで使われるデータは元のサイトで使われていたもの\n# 会社名をキーにした売上金額の辞書の形式になっている\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = {'Barton LLC': 109438.50,\n 'Frami, Hills and Schmidt': 103569.59,\n 'Fritsch, Russel and Anderson': 112214.71,\n 'Jerde-Hilpert': 112591.43,\n 'Keeling LLC': 100934.30,\n 'Koepp Ltd': 103660.54,\n 'Kulas Inc': 137351.96,\n 'Trantow-Barrows': 123381.38,\n 'White-Trantow': 135841.99,\n 'Will LLC': 104437.60}\ngroup_data = list(data.values())\ngroup_names = list(data.keys())\ngroup_mean = np.mean(group_data)\n```\n\n\n```\nprint(type(data))\n```\n\n \n\n\n# いまここ\n\n## Getting started\n\nThis data is naturally visualized as a barplot, with one bar per\ngroup. To do this with the object-oriented approach, we first generate\nan instance of :class:`figure.Figure` and\n:class:`axes.Axes`. The Figure is like a canvas, and the Axes\nis a part of that canvas on which we will make a particular visualization.\n\n

Note

Figures can have multiple axes on them. For information on how to do this,\n see the :doc:`Tight Layout tutorial\n `.

\n\n\n\n\n```\nfig, ax = plt.subplots()\n```\n\nNow that we have an Axes instance, we can plot on top of it.\n\n\n\n\n```\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\n```\n\n## Controlling the style\n\nThere are many styles available in Matplotlib in order to let you tailor\nyour visualization to your needs. To see a list of styles, we can use\n:mod:`.style`.\n\n\n\n\n```\nprint(plt.style.available)\n```\n\nYou can activate a style with the following:\n\n\n\n\n```\nplt.style.use('fivethirtyeight')\n```\n\nNow let's remake the above plot to see how it looks:\n\n\n\n\n```\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\n```\n\nThe style controls many things, such as color, linewidths, backgrounds,\netc.\n\n## Customizing the plot\n\nNow we've got a plot with the general look that we want, so let's fine-tune\nit so that it's ready for print. First let's rotate the labels on the x-axis\nso that they show up more clearly. We can gain access to these labels\nwith the :meth:`axes.Axes.get_xticklabels` method:\n\n\n\n\n```\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\n```\n\nIf we'd like to set the property of many items at once, it's useful to use\nthe :func:`pyplot.setp` function. This will take a list (or many lists) of\nMatplotlib objects, and attempt to set some style element of each one.\n\n\n\n\n```\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\n```\n\nIt looks like this cut off some of the labels on the bottom. We can\ntell Matplotlib to automatically make room for elements in the figures\nthat we create. To do this we set the ``autolayout`` value of our\nrcParams. For more information on controlling the style, layout, and\nother features of plots with rcParams, see\n:doc:`/tutorials/introductory/customizing`.\n\n\n\n\n```\nplt.rcParams.update({'figure.autolayout': True})\n\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\n```\n\nNext, we add labels to the plot. To do this with the OO interface,\nwe can use the :meth:`.Artist.set` method to set properties of this\nAxes object.\n\n\n\n\n```\nfig, ax = plt.subplots()\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\nax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',\n title='Company Revenue')\n```\n\nWe can also adjust the size of this plot using the :func:`pyplot.subplots`\nfunction. We can do this with the ``figsize`` kwarg.\n\n

Note

While indexing in NumPy follows the form (row, column), the figsize\n kwarg follows the form (width, height). This follows conventions in\n visualization, which unfortunately are different from those of linear\n algebra.

\n\n\n\n\n```\nfig, ax = plt.subplots(figsize=(8, 4))\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\nax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',\n title='Company Revenue')\n```\n\nFor labels, we can specify custom formatting guidelines in the form of\nfunctions. Below we define a function that takes an integer as input, and\nreturns a string as an output. When used with `.Axis.set_major_formatter` or\n`.Axis.set_minor_formatter`, they will automatically create and use a\n:class:`ticker.FuncFormatter` class.\n\nFor this function, the ``x`` argument is the original tick label and ``pos``\nis the tick position. We will only use ``x`` here but both arguments are\nneeded.\n\n\n\n\n```\ndef currency(x, pos):\n \"\"\"The two args are the value and tick position\"\"\"\n if x >= 1e6:\n s = '${:1.1f}M'.format(x*1e-6)\n else:\n s = '${:1.0f}K'.format(x*1e-3)\n return s\n```\n\nWe can then apply this function to the labels on our plot. To do this,\nwe use the ``xaxis`` attribute of our axes. This lets you perform\nactions on a specific axis on our plot.\n\n\n\n\n```\nfig, ax = plt.subplots(figsize=(6, 8))\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\n\nax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',\n title='Company Revenue')\nax.xaxis.set_major_formatter(currency)\n```\n\n## Combining multiple visualizations\n\nIt is possible to draw multiple plot elements on the same instance of\n:class:`axes.Axes`. To do this we simply need to call another one of\nthe plot methods on that axes object.\n\n\n\n\n```\nfig, ax = plt.subplots(figsize=(8, 8))\nax.barh(group_names, group_data)\nlabels = ax.get_xticklabels()\nplt.setp(labels, rotation=45, horizontalalignment='right')\n\n# Add a vertical line, here we set the style in the function call\nax.axvline(group_mean, ls='--', color='r')\n\n# Annotate new companies\nfor group in [3, 5, 8]:\n ax.text(145000, group, \"New Company\", fontsize=10,\n verticalalignment=\"center\")\n\n# Now we move our title up since it's getting a little cramped\nax.title.set(y=1.05)\n\nax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',\n title='Company Revenue')\nax.xaxis.set_major_formatter(currency)\nax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])\nfig.subplots_adjust(right=.1)\n\nplt.show()\n```\n\n## Saving our plot\n\nNow that we're happy with the outcome of our plot, we want to save it to\ndisk. There are many file formats we can save to in Matplotlib. To see\na list of available options, use:\n\n\n\n\n```\nprint(fig.canvas.get_supported_filetypes())\n```\n\nWe can then use the :meth:`figure.Figure.savefig` in order to save the figure\nto disk. Note that there are several useful flags we show below:\n\n* ``transparent=True`` makes the background of the saved figure transparent\n if the format supports it.\n* ``dpi=80`` controls the resolution (dots per square inch) of the output.\n* ``bbox_inches=\"tight\"`` fits the bounds of the figure to our plot.\n\n\n\n\n```\n# Uncomment this line to save the figure.\n# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches=\"tight\")\n```\n\n# いまここ\n", "meta": {"hexsha": "0bca7900f5a23627c592942fa798ff6898e370e0", "size": 790126, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "matplotlibtutorials.ipynb", "max_stars_repo_name": "kalz2q/-yjupyternotebooks", "max_stars_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-16T03:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T03:45:19.000Z", "max_issues_repo_path": "matplotlibtutorials.ipynb", "max_issues_repo_name": "kalz2q/-yjupyternotebooks", "max_issues_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matplotlibtutorials.ipynb", "max_forks_repo_name": "kalz2q/-yjupyternotebooks", "max_forks_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 266.5742240216, "max_line_length": 71050, "alphanum_fraction": 0.9142706353, "converted": true, "num_tokens": 11234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18366653278011918}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n%matplotlib inline\n```\n\n\n```python\nmatplotlib.rcParams['figure.figsize'] = (10.0, 8.0)\n```\n\n# Calculus Review: Introduction\n\n\n[Integrals](http://en.wikipedia.org/wiki/Integral) and [derivatives](http://en.wikipedia.org/wiki/Derivative) are widely used in \nscientific modeling and simulations. Integration, along with its inverse operation\ndifferentiation, are the two main operations of calculus. \n\nIn this lecture notebook we will review some of the basic concepts from Calculus, including going all the way back\nto discussing functions and their graphs, and the concept of the slope of a line; looking at limits and\nderivatives, and how the slop of a function relates to the derivative; and then at the concept of integration\nand integrals, and specifying and solving differential equations.\n\nThis notebook is only meant to be a quick review. It is hoped and expected that at some point you have studied at least\nthe basics of these topics in secondary education and during your undergraduate degree. Most students should be\nable to follow these materials and understand the important concepts who have at least a good understanding of\nalgebra and geometry, especially equations of lines and functions, as a starting point to understanding\nthe calculus mathematics.\n\nThe following suggested materials have more information and activities that you may use to supplement this\nreview. Some of the examples and materials used in this review come from examples in these links:\n\n- The [Kahn Academy courses on Differential and Integral calculus](https://www.khanacademy.org/math/calculus-1?t=classes) \n as well as [Integral Calculus](https://www.khanacademy.org/math/integral-calculus) would be good \n reviews for weeks 7 and 8 materials.\n- There are multiple good online textbooks for studying or reviewing differential and integral Calculus.\n There are several listed [here](https://www.math.ucdavis.edu/resources/learning/online-textbooks/)\n (I may be assigning some readings from here when we review Probability and Linear Algebra as well).\n I also like the [MIT Online Calculus book](https://ocw.mit.edu/resources/res-18-001-calculus-online-textbook-spring-2005/textbook/).\n- [Basic Calculus Refresher (UW-Madison)](http://pages.stat.wisc.edu/~ifischer/calculus.pdf) - a lot of the content\n of this review came from this 20 page calculus refresher.\n- Kahn Academy [Introduction to Integral Calculus](https://www.khanacademy.org/math/ap-calculus-ab/ab-integration-new/ab-6-1/v/introduction-to-integral-calculus)\n- [Understanding Calculus in 10 min](https://www.youtube.com/watch?v=WjJ-kpgps1c)\n\n# Functions and Graphs\n\nWe have been using functions in both the mathematical sense and the programming sense extensively in this\nclass. In the mathematical sense, the simplest function is a function of a single independent variable\n$x$. We often also use a dependent variable $y$ and say that \"y is a **function** of x\", written this\nway\n\n\\begin{equation}\ny = f(x)\n\\end{equation}\n\nThe simplest function we can imagine is a constant function, for example, \n\n\\begin{equation}\ny = 3\n\\end{equation}\n\nHere you may ask how is this a function of the independent variable $x$? In this case it is not, $y$ does\nnot depend on $x$, although we can also think of it like this:\n\n\\begin{equation}\ny = 0 \\cdot x + 3\n\\end{equation}\n\nWe could also graph this constant function. It is a pretty uninteresting plot, since the value of $y$ is \nalways 3 no matter what the value of $x$ is:\n\n\n```python\n# Example of constant function, it doesn't matter what the\n# independent variable x value is, y is always a constant 3\n# y = 3\ndef f(x):\n return 0*x + 3\n\n\nx = np.linspace(-3, 3)\nplt.plot(x, f(x));\nplt.ylim([-1, 4])\nplt.grid();\n```\n\n## Slope of a Line and the Slope-Intercept Equation\n\nThe slope of a line is simply the ratio of the change in $y$, written as $\\Delta y$ to the change in $x$, $\\Delta x$\n\n\\begin{equation}\nm = \\frac{\\Delta y}{\\Delta x}\n\\end{equation}\n\n(m is often used to represent the slop of a line). For our previous equation $y = 0x + 3$ you\nshould see that the slope of the line is 0, because $y$ never changes\nthus the ratio is 0. We say that the line has a slope of 0 in this case. \n\nLets try a different function, say\n\n\\begin{equation}\ny = 2x\n\\end{equation}\n\nHere is the graph of this line.\n\n\n```python\ndef f(x):\n return 2*x\n \nx = np.linspace(-3, 3)\nplt.plot(x, f(x));\nplt.xlim([-6, 6])\nplt.grid();\n```\n\nHere the slope $m = 2$ because for every change of $x$ $\\Delta x = 1$, $y$ will change by 2 $\\Delta y = 2$\nand thus the ratio is $m = \\Delta y / \\Delta x = 2 / 1 = 2$\n\nIf we add another term to the equation\n\n\\begin{equation}\ny = 2x + 3\n\\end{equation}\n\nThe graph of the equation now looks like this:\n\n\n```python\ndef f(x):\n return 2*x + 3\n\nx = np.linspace(-3, 3)\nplt.plot(x, f(x));\nplt.xlim([-6, 6])\nplt.grid();\n```\n\nHere the slope of the line is still the same $m = 2$. But when $x = 0$ $y$ has a value of $3$.\nWhenever you rearrange a linear function into the form $y = mx + b$, this is known as the slope-intercept\nform of the equation of the line. $m$ will be the slope, which gives the ratio of how $y$ changes to the amount\nthat $x$ changes. The constant $b$ will be the intercept of the line. When $x = 0$ this will be the value of $y$\nor in other words this will be the intercept location, the value of $y$ when x changes from negative to positive (at\nthe point $x = 0$ ).\n\nAt this point you should understand the following about the slope and the equation of a line\n\n- A line always has a constant slope. At all places on the line, the slope is always the same $m$. The\n slope never changes.\n- The slope-intercept equation of a line allows you to directly see the slope of the line and the intercept\n location where the line crosses the axis at $x = 0$.\n- A positive slope, like $+2$ above will describe a line that goes up, as $x$ gets bigger $y$ gets bigger. You can of\n course have a negative slope, in which case the line goes down, as $x$ gets bigger $y$ decreases.\n- A slope of 0 is a constant function, and defines a flat line as seen on its graph.\n\n## Other Functions of a Single Variable\n\nA line is a fairly simple function of a single varible. We can of course have much more complex functions, even\nif we still restrict ourself to functions of a single variable $f(x)$. Here are a few examples\n\n\\begin{equation}\ny = x^2 + 2x + 1 \\\\\ny = \\frac{2}{3}x^3 - 5x^2 + 5 \\\\\ny = x^{-1} \\\\\ny = 2^x\n\\end{equation}\n\nThe first 2 equations are examples of polynomial functions. Anytime $y$ is a functions of a power of $x$\nlike $x^1, x^2, x^3 \\cdots$ is an example of a polynomial function. The first function with a power of $x^2$\nis known as a quadratic function and the second with $x^3$ is a cubic function. The last equation is an\nexample of an exponential function (the $x$ appears in the exponent of one of the terms of the function).\n\nWe can of course graph these equations in a similar way as we did for our linear equations. They define\na unique mapping from any value of $x$ to a unique single value of $y$, so by mapping many values of $x$ to $y$ over some range\nwe can see the shape of the equation in that range. Here are the quadratic and cubic equations from above plotted separately.\n\n\n```python\ndef quadratic_function(x):\n return x**2\n\ndef cubic_function(x):\n return 2/3 * x**3 - 5 * x**2 + 5\n\nx = np.linspace(-5, 5)\n\nplt.subplots(1,2)\nplt.subplot(121)\nplt.plot(x, quadratic_function(x))\nplt.grid();\n\n\nplt.subplot(122)\nplt.plot(x, cubic_function(x))\nplt.grid();\n\n```\n\n# Limits and Derivatives\n\nThe higher order polynomial functions, and in fact most any more complex function of the variable $x$\nno longer have a constant slope. The rate of change of the line at any point $x$ of the function will\ndepend on the function properties at that point. \n\nLets say we want to know what the slope is of the basic quadratic function $y = x^2$ is at the point where $x = 2$.\nWe could use the equation for the slope of a line, and calculate the ratio of the change of $y$ to $x$\nlike this:\n\n\n\n\n```python\ndef f(x):\n return x**2\n\nplt.figure(figsize=(10,10))\nx = np.linspace(0, 5)\nplt.plot(x, f(x));\n\n\n# slope when x changes from 2 to 5 is\ndeltay = f(5.0) - f(2.0)\ndeltax = 5.0 - 2.0\nm = deltay / deltax\nprint(\"slope when x changes from 2 to 5: \", m)\nplt.plot([2.0, 5.0], [f(2.0), f(5.0)], 'k--')\n\n# slope when x changes from 2 to 4 is\ndeltay = f(4.0) - f(2.0)\ndeltax = 4.0 - 2.0\nm = deltay / deltax\nprint(\"slope when x changes from 2 to 4: \", m)\nplt.plot([2.0, 4.0], [f(2.0), f(4.0)], 'k--')\n\n# slope when x changes from 2 to 3 is\ndeltay = f(3.0) - f(2.0)\ndeltax = 3.0 - 2.0\nm = deltay / deltax\nprint(\"slope when x changes from 2 to 3: \", m)\nplt.plot([2.0, 3.0], [f(2.0), f(3.0)], 'k--')\n\n# slope when x changes from 2 to 3 is\ndeltay = f(2.1) - f(2.0)\ndeltax = 2.1 - 2.0\nm = deltay / deltax\nprint(\"slope when x changes from 2 to 2.5: \", m)\nplt.plot([2.0, 2.1], [f(2.0), f(2.1)], 'k--')\n\n# plot the tangent line, instantaneous slope is 4\n# instantaneous slope (derivative) is 4, so line is y = 4x + b that goes through point (2,4), so y = 4x -4\n# plot tangent at x=1.5 to x=3.5\nx1 = 1.0\ny1 = 4 * x1 - 4\nx2 = 3.5\ny2 = 4 * x2 - 4\nplt.plot([x1, x2], [y1, y2], 'r-')\nplt.plot(2, 4, 'ro');\nplt.grid();\n\n# example of slope as delta x decreases from 1 in powers of 10\nx = 2\ndeltax = 10\n\nfor i in range(8):\n deltax = deltax / 10\n deltay = f(x + deltax) - f(x)\n m = deltay / deltax\n print(\"slope at x=%f for deltax=%0.16f is:%0.16f\" % (x, deltax, m))\n```\n\nYou should intuitively see that as we make the change in $x$ smaller ($\\Delta x$) the lines they define that we\nmeasure the slope of are approaching the red line. The red line represents the tangent to the curve right at the point\nwe want to measure the slope $x = 2$. For a quadratic curve like this one, the slope is not constant, it is constantly\nchanging. Each location on the equation will have a slightly different slope. But we can measure the\n\"instantaneous slope\", also called the \"instantaneous rate of change\" at a given point. This is simply the slope\nof the red line shown. More formally, in the limit as $\\Delta x$ gets smaller and smaller and eventually reaches\n0, the lines we measure the slope of get closer and closer to the red line, the tangent line which is the true\ninstantaneous slope of the equation at the point $x = 2$. Formally we can use the concept of a limit to specify\nthis idea:\n\n\\begin{equation}\nm_{\\text{tan}} = \\lim\\limits_{\\Delta x \\to 0} \\frac{\\Delta y}{\\Delta x} = \\lim\\limits_{\\Delta x \\to 0} \\frac{f(x + \\Delta x) - f(x)}{\\Delta x} \n\\end{equation}\n\nThis idea, denoted by the notation $\\frac{dy}{dx}$ is called the **derivative** of the function \n$y = f(x)$ measured instantaneously at a given point $x$. The derivative is another name for this notion\nof the measure of the instantaneous rate of change, or the slope of the function at a particular point on\nthe function.\n\nThere are many different notations to represent this concept of the derivative:\n$\\frac{d f(x)}{dx}$, $\\frac{d}{dx} f(x)$, $f'(x)$. (The last one is sometimes referred to as \"prime notation.\") \n\nIt is possible to come up with a formula that can be used to calculate the derivitaive of a function at\nany point. For example, lets look quickly at the function $y = f(x) = x^2$ above. For any value of $x$,\nusing the definition above, we have the following expression\n\n\\begin{equation}\nm = \\frac{\\Delta y}{\\Delta x} \n = \\frac{(x + \\Delta x)^2 - x^2}{\\Delta x} \n = \\frac{x^2 + 2x \\Delta x + (\\Delta x)^2 - x^2}{\\Delta x}\n = \\frac{\\Delta x (2x + \\Delta x)}{\\Delta x}\n = 2x + \\Delta x\n\\end{equation}\n\nThe previous sequence may look complicated, but we are using simple algebra to expand and cancel out terms, just\nwith the maybe unfamiliar term $\\Delta x$ in the expressions. The result of this rearrangement though shows\nsomething interesting. This says simply that the slope of any line at any point of the function\nis $2x + \\Delta x$ for a given $\\Delta$. But also it says, in the limit, when $\\Delta x = 0$, the\ninstantaneous slope will be simply $2x$. Or in other words we have shown that for our function $f(x) = x^2$\n\n\\begin{equation}\n\\frac{d f(x)}{dx} = 2x\n\\end{equation}\n\nThis means that the derivative (instantaneous rate of change) of the function is $2x$ at any point $x$\nof this function. We can use this expression for the derivative of our function $y = x^2$\nto determine the instantaneous rate of change at any point of our function. For example:\n\n\n```python\ndef f(x):\n \"\"\"The simple quadratic function we are using y = x^2\n \"\"\"\n return x**2\n\ndef df(x):\n \"\"\"The derivative of our equation, can be used to determine the instantaneous\n rate of change, or in other words the slope, of the equation at any particular\n point x.\n \"\"\"\n return 2 * x;\n\ndef plot_tangent_line(x):\n \"\"\"A little utility function, this will plot a tangent line\n on the current figure at the location x, making use of the\n slope of the function f(x) using its derivative df(x), and\n plotting a line that goes through x with that slope\n \"\"\"\n # determine value of y at the point x, and the slope of the line\n # at point x\n y = f(x)\n m = df(x)\n \n # y = mx + b\n # we have y and m for our needed line, need to determine\n # correct value of be, so rearrange\n # b = y - mx\n # and determine the correct intercept of the tangent line\n b = y - m * x\n \n # we will plot a line from -0.5 to +0.5 of x\n deltax = 0.75\n x0 = x - deltax\n x1 = x + deltax\n \n # we have the equation of the line, and we have two point x0, x1, determine\n # the points y0, y1 on the line\n y0 = m * x0 + b\n y1 = m * x1 + b\n \n # now we can plot the tangent line\n plt.plot([x0, x1], [y0, y1], 'r--')\n \n # plot a marker at the tangent point\n plt.plot(x, y, 'ro')\n \n # annotate the plot\n plt.text(x+0.05, y, 'x = %f\\nm = %f' % (x, m))\n \n \n# plot the original function\nx = np.linspace(-5.0, 5.0)\nplt.plot(x, f(x))\nplt.grid();\n\n# plot some tangent lines at different points, using the derivative (slope) of\n# the function to do it. We use a small utility function to plot several\n# example tangent lines\nplot_tangent_line(-4)\nplot_tangent_line(-2)\nplot_tangent_line(0)\nplot_tangent_line(2)\nplot_tangent_line(4)\n```\n\n# General Rules of Derivation\n\nUsing similar methods to this, we can also analyze functions like $y = x^3$ or $y = x^4$. In general if you do\nthis you can easily see that a general rule exists for any power function $x^p$. Namely if $y = f(x) = x^p$\nthen\n\n**Power Rule**\n\n\\begin{equation}\n\\frac{d}{dx} (x^p) = p x^{p-1}\n\\end{equation}\n\nThis means that for example for the function $y = x^5$ the derivative of this function can be calculated\nas\n\n\\begin{equation}\n\\frac{dy}{dx} = f'(x) = 5 x^{4}\n\\end{equation}\n\nLikewise through similar analysis it is possible to derive other general rules of derivation. Here are a few\nthat are useful:\n\n**Exponential Rule**\n\nIf $y = f(x) = b^x$ then\n\n\\begin{equation}\n\\frac{d}{dx} (b^x) = b^x \\ln(b)\n\\end{equation}\n\nIf $y = f(x) = e^{ax}$ then\n\n\\begin{equation}\n\\frac{d}{dx} (e^{ax}) = a e^{ax}\n\\end{equation}\n\n\n**Logarathim Rule**\n\nif $y = f(x) = \\log_b(x)$ then\n\n\\begin{equation}\n\\frac{d}{dx} (\\log_b(x)) = \\frac{1}{x} \\frac{1}{\\ln(b)}\n\\end{equation}\n\nas a special case, when $(b = e)$ then\n\n\\begin{equation}\n\\frac{d}{dx} (\\ln(x)) = \\frac{1}{x}\n\\end{equation}\n\n\n## Properties of Derivatives\n\nGiven some general rules like this, we can define several properties of derivatives, that allow us to\ndetermine exact equations for the derivatives of many different functions and combinations of functions. \n\n1. Derivative of a **constant**\n2. **Sum and Difference Rules**\n3. **Product Rule**\n4. **Quotient Rule**\n5. **Chain Rule**\n\nIn a introductory calculus class you often spend a lot of time deriving the derivative\nof mathematical expressions and learning to apply these rules to determine the symbolic\nderivative for many types of functions. In this class we do not really calculate\nsymbolic solutions for the derivatives of functions, because we are learning about\ncomputational (approximate) methods to calculate things like the derivative of\nfunctions. So if you are rusty or haven't learned or practiced how to determine symbolically\nthe expression for the derivative of a function, it is not really that important for this\nclass, as long as you understand the basic concept of a derivative and what it is\nand what it means. With a solid understanding of the concept of a derivative, we can\nthen better understand the uses we might put this concept to to solve other types of \nproblems, including its relationship to the concept of an integral.\n\n\n# Applications of Derivatives: Roots and Minima / Maxima\n\n## Finding roots of an Equation\n\nIt is often useful to find what are known as the **roots** of an equation, i.e. the location where a function\n$f(x) = 0$, or in other words the values where the graph of $f(x)$ intersects the x-axis. Algebraically this can\nbe extremely tedious or even impossible, so we often use numerical techniques. We will later look at a few such\nroot finding techniques. The most basic technique known as the Newton method, or the Netwon-Raphson method, starts\nwith an initial guess $x_0$ and then produces a sequences of values (i.e.\nit defines a series) that converges to a numerical solution\nof a root. By iterating the expression\n\n\\begin{equation}\nx_i = x_{i-1} - \\frac{f(x_{i-1})}{f'(x_{i-1})}\n\\end{equation}\n\nTake for example the function\n\n\\begin{equation}\nf(x) = x^3 - 21 x^2 + 135x - 220\n\\end{equation}\n\n\nIf we explore the graph of this funtion, it appears to have a root somewhere between 2.4 and 2.6\n\n\n```python\ndef f(x):\n return x**3 - 21 * x**2 + 135 * x - 220\n\nx = np.linspace(2.0, 3.0)\nplt.plot(x, f(x))\nplt.grid();\n```\n\nStarting with an initial value of $x_0 = 2$ we can iterate using the previous described Newton's method\nlike this:\n\n\n```python\ndef f(x):\n return x**3 - 21 * x**2 + 135 * x - 220\n\ndef df(x):\n \"\"\"Derivative of f(x)\n \"\"\"\n return 3 * x**2 - 42 * x + 135\n\nNUM_ITER = 10\nx = np.zeros(NUM_ITER)\nx[0] = 2.0\nprint(0, x[0])\nfor i in range(1, NUM_ITER):\n x[i] = x[i-1] - f(x[i-1]) / df(x[i-1])\n print(i, x[i])\n```\n\n 0 2.0\n 1 2.4126984126984126\n 2 2.461290404582591\n 3 2.461940602324453\n 4 2.4619407179495005\n 5 2.461940717949505\n 6 2.4619407179495045\n 7 2.461940717949506\n 8 2.4619407179495045\n 9 2.461940717949506\n\n\nWe can confirm that this final value in the sequence is indeed a root of the equation\nby plugging it back into the function.\n\n\n```python\nprint(x[9], f(x[9]))\n```\n\n 2.461940717949506 5.684341886080802e-14\n\n\nSince this is a numerical method, the result won't be exactly 0, but the function\nshould essentially be very close to 0 at the point we numerically determined is a\nroot. You can also check the graph of the function below and see that the function\ncrosses the x axis at this value of x.\n\nTo understand why this works, look at the expression for the series. We are\nsubtracting the expression\n\n\\begin{equation}\n\\frac{f(x)}{f'(x)}\n\\end{equation}\n\neach time to come up with the next value in the series. Remember we are trying to find\nthe root of the equation $y = f(x)$. So when $f(x)$ is 0 or close to 0, this\nexpression is going to be 0 or close to 0, and we won't be subtracting much from the\ncurrent value in the series. \n\nAlso we need to combine information about whether $f(x)$ is positive or negative\nalong with information about whether the derivative (slope) is positive or negative\nto determine whether we want to make $x$ bigger or smaller to move in a\ndirection closer to a root. Look at the figure for our example function. At the\nstarting point of $x_0 = 2$, the function $f(x) < 0$ thus $f(x)$ is negative.\nThe root in our vicinity is to the right (we need $x$ to increase). The fact that\nthe derivative (slope) is positive at the point $x_0 = 2$ means that if we increase \n$x$ we should be moving up the curve to a location closer to where $f(x) = 0$. Thus\nby combining information about the sign of $f(x)$ and the sign of the slope\n$f'(x)$ this lets us determine if we need to increase or decrease our next value\nof $x$. In this particular case, since $f(x)$ is negative and the derivative $f'(x)$\nis positive, the expression ends up being negative, and since we are subtracting a negative\nwe end up increasing $x$ in the next step. If instead we had started at\n$x_0 = 3$, the function $f(x)$ would be positive at this location, and the derivative\nwould also be positive, which would indicate we need to subtract some amount from\n$x$ to go towards the root. The same argument/intuition can be made for when the\nderivative is negative, in which case which direction you need to go to approach the\nroot will be reversed from our example here, but again the general Newton's method\nexpression will work to move you closer to the root of the equation.\n\n\n## Minimum and Maximum of Equations\n\nOften it is useful to be able to \"minimize\" or \"maximize\" a function. This means\nthat we want to find the location where the function is at its largest or smallest\nvalue (often restricted to some range).\n\nA function will be at a local maximum or minimum when its derivative is 0. \n\n\\begin{equation}\nf'(x) = 0\n\\end{equation}\n\nTake for example again the same function we have been using\n\n\\begin{equation}\nf(x) = x^3 - 21 x^2 + 135x - 220\n\\end{equation}\n\n\n```python\ndef f(x):\n return x**3 - 21 * x**2 + 135 * x - 220\n\nx = np.linspace(2, 12, 1000)\n#x = np.linspace(2.45, 2.47)\nplt.plot(x, f(x))\nplt.grid();\n```\n\nIf we take the derivative of the function and set it to 0 to find\nthe locations of the minima and maxima we have\n\n\\begin{equation}\nf'(x) = 3x^2 - 42x + 135 \\\\\n3x^2 - 42x + 135 = 0 \\\\\n3(x - 5) (x - 9) = 0\n\\end{equation}\n\nWe could have used the quadratic equation to determine the solution to setting our\nderivative to 0, but in this case we can also relatively easily factor the quadratic\nexpression to easily see where the roots must be located.\nThus wee see that when $x = 5$ or $x = 9$ these will be solutions to this equation,\nand from the graph we see that these are indeed the locations of the minimum and the\nmaximum of the function.\n\n# Integrals of Functions\n\n\nA definite integral of a continuous function $f(x)$ is a measure of the area under the graph of $f$ in\nsome interval $[a, b]$. The integral of a function is related to the derivative of the function. It is not\ntoo difficult to derive this association. Lets say you have a continuous function $f(x)$ and you want to\nfind the area under the curve of this graph in the interval $[a, x]$ from some *fixed* lower value $a$ to\nany *variable* upper value $x$.\n\n\n\n\n```python\ndef f(x):\n \"\"\"An example of a specific function we want to find the area under the\n graph of.\n \"\"\"\n return x * (x - 3) * (x - 6) + 20\n\nplt.figure(figsize=(16, 12))\nx = np.linspace(0, 6.25)\nplt.plot(x, f(x), 'k-', linewidth=3)\nplt.grid();\n\n# a = 0, x = 4, deltax = 2\n# represent F(x), function to calculate area from fixed a to x\na = 0\nb = 4\ndeltax = 2\nz = 5.35\nx = np.linspace(a, b)\nplt.fill_between(x, f(x), color='lightblue')\n\n# represent F(x + deltax) - F(x)\ndeltax = 2\nx = np.linspace(b, b+deltax)\nplt.fill_between(x, f(x), color='lightgreen');\n\n# label the graph\n# first remove the specific tics and set general/example tic labels\nplt.yticks([0])\nplt.xticks([a, b, z, b+deltax], ['$a$', '$x$', '$z$', '$x + \\Delta x$'], fontsize=20);\n\n# label the functions\nplt.xlim([0, 7.6])\nplt.text(2.75, 25, '$y = f(x)$', fontsize=20)\nplt.text(1.5, 12, '$F(x)$', fontsize=20)\nplt.text(6.25, 15, '$f(z)$', fontsize=20)\nplt.arrow(6.25, 15, z-6.05, f(z)-14.4, head_width=0.1, head_length=0.5, color='black')\nplt.text(6.25, 7, '$F(x + \\Delta x) - F(x)$', fontsize=20)\nplt.arrow(6.25, 7, -0.5, 0, head_width=0.2, head_length=0.1, color='black')\n\n# add lines for width and height of area\nplt.plot([z, z], [0, f(z)], 'k--')\nplt.plot([b, b+deltax], [f(z), f(z)], 'k--');\n```\n\nLet $F(x)$ = Area under the graph of $f$ in the interval $[a, x]$.\n\nthen $F(x + \\Delta x)$ = Area under the graph of $f$ in the interval $[a, x + \\Delta x]$\n\nif we take the difference of these two areas we have \n\n\\begin{equation}\nF(x + \\Delta x) - F(x) = \\text{Area under the graph of} f \\; \\text{in the interval} \\; [x, x + \\Delta x]\n\\end{equation}\n\nThe area of this difference (the green bit of the figure) has to be equal to the area of a rectangle with height $f(z)$,\nwhere $z$ is some value in the interval $[x, x + \\Delta x]$, and with width of $\\Delta x$,\nthus the area of the previous difference can be written as:\n\n\\begin{equation}\nF(x + \\Delta x) - F(x) = f(z) \\Delta x\n\\end{equation}\n\nrewriting we have\n\n\\begin{equation}\n\\frac{F(x + \\Delta x) - F(x)}{\\Delta x} = f(z)\n\\end{equation}\n\nThis should look a little familiar. This is the finite difference equation we used (but with the function $F$) in\ndeveloping the concept of the derivative. If we take this expression in the limit again as $\\Delta x \\to 0$\nwe see that the right hand side $f(z)$ becomes $f(x)$ (because z is some value in the interval from\n$[x, x + \\Delta x]$, and as $\\Delta x \\to 0$, $z$ simply becomes $x$). Thus we have\n\n\\begin{equation}\n\\frac{d}{dx} F(x) = f(x)\n\\end{equation}\n\n$F$ is called the **antiderivative** of $f$. In other words, $F$ is the function such\nthat, if you take the derivative of it $F'(x)$ you will end up the the function\n$f(x)$. In essence, if you do the inverse of the process of determining\nthe derivative of a function, we can use this antiderivative to calculate values of the function $F$ in order to\nexactly measure the area under the curve of functions $f$.\n\nWe formally express this concept of calculating the area under the graph of a function $f$ from its\nantiderivative using the symbol for the definite integral of a function like this:\n\n\\begin{equation}\nF(x) = \\int_a^b f(x) \\; dx\n\\end{equation}\n\n## Properties of Integrals\n\nIntegrals possess the analogues of the properties of derivatives. For example the antiderivative\nof a constant and of the sum and difference of functions work in the same way as for derivatives.\nThe Power Rule, Logarithm Rule and Exponential Rule work basically in an inverted manner to calculate\nthe antiderivative of a function.\n\n## Calculating Areas using Definite Integrals\n\nIf you can calculate the antiderivative of a function $f$, you can use this to calculate the area under\nthe graph of the curve of the function $f$ on any finite interval $[a, b]$.\n\nFor example, take the function\n\n\\begin{equation}\nf(x) = x^3 (1 - x^4)^2\n\\end{equation}\n\nThe graph of this function in the interval $[0, 1]$ looks like this.\n\n\n```python\ndef f(x):\n return x**3 * (1 - x**4)**2\n\na = 0\nb = 1.0\nx = np.linspace(a, b, 1000)\nplt.plot(x, f(x), 'k-', linewidth=3)\nplt.fill_between(x, f(x))\nplt.grid();\n```\n\nAs a rough estimate, since the maximum height of the function is 0.2, we know that the area of the box is 0.2.\nThe area under the graph looks like it is probably less than $1/2$ of the total area of this bounding box, so\nI would expect an area of a bit under 0.1 for this function.\n\nWe can calculate the antiderivative of the function. This function is a polynomial, so it is probably easiest\nto simply exapand the terms and then calculate the antiderivative of the sum/difference of the terms, like this:\n\n\\begin{equation}\n\\int_0^1 x^3 (1 - x^4)^2 \\; dx \\\\\n\\int_0^1 x^3 (1 - 2x^4 + x^8) \\; dx \\\\\n\\int_0^1 x^3 - 2x^7 + x^{11} \\; dx \\\\\n\\end{equation}\n\nThe antiderivative of simple terms raised to a power will use the reverse of the Power Rule, ths we have the\nantiderivative\n\n\\begin{equation}\nF(X) = \\Big[ \\frac{x^4}{4} - \\frac{2 x^8}{8} + \\frac{x^{12}}{12} \\Big]_0^1\n\\end{equation}\n\n(We leave it as an exercise for the student to prove to yourself that if you\ntake the derivative $\\frac{d}{dx} F(X)$ you get the original function $f(x)$).)\n\nNotice the notation of the 0 and 1 on the expression for the antiderivative here. To use this\nantiderivative to calculate the area under the curve exactly, you take\n\n\\begin{equation}\nF(b) - F(a)\n\\end{equation}\n\nthus we can calculate the area of this particular function in the interval $[a=0, b=1]$ as\n\n\\begin{equation}\n\\Big[ \\frac{1^4}{4} - \\frac{2 \\cdot 1^8}{8} + \\frac{1^{12}}{12} \\Big] - \n\\Big[ \\frac{0^4}{4} - \\frac{2 \\cdot 0^8}{8} + \\frac{0^{12}}{12} \\Big] =\n\\frac{1}{12} - 0 = \\frac{1}{12} = 0.083333\n\\end{equation}\n\nThis is the general procedure for calculating a definite integral symbolically\n(an exact solution). You first need to derive the expression\nfor the antiderivative, using the inverse of the derivative rules, if you can. If such an antiderivate\nexpression is possible, then the area under the curve for any definite interval can be calculated by taking\nthe difference of the antiderivative on the two ends of the interval.\n\n# Acknowledgements and Versions\n\n\n```python\n%load_ext version_information\n\n%version_information numpy, scipy, matplotlib\n```\n\n\n\n\n
SoftwareVersion
Python3.7.3 64bit [GCC 7.3.0]
IPython7.6.1
OSLinux 5.0.0 29 generic x86_64 with debian buster sid
numpy1.16.4
scipy1.3.0
matplotlib3.1.0
Fri Oct 04 09:59:24 2019 CDT
\n\n\n", "meta": {"hexsha": "16a602953988ce905d432ca7dee0cf1486e2eddb", "size": 316686, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "lectures/review/U00-3-Calculus-Review.ipynb", "max_stars_repo_name": "tgrasty/CSCI574-Machine-Learning", "max_stars_repo_head_hexsha": "bcf797262852c4b46a6702c69f69724b0b9e93f6", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lectures/review/U00-3-Calculus-Review.ipynb", "max_issues_repo_name": "tgrasty/CSCI574-Machine-Learning", "max_issues_repo_head_hexsha": "bcf797262852c4b46a6702c69f69724b0b9e93f6", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lectures/review/U00-3-Calculus-Review.ipynb", "max_forks_repo_name": "tgrasty/CSCI574-Machine-Learning", "max_forks_repo_head_hexsha": "bcf797262852c4b46a6702c69f69724b0b9e93f6", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-17T17:03:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T17:03:58.000Z", "avg_line_length": 236.1565995526, "max_line_length": 48092, "alphanum_fraction": 0.9089066141, "converted": true, "num_tokens": 8845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.18316787324075146}} {"text": "# Topic 1: Probability\n\n## Associated Reading: Bishop 1.1, 1.2, 2.1\n\n## 1. A definition of probability\nWe live in an uncertain world. Sometimes, as computer scientists, we're sheltered from that because we think about things like deterministic algorithms for which there are certain guarantees about, for example, the amount of time it will take to run, or perhaps even more basic, that the procedure will yield a correct result every time. For a given input, the path to a given output is well-defined (suspending consideration of the very interesting class of randomized algorithms). However, when we do Machine Learning, we're doing something a bit different: we don't know how to write the program, so we're going to try and reconstruct it by observing the world$^1$. In so doing, we have to come to terms with the notion that those observations are going to be imperfect in a variety of ways: imperfection in our means of observing, systematic errors in the way that we represent such information, wrong assumptions about how we allow our learning machines to behave, and old-fashioned, honest-to-goodness randomness. Ignoring these sources of imperfection does not work: it is far better to be conscious of our uncertainties than overconfident in a notion that doesn't actually capture the truth. The practical implications of this is that we are going to need to become comfortable expressing the lessons that we learn from data, and the predictions that we make based on what we've learned, in a language that's suited towards expressing these uncertainties. That language is probability. \n\nThe stuff that we need to start working with the language of probability in a practical way is less extensive than you are probably expecting. All that we need to take us quite a ways is a definition and a few rules for manipulation. Let's start with a definition, and there's actually some competition between a few different ideas here. You would think that with the ubiquity of statistics in modern society, that this would have already been settled 200 years ago. But no, the debate continues to this day. The two candidate definitions are:\n- (Frequentist) $P(X=x)$ is the number of times we observe that a random variable $X=x$ for an infinite number of trials, divided by the total number of trials. For example, in the limit as $n\\rightarrow \\infty$, the probability of a fair coin landing on heads is 1/2, so $P(coin=heads)=0.5$. \n$$ \\frac{N_{X=x}}{N_{trials}}, N_{trials}\\rightarrow \\infty $$\n- (Bayesian) $P(X=x)$ is the degree to which we believe that for a given trial, we will observe that $X=x$. So for $P(X=x)=1$, we're certain that $X=x$, and for $P(X=x)=0$, we're certain that this is not the case, and $P(X=x) = 0.5$, it's fifty-fifty. \n\nThe difference probably seems totally pedantic to you right now, but it actually isn't, especially in the context of machine learning or inverse problems in general. In the case of the coin flip example, there's really not that much difference, because we can perform many repeats of the same experiment, such that we can approximate the limit as the number of trials go to infinity, and use those trials to update our probabilistic model of the coin. However, there's a meaningful distinction when we start to reason about things that we can't conduct experiments on. My research application area is in predicting change in the polar ice caps, and it provides a nice example: let's say that $\\mathcal{H}$ is the specific hypothesis that 200 years from now, the Greenland Ice Sheet will have completely melted. Intuitively, it's reasonable to ask what's $P(\\mathcal{H})$? What's the probability that this hypothesis is true? \n\nIf we plug this specific case into the frequentist definition, we see the problem: $P(H)$ is the number of times that we observe the Greenland Ice Sheet to melt out of an infinite number of trials? We don't have an infinite number of trials to work with: we only have the one. In contrast, there's no particular problem with the Bayesian definition: it's simply a statement that $P(H)$ encodes our current state of information about Greenland's future, or more generally $P(H)$ is a formal quantification of the information that we have about a preposition, when we're not yet exactly sure whether the preposition is true or false. In fact, this idea is just a generalization of something that you already know about, which is prepositional logic: probability is the extension of logic to situations where prepositions aren't either one or zero, but something in the middle. If it's not already clear, this second so-called Bayesian definition of probability is the one that we're going to concern ourselves with. For practical purposes, we need to know just a few identities that largely mirror prepositional logic: the product rule, which is akin to the AND operation, and the sum rule, which is akin to OR. \n\n$^1$. (This analogy is pretty loose, because we're actually going to exert quite a bit of control on exactly what types of programs we \"learn\" by specifying a mathematical model, although some cutting edge work towards general AI is indeed oriented towards trying to synthesize syntactically valid programs from data). \n\n## 2. Joint probability rules\n\n\nThese two rules are best understood in the context of joint probability distributions, or the probability of two events occurring at the same time. For example, $P(X=x,Y=y)$ quantifies our belief that $X=x$ and $Y=y$$^2$.\n\nThis is most easily understood by drawing a grid in two dimensions. On the horizontal axis is the random variable X, on the vertical axis is the random variable Y. Then we divide the axes into three subdivisions each, and call each subdivision 1,2, or 3. \n\n$^2$ (If you haven't seen this upper case-lower case notation before, here's how it works. Upper case letters are random variables: it's just the name of a thing that could take different values. It's been declared, and it has a type, but we don't know the exact value. Lower case letters represent actual specific values. For example if $X$ is a random variable representing the outcome of a coin flip, then the *support* of $X$ is the set $\\{heads,tails\\}$. $x$ in this case is a specific outcome from that set, i.e. for a fair coin $P(X=heads) = 50$%.) \n\n### 2.1 Sum rule\nSo imagine, that this thing is a set of boxes, and we're randomly throwing balls into the boxes. The probability of the ball landing in any particular box is given by the joint probability $P(X,Y)$. In our case, we have 9 cells, so $P(X=2,Y=2) = 1/9$. \n\n**Now, what is $P(X=2)$?**\n\nIt is, of course, $1/3$. This is pretty obvious, but it's instructive to write it as \n$$P(X=2) = P(X=2,Y=1) + P(X=2,Y=2) + P(X=2,Y=3) = \\sum_{i=1}^3 P(X=2,Y=y_i) = 1/3.$$\n$P(X=2)$ is known as the *marginal probability*, and this procedure is known as the sum rule, or generally:\n$$\nP(X=x_j) = \\sum_{i=1}^m P(X=x_j,Y=y_i). \n$$\n\n### 2.2 Product rule\nNow let's consider cases where we're given the value of one of the random variables. This is called *conditional probability*, annotated $P(Y=y_j|X=x_i)$. \n\n**If we know that $X=2$, what is the probability that $Y=2$?** This is pretty obvious graphically, but worth writing down the actual mathematical relationship between the joint distribution and the conditional, which is \n$$P(X=x,Y=y) = P(X=x|Y=y) P(Y=y)$$. We are after the first term on the right side, so if we divide the left hand term (which is 1/9) by the rightmost (which is 1/3), we get, as expected, 1/3. \n\n### 2.3 Exchangability \nNothing changes if we swap the axis-labels, so $P(X=x,Y=y) = P(Y=y,X=x)$.\n\n### 2f.4 Conditional probability examples\nEquipped with these probability rules, now let's use them to answer some simple questions. To begin, Let's say that we've got two two bowls, green and blue. Inside green, we have 1 kiwis and 3 oranges. Inside blue, we have 3 kiwis and 1 orange. Now what if I asked the question, whats the probability of drawing an orange if I sample from both bowls with equal likelihood? Then we have that\n\\begin{align}\nP(Orange) & = P(Orange,Blue) + P(Orange,Green) \\\\\n & = P(Orange|Blue)P(Blue) + P(Orange|Green)P(Green) \\nonumber \\\\\n & = (1/4)(1/2) + (3/4)(1/2) = 1/2. \\nonumber\n\\end{align}\n*Note that I've simplified notation a little bit: Instead of writing P(Fruit=Orange,Bowl=Blue), I'm just writing P(Orange,Blue)*. What if I move these three kiwis out of blue, and into green. So now there's 1 orange in green, and 4 kiwis and three oranges in blue. What's the probability of an orange?\n\\begin{align}\nP(Orange) & = P(Orange,Blue) + P(Orange,Green) = P(Orange|Blue)P(Blue) \\nonumber \\\\\n & + P(Orange|Green)P(Green) \\nonumber \\\\\n & = (3/7)(1/2) + (1)(1/2) = 3/14 + 7/14 = 5/7\n\\end{align}\nWe are now more likely to pick a bowl with more oranges, so the overall likelihood of picking an orange goes up. Now, what if I ask, under the same rules as above, \"I picked an orange. What is the probability that this orange came from the green bowl?\". This requires a bit more thought. Before, we had a scenario where our conditional probabilities were determined entirely by things that we knew already. Given a bowl color, I can tell you directly what the probability of a fruit is. But in this case, oranges could come from either bowl, so having an orange doesn't directly determine the probability of a bowl. Instead we need to come up with a rule for inverting probability in some way. And this isn't very difficult using the tools we have above. Let's start with the identity:\n$$P(X=x,Y=y) = P(Y=y,X=x),$$\nnow apply the product rule and divide:\n$$P(X=x|Y=y) = \\frac{P(Y=y|X=x)P(X=x)}{P(Y=y)}$$\nNow we can use this result directly:\n$$P(Green|Orange) = \\frac{P(Orange|Green)P(Green)}{P(Orange)} = (1)(1/2)(7/5) = 7/10$$\nBecause green was a sure bet for orange, and the probability of choosing green was equal to that of blue, we find that it's quite a bit more likely that the orange came from the green bowl.\n\n### 2.5 Bayes rule\nThe formula that we used to compute this turns out to be so important that it has its own special proper-noun name: Bayes' Theorem. The name is stupid by the way, it was in fact Pierre-Simon Laplace who first understood it in its modern usage and also developed some of its philosophical implications. And once again, you're probably thinking \"so what?\", how does this help me do machine learning? And the answer becomes a little bit more plain if we apply Bayes' theorem to the case where we have to pick between competing hypotheses that describe the world, which we'll call models $M$ given some real data about the world, which we'll call $D$. Bayes' theorem then says \n$$P(M=m|D=d) = \\frac{P(D=d|M=m)P(M=m)}{P(D=d)},$$\nwhich is to say that it provides us a statistical formula for selecting between models of reality given observations of said reality. Let's take a look at the anatomy of this equation: The thing on the left is called the *posterior probability* or the probability that a given hypothesis is true after considering the data. On the right hand side, $P(M=m)$ is called the *prior probability*, which is the probability of a particular hypothesis being the correct one *prior* to considering the data. The prior probability is updated according to the first term in the numerator which is called the *likelihood*, which answers the question, assuming that a particular model $M=m$, what is the probability that we will observe the data $y$? Finally, the denominator is often called the *evidence*, and it's the probability of observing the data under all possible hypotheses. \n\nThis formula shapes your life and your thinking in ways that you have never imagined. Least squares linear regression (which we'll get to)? Bayes rule. Want to go bet on a horse race and be sure that you're not being scammed? Bayes' rule. *The fundamental human process of updating actions based on sensory input*? Empirically, also Bayes' rule. Everything (and I mean everything) that we do in this course from here on will be some application of Bayes rule, sometimes explicitly, sometimes implicitly. \n\n\n# Lab 09/02\n*From your group, choose a scribe. Then compose a document responding to the following. When complete, please turn in the assignment to the appropriate link in this week's Moodle page.*\n\nA classic example of Bayes' theorem in action comes from the world of disease testing. This is a really good example because it shows the importance of the prior distribution. So here's the problem: imagine that you're concerned that you have COVID-19, something that currently affects roughly 7 in 1000 people in the US, and you go down to the county health services to take a COVID test. The doctor tells you that the sensitivity of the test is 70%, which is to say that if you have the disease the test will read positive 70% of the time. We also know that the test has a specificity of 98%, which implies that 98% of the time, if you don't have the disease, the test will read negative. Unfortunately, your test comes back positive. \n\n**Compute the probability that you actually have the disease.**\n\n**Using python (matplotlib), generate a plot showing the probability above as a function of the specificity.**\n\n**Devise a simple strategy for reducing the false positive rate**\n\n\n```python\n\n```\n", "meta": {"hexsha": "133d4e370f83b9251c75491607157919a2ef82d1", "size": 14936, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "01_probability.ipynb", "max_stars_repo_name": "UMT-Machine-Learning-2021/01-Probability", "max_stars_repo_head_hexsha": "0c934140887aa5888c1e39586f8b0ac00d4805ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-28T12:37:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T12:37:49.000Z", "max_issues_repo_path": "01_probability.ipynb", "max_issues_repo_name": "UMT-Machine-Learning-2021/01-Probability", "max_issues_repo_head_hexsha": "0c934140887aa5888c1e39586f8b0ac00d4805ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_probability.ipynb", "max_forks_repo_name": "UMT-Machine-Learning-2021/01-Probability", "max_forks_repo_head_hexsha": "0c934140887aa5888c1e39586f8b0ac00d4805ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.8923076923, "max_line_length": 1512, "alphanum_fraction": 0.7060123192, "converted": true, "num_tokens": 3336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.18305262374456877}} {"text": "```\n%pylab inline\nfigsize(12.5,4)\n```\n\n \n Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].\n For more information, type 'help(pylab)'.\n\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are a Bayesian practitioner! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n\n###The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty* about our beliefs. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist* methods assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these universes, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is clear how we can speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate A will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either heads or tails. Now what is *your* belief that the coin is heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true. Though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease.\n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial evidence. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even --especially-- if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being heads. $P(A | X):\\;\\;$ You look at the coin, observe a heads has landed, denote this information $X$, and trivially assign probability 1.0 to heads and 0.0 to tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*.\n\n\n\n###Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: a probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of stastical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools like Least Squares linear regression, LASSO regression, EM algorithm etc. are all very powerful and incredibly fast. Bayesian methods are a compliment to solve the problems these solutions cannot or to gain further insight into the underlying system by offering more flexibility in modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after it's discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nSince every statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure what the ratio of heads is in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no guess apriori. We begin to flip a coin, and record the observations: this is our data. How does our inference change as we observe more and more data? More specifically, what do our posterior probabilities look like?\n\nBelow we plot a sequence of updating posteriors as we observe data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for matplotlib plots.\nIf executing this book, and you wish to use the book's styling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the book's styles/ dir.\n See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to update the styles\n in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\"\"\"\n#the code below can be passed over, as it is currently not important.\nfigsize( 11, 9)\n\nimport scipy.stats as stats\ndist = stats.beta\n#n_trials = [0,1, 2 ,4, 8, 16, 32, 64, 128, 500]\nn_trials = [0,1,2,3,4,5,6,7, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size = n_trials[-1] )\n\nx = np.linspace(0,1,100)\n#y_prior = np.nan*np.ones( 100 )\n\nfor k, N in enumerate(n_trials):\n sx = subplot( len(n_trials)/2, 2, k+1)\n \n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads )\n plt.plot( x, y, label= \"observe %d tosses,\\n %d heads\"%(N,heads) )\n plt.fill_between( x, 0, y, color=\"#348ABD\", alpha = 0.4 )\n plt.vlines( 0.5, 0, 4, color = \"k\", linestyles = \"--\", lw=1 )\n \n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n\n\nplt.suptitle( \"Bayesian updating of posterior probabilties\", \n y = 1.02,\n fontsize = 14);\n\nplt.tight_layout()\n```\n\nAs the plot above shows, as we start to observe data, our posterior probabilities, represented as the above curves, start to shift and move around. Eventually, as we observe more and more data, our probabilities will lump closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the graph is not always *peaked* at 0.5. Apriori, there is no reason it should be. Remember we do not know what $p$ is, we only have seen the data. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5.\n\nThat being said, it does assign a positive probability to $p$ really being 0.5. As more data accumulates, we would see more and more probabilitiy being assigned at $p=0.5$.\n\nThe next example is a simple demonstration of the mathematics of Bayesian updating. \n\n#####Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize( 12, 4 )\np = np.linspace( 0,1, 50)\nplt.plot( p, 2*p/(1+p), color = \"#348ABD\", lw = 3 )\nplt.fill_between( p, 2*p/(1+p), alpha = .2, facecolor = [\"#348ABD\"])\nplt.scatter( 0.2, 2*(0.2)/1.2, s = 140, c =\"#348ABD\" )\nplt.xlim( 0, 1)\nplt.ylim( 0, 1)\nplt.xlabel( \"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title( \"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a graph of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize( 9, 4 )\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar( [0,.7], prior ,alpha = 0.60, width = 0.25, \\\n color = colours[0], label = \"prior distribution\",\n lw = \"3\", edgecolor = colours[0])\n\n\nplt.bar( [0+0.25,.7+0.25], posterior ,alpha = 0.5, \\\n width = 0.25, color = colours[1], \n label = \"posterior distribution\",\n lw = \"3\", edgecolor = colours[1])\n\nplt.xticks( [0.20,.95], [\"Bugs Absent\", \"Bugs Present\"] )\nplt.title(\"Prior and Posterior probability of bugs present, prior = 0.2\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. There are three cases:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can constantly make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. is is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\nWhat is $\\lambda$? It is called the parameter, and it describes the shape of the distribution. For the Poisson random variable, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. Unlike $\\lambda$, which can be any positive number, $k$ must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne very useful property of the Poisson random variable, given we know $\\lambda$, is that its expected value is equal to the parameter, ie.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's something useful to remember. Below we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$ we add more probability to larger values occurring. Secondly, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize( 12.5, 4)\n\nimport scipy.stats as stats\na = np.arange( 16 )\npoi = stats.poisson\nlambda_ = [1.5, 4.25 ]\n\nplt.bar( a, poi.pmf( a, lambda_[0]), color=colours[0],\n label = \"$\\lambda = %.1f$\"%lambda_[0], alpha = 0.60,\n edgecolor = colours[0], lw = \"3\")\n\nplt.bar( a, poi.pmf( a, lambda_[1]), color=colours[1],\n label = \"$\\lambda = %.1f$\"%lambda_[1], alpha = 0.60,\n edgecolor = colours[1], lw = \"3\")\n\nplt.xticks( a + 0.4, a )\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with a *exponential density*. The density function for an exponential random variable looks like:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike the Poisson random variable, an exponential random variable can only take on non-negative values. But unlike a Poisson random variable, the exponential can take on *any* non-negative values, like 4.25 or 5.612401. This makes it a poor choice for count data, which must be integers, but a great choice for time data, or temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. Below are two probability density functions with different $\\lambda$ value. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0,4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l,c in zip(lambda_,colours):\n plt.plot( a, expo.pdf( a, scale=1./l), lw=3, \n color=c, label = \"$\\lambda = %.1f$\"%l)\n plt.fill_between( a, expo.pdf( a, scale=1./l), color=c, alpha = .33)\n \nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We only see $Z$, and must go backwards to try and determine $\\lambda$. The problem is so difficult because there is not a one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is better! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ is. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first: after all, $\\lambda$ is fixed, it is not (necessarily) random! How can we assign probabilities to a non-random event. Ah, we have fallen for the frequentist interpretation. Recall, under our Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, concerning text-message rates:\n\n> You are given a series of text-message counts from a user of your system. The data, plotted over time, appears in the graph below. You are curious if the user's text-messaging habits changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize( 12, 3.5 )\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar( np.arange( n_count_data ), count_data, color =\"#348ABD\" )\nplt.xlabel( \"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim( 0, n_count_data );\n```\n\nBefore we begin, with respect to the plot above, would you say there was a change in behaviour\nduring the time period? \n\nHow can we start to model this? Well, as I conveniently already introduced, a Poisson random variable would be a very appropriate model for this *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure about what the $\\lambda$ parameter is though. Looking at the chart above, it appears that the rate might become higher at some later date, which is equivalently saying the parameter $\\lambda$ increases at some later date (recall a higher $\\lambda$ means more probability on larger outcomes, that is, higher probability of many texts.).\n\nHow can we mathematically represent this? We can think, that at some later date (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we create two $\\lambda$ parameters, one for behaviour before the $\\tau$, and one for behaviour after. In literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\n If, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, the $\\lambda$'s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda_i, \\; i=1,2,$ can be any positive number. The *exponential* random variable has a density function for any positive number. This would be a good choice to model $\\lambda_i$. But, we need a parameter for this exponential distribution: call it $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter*, or a *parent-variable*, literally a parameter that influences other parameters. The influence is not too strong, so we can choose $\\alpha$ liberally. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data, since we're modeling $\\\\lambda$ using an Exponential distribution we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAlternatively, and something I encourage the reader to try, is to have two priors: one for each $\\lambda_i$; creating two exponential distributions with different $\\alpha$ values reflects a prior belief that the rate changed after some period.\n\nWhat about $\\tau$? Well, due to the randomness, it is too difficult to pick out when $\\tau$ might have occurred. Instead, we can assign an *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it would be an ugly, complicated, mess involving symbols only a mathematician would love. And things would only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution. We next turn to PyMC, a Python library for performing Bayesian analysis, that is agnostic to the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that documentation can be lacking in areas, especially the bridge between beginner to hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the above problem using the PyMC library. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random. The title is given because we create probability models using programming variables as the model's components, that is, model components are first-class primitives in this framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nDue to its poorly understood title, I'll refrain from using the name *probabilistic programming*. Instead, I'll simply use *programming*, as that is what it really is. \n\nThe PyMC code is easy to follow along: the only novel thing should be the syntax, and I will interrupt the code to explain sections. Simply remember we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as mc\n\nn = count_data.shape[0]\n\nalpha = 1.0/count_data.mean() #recall count_data is \n #the variable that holds our txt counts\n\nlambda_1 = mc.Exponential( \"lambda_1\", alpha )\nlambda_2 = mc.Exponential( \"lambda_2\", alpha )\n\ntau = mc.DiscreteUniform( \"tau\", lower = 0, upper = n )\n```\n\nIn the above code, we create the PyMC variables corresponding to $\\lambda_1, \\; \\lambda_2$. We assign them to PyMC's *stochastic variables*, called stochastic variables because they are treated by the backend as random number generators. We can test this by calling their built-in `random()` method.\n\n\n```\nprint \"Random output:\", tau.random(),tau.random(), tau.random()\n```\n\n Random output: 55 42 41\n\n\n\n```\n@mc.deterministic\ndef lambda_( tau = tau, lambda_1 = lambda_1, lambda_2 = lambda_2 ):\n out = np.zeros( n ) \n out[:tau] = lambda_1 #lambda before tau is lambda1\n out[tau:] = lambda_2 #lambda after tau is lambda2\n return out\n```\n\nThis code is creating a new function `lambda_`, but really we think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet. The `@mc.deterministic` is a decorator to tell PyMC that this is a deterministic function, i.e., if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = mc.Poisson( \"obs\", lambda_, value = count_data, observed = True)\n\nmodel = mc.Model( [observation, lambda_1, lambda_2, tau] )\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we try to retrieve the results.\n\nThe below code will be explained in the Chapter 3, but this is where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Monte Carlo Markov Chains* (which I delay explaining until Chapter 3). It returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distribution looks like. Below, we collect the samples (called *traces* in MCMC literature) in histograms.\n\n\n```\n### Myserious code to be explained later.\nmcmc = mc.MCMC(model)\nmcmc.sample( 20000, 5000, 1 )\n```\n\n [****************100%******************] 20000 of 20000 complete\n\n\n\n```\nlambda_1_samples = mcmc.trace( 'lambda_1' )[:]\nlambda_2_samples = mcmc.trace( 'lambda_2' )[:]\ntau_samples = mcmc.trace( 'tau' )[:]\n```\n\n\n```\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_1_samples, histtype='stepfilled', bins = 32, alpha = 0.85, \n label = \"posterior of $\\lambda_1$\", color = \"#A60628\",normed = True )\nplt.legend(loc = \"upper left\")\nplt.title(r\"Posterior distributions of the variables $\\lambda_1,\\;\\lambda_2,\\;\\tau$\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda$ value\")\nplt.ylabel(\"probability\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\n\nplt.hist( lambda_2_samples,histtype='stepfilled', bins = 35, alpha = 0.85, \n label = \"posterior of $\\lambda_2$\",color=\"#7A68A6\", normed = True )\nplt.legend(loc = \"upper left\")\nplt.xlim([15,30])\nplt.xlabel(\"$\\lambda$ value\")\nplt.ylabel(\"probability\")\n\nplt.subplot(313)\n\n\nw = 1.0/ tau_samples.shape[0] * np.ones_like( tau_samples )\nplt.hist( tau_samples, bins = n_count_data, alpha = 1, \n label = r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth =1. )\n\nplt.legend(loc = \"upper left\");\nplt.ylim([0,.75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(\"days\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that the Bayesian methodology returns a *distribution*, hence we now have distributions to describe the unknown $\\lambda$'s and $\\tau$. What have we gained? Immediately we can see the uncertainty in our estimates: the more variance in the distribution, the less certain our posterior belief should be. We can also say what a plausible value for the parameters might be: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. What other observations can you make? Look at the data again, do these seem reasonable? The distributions of the two $\\\\lambda$s are positioned very differently, indicating that it's likely there was a change in the user's text-message behaviour.\n\nAlso notice that the posterior distributions for the $\\lambda$'s do not look like any exponential distributions, though we originally started modelling with exponential random variables. They are really not anything we recognize. But this is OK. This is one of the benefits of taking a computational point-of-view. If we had instead done this mathematically, we would have been stuck with a very analytically intractable (and messy) distribution. Via computations, we are agnostic to the tractability.\n\nOur analysis also returned a distribution for what $\\tau$ might be. Its posterior distribution looks a little different from the other two because it is a discrete random variable, hence it doesn't assign probabilities to internals. We can see that near day 45, there was a 50% chance the users behaviour changed. Had no change occurred, or the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many values are likely candidates for $\\tau$. On the contrary, it is very peaked. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say we can perform amazingly useful things. For now, let's end this chapter with one more example. We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le70$? Recall that the expected value of a Poisson is equal to its parameter $\\lambda$, then the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, we are calculating the following: Let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change hadn't occurred yet), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n\n\n\n___________________\n\n\n```\nfigsize( 12.5, 4)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\" (in the lambda1 \"regime\")\n # or \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed, \n # and therefore lambda (the poisson parameter) is the expected value of \"message count\"\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum() \n + lambda_2_samples[~ix].sum() ) /N\n\n \nplt.plot( range( n_count_data), expected_texts_per_day, lw =4, color = \"#E24A33\" )\nplt.xlim( 0, n_count_data )\nplt.xlabel( \"Day\" )\nplt.ylabel( \"Expected # text-messages\" )\nplt.title( \"Expected number of text-messages received\")\n#plt.ylim( 0, 35 )\nplt.bar( np.arange( len(count_data) ), count_data, color =\"#348ABD\", alpha = 0.5,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and the change was sudden rather then gradual (demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-2-text subscription, or a new relationship. (The 45th day corresponds to Christmas, and I moved away to Toronto the next month leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n#type your code here.\n```\n\n3\\. Looking at the posterior distribution graph of $\\tau$, why do you think there is a small number of posterior $\\tau$ samples near 0? `hint:` Look at the data again.\n\n4\\. What is the mean of $\\lambda_1$ **given** we know $\\tau$ is less than 45. That is, suppose we have new information as we know for certain that the change in behaviour occurred before day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part, just consider all instances where `tau_trace<45`. )\n\n\n```\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. .\n- [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "3b02b7538e13451798ae26aa1e64c721310da20c", "size": 404440, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_stars_repo_name": "elyase/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "1b587fe9652168553d25fdde7ba46a3d4e08ff0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-06-22T16:15:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-22T16:15:11.000Z", "max_issues_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_issues_repo_name": "elyase/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "1b587fe9652168553d25fdde7ba46a3d4e08ff0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Chapter1_Introduction.ipynb", "max_forks_repo_name": "elyase/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "1b587fe9652168553d25fdde7ba46a3d4e08ff0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 388.1381957774, "max_line_length": 111988, "alphanum_fraction": 0.9036618534, "converted": true, "num_tokens": 10812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.1828731843628664}} {"text": "## LMA source files\n\nMost of the older LMA source files have filenames like `LYLOUT_20211013_000000_0600.dat.gz`.\n\nNewer ones look like `WTLMA_2011_211013_102700_0060.dat.gz`. \n\nIn the newer files, `LYLOUT` (which was shared by all networks) is replaced with a network identifier, here `WTLMA_2011`, for the West Texas LMA that was established in 2011. All files end with `yyyymmdd_HHMMSS_duration.dat.gz`. The start time of the file is `yyyymmdd_HHMMSS`, and `duration` is the total length of the file in seconds.\n\nThey are compressed (`.gz`) plain text files - if you unzip them you can look at them with any text editor.\n\nRealtime data files are usually one minute in length, though sometiems they are also provided as bundles of hourly data. Postprocessed data files are almost always ten minutes long.\n\n### Headers of LMA postprocessed data.\n\nMain sections:\n- `Analysis program:` is the command used to process this data file.\n- The next few lines are information about the LMA network read from the `.loc` or `.gps` file provided to the processing program, and other information about the processing settings used.\n- The `Station information` table provides the location (here, truncated for privacy) and receive channel (Ch. 3 is 60-66 MHz) of each station.\n- The `Station data` table gives the data collection mode of the station. Here we see an 80 µs collection window was used, that there was an assumed 70 ns GPS timing error, the number and fraction of sources to which each station contributed, a power metric relative to the median (I think), and whether that station was active and used in processing this data file.\n- The `Station mask order` tells us which station corresponds to which bit in the station mask. We'll explain this below.\n- Finally, we have a description of the data format for the VHF sources (here, called events), with a descriptive name for each column and its the data format, and the total event count. These descriptions are not always correct, as you can see for the realtime data file!\n\n**Postprocssed data header** from 2021-06-27, 0200-0210 UTC - ten minutes of data.\nLightning Mapping Array analyzed data\nAnalysis program: /data/lma_realtime/new/lma_analysis-10.14.9R -d 20210627 -t 020000 -s 600 -g /data/lma_realtime/new/wt.gps -a -n 5 -o /data/rtlma/processed_data/2021/Jun/27/ -q -x 5.00 -y 500.00\nAnalysis program version: 10.14.9R\nFile created: Thu Sep 16 03:34:46 2021\nData start time: 06/27/21 02:00:00\nNumber of seconds analyzed: 600\nLocation: WTLMA_2011\nCoordinate center (lat,lon,alt): 33.6069680 -101.8226250 984.00\nCoordinate frame: cartesian\nMaximum diameter of LMA (km): 79.743\nMaximum light-time across LMA (ns): 266047\nNumber of stations: 13\nNumber of active stations: 8\nActive stations: G W B N L P H X\nMinimum number of stations per solution: 5\nMaximum reduced chi-squared: 5.00\nMaximum number of chi-squared iterations: 20\nStation information: id, name, lat(d), lon(d), alt(m), delay(ns), board_rev, rec_ch\nSta_info: E Estac 33.6 -101.8 984.00 26 3 3\nSta_info: G Idalo 33.7 -101.6 992.00 26 3 3\nSta_info: W Llano 33.4 -101.7 956.85 26 3 3\nSta_info: B Biggin 33.7 -102.0 1007.59 26 3 3\nSta_info: N Newdl 33.7 -101.8 998.45 26 3 3\nSta_info: O Reese 33.5 -102.0 1018.00 26 3 3\nSta_info: R Roosevelt 33.5 -101.6 960.00 26 3 3\nSta_info: L Loren 33.6 -101.5 956.00 26 3 3\nSta_info: P Peter 33.8 -101.6 978.00 26 3 3\nSta_info: A Abern 33.9 -101.8 1022.23 26 3 3\nSta_info: H Wolff 33.4 -102.0 993.51 26 3 3\nSta_info: X Level 33.5 -102.3 1049.01 26 3 3\nSta_info: T ReeseTower 33.6 -102.0 1019.00 26 3 3\nStation data: id, name, win(us), dec_win(us), data_ver, rms_error(ns), sources, %,

, active\nSta_data: E Estac 0 0 70 0 0.0 0.00 NA\nSta_data: G Idalo 80 12 70 515907 88.0 0.75 A\nSta_data: W Llano 80 12 70 463829 79.2 0.03 A\nSta_data: B Biggin 80 12 70 474843 81.0 1.77 A\nSta_data: N Newdl 80 12 70 523811 89.4 0.85 A\nSta_data: O Reese 0 0 70 0 0.0 0.00 NA\nSta_data: R Roosevelt 0 0 70 0 0.0 0.00 NA\nSta_data: L Loren 80 12 70 320263 54.7 2.33 A\nSta_data: P Peter 80 12 70 497376 84.9 2.21 A\nSta_data: A Abern 0 0 70 0 0.0 0.00 NA\nSta_data: H Wolff 80 12 70 390070 66.6 0.66 A\nSta_data: X Level 80 12 70 43247 7.4 0.00 A\nSta_data: T ReeseTower 0 0 70 0 0.0 0.00 NA\nMetric file version: 4\nStation mask order: TXHAPLRONBWGE\nData: time (UT sec of day), lat, lon, alt(m), reduced chi^2, P(dBW), mask\nData format: 15.9f 12.8f 13.8f 9.2f 6.2f 5.1f 6x\nNumber of events: 585980\n*** data ***\n 7195.563227082 14.42079200 -168.11020038 1471087992.23 230.40 100.1 0x011e\n 7198.034285095 1.85676802 -166.66390846 616695433.21 336.78 93.6 0x050e\n 7199.534259710 73.62739777 92.92428877 154306312.18 85.80 82.2 0x019c\n 7199.999970628 33.57516955 -101.85614830 13424.97 101.96 -1.4 0x0516\n 7200.000295524 34.00685344 -101.79561170 6858.94 0.17 11.0 0x009e\n 7200.000769921 33.98258103 -101.79108175 6512.81 0.31 7.9 0x0c16\n 7200.000901130 34.00999875 -101.81978857 7349.40 0.37 7.6 0x011e\n 7200.001103478 34.19873867 -101.73348211 27670.57 3.82 14.7 0x050e\n 7200.001213632 33.77065089 -102.07323840 9979.92 2.27 14.5 0x0598\n 7200.001485129 34.05024204 -101.78250330 13454.71 0.29 15.1 0x058c\n**Realtime data header** from 2021-10-13 0400-0401 UTC - one minute of data.\nLightning Mapping Array analyzed data\nAnalysis program: /data/lma_realtime/new/lma_analysis-10.14.9RT -g /data/lma_realtime/new/wt.gps -n 5 -o /data/lma_realtime/out -x 5.00\nAnalysis program version: 10.14.9RT\nFile created: Wed Oct 13 04:01:02 2021\nData start time: 10/13/21 04:00:00\nNumber of seconds analyzed: 60\nLocation: WTLMA_2011\nCoordinate center (lat,lon,alt): 33.6069680 -101.8226250 984.00\nCoordinate frame: cartesian\nMaximum diameter of LMA (km): 79.743\nMaximum light-time across LMA (ns): 266047\nNumber of stations: 12\nNumber of active stations: 7\nActive stations: W B N P A H X\nMinimum number of stations per solution: 5\nMaximum reduced chi-squared: 5.00\nMaximum number of chi-squared iterations: 20\nStation information: id, name, lat(d), lon(d), alt(m), delay(ns), board_rev, rec_ch\nSta_info: E Estac 33.6 -101.8 984.00 26 3 3\nSta_info: G Idalo 33.7 -101.6 992.00 26 3 3\nSta_info: W Llano 33.4 -101.7 956.85 26 3 3\nSta_info: B Biggin 33.7 -102.0 1007.59 26 3 3\nSta_info: N Newdl 33.7 -101.8 998.45 26 3 3\nSta_info: O Reese 33.5 -102.0 1018.00 26 3 3\nSta_info: R Roosevelt 33.5 -101.6 960.00 26 3 3\nSta_info: L Loren 33.6 -101.5 956.00 26 3 3\nSta_info: P Peter 33.8 -101.6 978.00 26 3 3\nSta_info: A Abern 33.9 -101.8 1022.23 26 3 3\nSta_info: H Wolff 33.4 -102.0 993.51 26 3 3\nSta_info: X Level 33.5 -102.3 1049.01 26 3 3\nStation data: id, name, win(us), dec_win(us), data_ver, rms_error(ns), sources, %,

, active\nSta_data: E Estac 0 0 70 0 0.0 0.00 NA\nSta_data: G Idalo 80 12 70 74 7400.0 1.07 NA\nSta_data: W Llano 80 12 70 2 200.0 0.34 A\nSta_data: B Biggin 80 12 70 3 300.0 0.22 A\nSta_data: N Newdl 80 12 70 76 7600.0 0.35 A\nSta_data: O Reese 0 0 70 0 0.0 0.00 NA\nSta_data: R Roosevelt 0 0 70 0 0.0 0.00 NA\nSta_data: L Loren 0 0 70 0 0.0 0.00 NA\nSta_data: P Peter 80 12 70 77 7700.0 1.58 A\nSta_data: A Abern 80 12 70 76 7600.0 3.99 A\nSta_data: H Wolff 80 12 70 76 7600.0 0.31 A\nSta_data: X Level 80 12 70 2 200.0 0.09 A\nMetric file version: 4\nStation mask order: XHAPLRONBWGE\nData: time (UT sec of day), lat, lon, alt(m), reduced chi^2, P(dBW), mask\nData format: 15.9f 12.8f 13.8f 9.2f 6.2f 5.1f 5x\nNumber of events: 1\n*** data ***\n14402.294258784 33.68914553 -102.11318221 32320.04 3.96 -8.2 0xf08\n14406.018238618 33.66219201 -102.05494124 37331.34 0.67 5.0 0x718\n14429.547782698 34.24702550 -101.74849670 7692.76 0.13 10.6 0x712\n14429.556551814 34.24626004 -101.75420033 7793.37 0.02 21.9 0x712\n14429.558081952 34.24751434 -101.75747915 8816.25 2.03 10.2 0x712\n\nHow do we tell the difference between the file types? Look at the `lma_analysis` line: the program version ending in `RT` indicates realtime, while the postprocessing ends in `R`, for reasons I don't understand. The path to the output filename location (`-o`) also gives a clue about where the data file was first saved, which hopefully was on a somewhat informative path on your data processing server.\n\n## Interpreting the event data columns\n\nThe time and location columns in the data file above are self-explanatory, though it is good to know they are with respect to the WGS84 ellipsoid. The event power, in dBW at the source, is also provided.\n\nThe station mask column is a [hexadecimal number](https://en.wikipedia.org/wiki/Hexadecimal), where each digit after the `0x` represents a value between 0-15. Let's look at how to interpret `0xf08`.\n\n\n```python\n# Convert hexadecimal (base-16) to a decimal (base-10) integer\nhexmask = '0xf09'\nnumber = int(hexmask, 16)\nprint(\"Hex {0} is decimal integer {1}\".format(hexmask, number))\n\n# Print the integer as a decimal, and as binary, with leading zeroes and 16 bits (016b).\nprint(\"Integer {0} is binary {0:016b}\".format(number))\n```\n\n Hex 0xf09 is decimal integer 3849\n Integer 3849 is binary 0000111100001001\n\n\nWe see that `0xf09` converts to this binary string corresponding to the station location order from the header:\n\n```\n0000111100001001\n XHAPLRONBWGE\n```\n\nso stations X, H, A, P, B, and E contributed to this solution. If we sum the bits in the station mask, we find the number of contributing stations was 6. This is above the minimum required for a solution (5). \n\n**The number of contributing staitons is an important parameter that lets us control the amount of noise in our science analyses.**\n\nFor a fullly operational network a minimum of 6 contributing stations is a good starting number, but values of 5 or 7 can be useful.\n\nNoise is primarily caused by false correlations produced by random, local VHF sources at several stations that happen to correlate with each other. More stations in a network means a greater chance of false corelation, so larger LMA networks tend to need a minimum higher station count to keep noise in check.\n\n**The other primary quality control parameter is the reduced `chi^2` value.** The processing requires that all sources have $\\chi^2 < 5$.\n\n\n(If you see values larger than 5 in a data file, a second pass has been used to restore some very high power sources that might be a special class of discharge called \"narrow bipolar events\". The post-processed header above includes `-y 500.00`, so a second pass was done for that data file, up to $\\chi^2 < 500$.)\n\n$\\chi^2$ is a measure of the goodness of fit of the solutions. Specififally, it is the [$\\chi^2$ statistic](https://mathworld.wolfram.com/Chi-SquaredDistribution.html) of the normalized squared timing errors. Using the notation of [Thomas et al. (2004)](10.1029/2004JD004549), eq. A2,\n\n\\begin{equation}\n\\Large\\chi^2 = \\Large\\sum_{i=1}^N \\frac{(t_i^\\mathrm{obs} - t_i^\\mathrm{fit})^2}{\\Delta t_\\mathrm{rms}^2},\n\\end{equation}\n\nwhere $t_i^\\mathrm{obs}$ is the observed arrival time of the source at each station, and $t_i^\\mathrm{fit}$ the predicted arrival time of each source (traveling at the speed of light) at each station. $\\Delta t_\\mathrm{rms}$ is the expected (root mean square) normalized timing error assumed in the processing, i.e., 70 ns for the two data files above.\n\nThe actual value in the file is the **reduced $\\chi^2$**, \n\n\\begin{equation}\n\\chi_{\\nu}^2 = \\frac{\\chi^2}{N - 4}\n\\end{equation}\n\nwhich has been further normalized by the number of degrees of freedom $\\nu = N - 4$, where $N$ is the number of contributing stations and 4 is the number of retrieved paramters for the source location $(x,y,z,t)$.\n\nUsing these equations, we can convert the data file's $\\chi_{\\nu}^2$ value into the actual timing errors, and/or calculate the true \\chi_{\\nu}^2 for the actual GPS timing noise, which is typically less than 70 ns. \n\n([Thomas et al. (2004)](10.1029/2004JD004549) shows how the timing errors relate to range, azimuth, and elevation errors, and how to determine $\\Delta t_\\mathrm{rms}$ for any data file.)\n\nPractically speaking, we usualy don't calculate the corrected $\\chi_\\nu^2$ unless we care about converting the timing errors into location errors. Instead, we simply use the file's $\\chi_{\\nu}^2$ and reduce our maximum chi-sq until we're satisfied we've removed most noise.\n\nWhen [working with data from some day for the first time](./FirstLMAplots.ipynb), it is useful to experiment with a minimum number of stations of 5, 6, and 7, and reduced chi-squared values of 1.0 and 5.0, since the best setting for that day depends on the number of active stations and the radio noise in the ambient environment on that day. You will observe that there is a tradeoff between removing noise and removing detail in lightning channels. The balance point is a judgment call, but should always be reported in publications using LMA data.\n\nBefore we [move on to actually trying to filter and plot some data ourselves](./FirstLMAplots.ipynb), let's use the cell below to look at the header of a file we'll work with later today. You might need to adjust `n_lines` to see more of the header.\n\n\n```python\nn_lines = 100\nfilename = '/data/Houston/realtime-tracer/LYLOUT_200524_210000_0600.dat.gz'\n\nimport gzip\nwith gzip.open(filename, 'rt', encoding='utf8') as lmafile:\n header_lines = [lmafile.readline() for i in range(n_lines)]\nfor line in header_lines:\n print(line, end='')\n```\n\n New Mexico Tech Lightning Mapping Array - analyzed data\n Analysis program: /data1/hlma_tamu/lma_analysis -d 20200524 -t 210000 -s 600 -l /data1/hlma_tamu/hstnA.loc -o /data1/hlma_data/processed/080us_data/0600/nomdl//2020/05/200524 -x 5.00 -y 500.00\n Analysis program version: 10.11.7R\n File created: Mon May 25 00:23:04 2020\n Data start time: 05/24/20 21:00:00\n Number of seconds analyzed: 600\n Location: HSTN LMA 2012\n Coordinate center (lat,lon,alt): 29.7600000 -95.3700000 -200.00\n Coordinate frame: cartesian\n Maximum diameter of LMA (km): 205.007\n Maximum light-time across LMA (ns): 683965\n Number of stations: 13\n Number of active stations: 7\n Active stations: A B I J K L M\n Minimum number of stations per solution: 6\n Maximum reduced chi-squared: 5.00\n Maximum number of chi-squared iterations: 20\n Station information: id, name, lat(d), lon(d), alt(m), delay(ns), board_rev, rec_ch\n Sta_info: A Cy-Fair ISD 29.9392583 -95.6464869 24.31 45 3 3\n Sta_info: B Williams Airport 30.1574342 -95.3209639 19.35 45 3 3\n Sta_info: C Johnson Space Center 29.5670202 -95.0984633 -2.93 45 3 3\n Sta_info: D Sugarland 29.6196458 -95.6576139 3.06 45 3 3\n Sta_info: E TAMU 1 30.6461624 -96.2979071 75.82 45 3 2\n Sta_info: F Houston SW Airport 29.5050035 -95.4759368 6.89 45 3 3\n Sta_info: G Addicks 29.7679573 -95.6452786 15.23 45 3 3\n Sta_info: H Houston Raceway 29.7913451 -94.8828558 -5.65 45 3 3\n Sta_info: I TAMU 2 30.6462000 -96.2979000 69.02 45 3 3\n Sta_info: J Lone Star College 30.0019908 -95.3840236 6.76 45 3 3\n Sta_info: K Alvin 29.4407042 -95.2733397 -5.24 45 3 3\n Sta_info: L May 30.0581250 -95.0614192 1.39 45 3 3\n Sta_info: M Galveston 29.3159000 -94.8220000 -2.99 45 3 3\n Station data: id, name, win(us), dec_win(us), data_ver, rms_error(ns), sources, %,

, active\n Sta_data: A Cy-Fair ISD 80 10 70 118447 99.3 2.07 A\n Sta_data: B Williams Airport 80 10 70 118433 99.3 2.29 A\n Sta_data: C Johnson Space Center 0 0 70 0 0.0 0.00 NA\n Sta_data: D Sugarland 0 0 70 0 0.0 0.00 NA\n Sta_data: E TAMU 1 0 0 70 0 0.0 0.00 NA\n Sta_data: F Houston SW Airport 0 0 70 0 0.0 0.00 NA\n Sta_data: G Addicks 0 0 70 0 0.0 0.00 NA\n Sta_data: H Houston Raceway 0 0 70 0 0.0 0.00 NA\n Sta_data: I TAMU 2 80 10 70 118061 99.0 0.08 A\n Sta_data: J Lone Star College 80 10 70 118294 99.2 0.30 A\n Sta_data: K Alvin 80 10 70 117986 98.9 0.78 A\n Sta_data: L May 80 10 70 110846 92.9 2.13 A\n Sta_data: M Galveston 80 10 70 14116 11.8 76.22 A\n Metric file version: 4\n Station mask order: MLKJIHGFEDCBA\n Data: time (UT sec of day), lat, lon, alt(m), reduced chi^2, P(dBW), mask\n Data format: 15.9f 12.8f 13.8f 9.2f 6.2f 5.1f 6x\n Number of events: 119290\n *** data ***\n 75591.978874007 79.70932923 -114.48340374 2406689178.91 35.72 101.7 0x1703\n 75599.998664584 27.39779476 -95.62892200 719865.17 166.77 30.3 0x1703\n 75600.000080056 30.51557585 -95.56277434 9948.14 149.81 12.0 0x0f03\n 75600.000367376 30.88925893 -95.30721212 11633.74 314.10 23.7 0x0f03\n 75600.000434196 30.05190243 -95.79910575 33037.95 3.70 8.5 0x1703\n 75600.001399791 30.82301277 -95.47161575 6411.17 0.14 16.4 0x0f03\n 75600.001552058 30.78454293 -95.30852548 10396.54 0.14 15.8 0x0f03\n 75600.001748370 30.71511685 -95.64580199 742.16 154.69 14.1 0x0f03\n 75600.002204027 30.49020057 -95.51679219 7324.00 4.76 10.5 0x0f03\n 75600.003609747 29.91724127 -95.17903970 13222.17 52.06 4.0 0x0f03\n 75600.003954346 30.78271680 -95.30956792 10765.62 0.08 19.2 0x0f03\n 75600.004041880 30.82071122 -95.29332307 7274.72 5.15 16.8 0x0f03\n 75600.005431992 29.93996735 -96.30764088 13947.72 160.35 20.9 0x0f03\n 75600.005882026 30.48913577 -95.51506485 8307.87 0.02 12.6 0x0f03\n 75600.006463519 15.49003757 -98.65527996 3505839.60 135.01 45.3 0x1b03\n 75600.008114909 30.23230682 -95.69142961 37035.82 299.60 10.0 0x1703\n 75600.008193535 29.96158364 -96.39246591 17331.83 118.72 22.7 0x0f03\n 75600.009615840 30.51119988 -95.58075716 8579.13 0.10 19.4 0x0f03\n 75600.009695027 30.51200176 -95.58121006 8126.00 0.37 11.1 0x0f03\n 75600.010946557 29.95254677 -96.39864220 10102.00 0.14 21.4 0x0f03\n 75600.012435197 30.77913572 -95.33296927 6726.34 0.09 12.3 0x0f03\n 75600.012628815 30.49530217 -95.50177713 7867.36 18.08 10.5 0x0f03\n 75600.013701366 30.51012676 -95.58451940 8477.86 0.18 14.7 0x0f03\n 75600.013852652 29.91800885 -100.46163291 182057.84 145.30 24.7 0x1703\n 75600.014096699 30.51108028 -95.58329245 8955.30 2.49 12.3 0x0f03\n 75600.014530316 29.95579657 -96.39807772 13360.71 2.83 24.0 0x0f03\n 75600.014733671 30.48676064 -95.51246549 7696.23 4.16 14.9 0x0f03\n 75600.014849400 30.48388991 -95.51274343 8495.17 16.11 14.0 0x0f03\n 75600.015756768 30.49476360 -95.50253507 8708.50 0.16 17.5 0x0f03\n 75600.016415183 30.48380113 -95.51426141 8363.24 6.96 10.3 0x0f03\n 75600.017501534 30.00980639 -96.34460249 14136.79 352.52 9.1 0x1703\n 75600.017761630 30.51341646 -95.58546891 8601.91 0.39 13.3 0x0f03\n 75600.020262247 41.55817024 -85.67353157 1975337.34 99.43 35.3 0x1703\n 75600.020376910 29.96574530 -96.49436881 5043.18 180.18 21.5 0x0f03\n 75600.020400010 30.46027205 -95.49275367 8241.02 148.68 19.1 0x0f03\n 75600.020565633 29.95470580 -96.39262310 11576.86 0.08 21.8 0x0f03\n 75600.021161321 30.49254865 -95.50437149 8834.57 0.60 9.4 0x0f03\n 75600.021637111 30.49300121 -95.50419577 8783.24 18.30 15.9 0x0f03\n 75600.021929961 30.53010627 -95.52304394 5435.84 0.09 11.0 0x0f03\n 75600.024595259 29.97064879 -95.26012393 43638.48 170.37 6.6 0x1703\n 75600.025243989 30.72271316 -95.39656696 7015.05 1.56 9.3 0x0f03\n 75600.027739195 30.48166319 -95.50737724 7735.94 5.17 17.5 0x0f03\n 75600.028721960 30.51964581 -95.58446590 8605.89 0.33 15.0 0x0f03\n 75600.031864116 30.47716015 -95.50704139 8200.90 0.77 11.2 0x0f03\n 75600.032694056 30.52458915 -95.58517353 8541.51 0.02 11.6 0x0f03\n 75600.032812068 30.86507046 -95.31458893 5228.54 47.90 15.6 0x0f03\n 75600.033274952 29.62603808 -95.57112845 29373.25 179.70 4.0 0x1703\n 75600.033612308 30.07638288 -96.45165599 491638.76 177.56 19.8 0x1703\n 75600.034853640 30.52693153 -95.58457205 8436.68 0.15 9.3 0x0f03\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "517f77011b497e35c8a5c030a68ac7527b209593", "size": 26726, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "TRACER-2021/LMAsourcefiles.ipynb", "max_stars_repo_name": "deeplycloudy/lmaworkshop", "max_stars_repo_head_hexsha": "e0ffa56f8ce3d025c103973d58c524d856d7fdac", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TRACER-2021/LMAsourcefiles.ipynb", "max_issues_repo_name": "deeplycloudy/lmaworkshop", "max_issues_repo_head_hexsha": "e0ffa56f8ce3d025c103973d58c524d856d7fdac", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TRACER-2021/LMAsourcefiles.ipynb", "max_forks_repo_name": "deeplycloudy/lmaworkshop", "max_forks_repo_head_hexsha": "e0ffa56f8ce3d025c103973d58c524d856d7fdac", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-27T07:42:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T07:42:25.000Z", "avg_line_length": 59.1283185841, "max_line_length": 556, "alphanum_fraction": 0.6021477213, "converted": true, "num_tokens": 8565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1820559275385114}} {"text": "------------------------------------------------------------------------- \n\n 中学生の数学をパイソンで学ぶ(中1病) \n\n coding: utf-8 \n published at: 2022-01-08 \n\n MITlicense (c) 2022 DomZeroYunx(asdjod13ff@pm.me)\n 転載の際は必ず著作表示を保持してください。\n\n------------------------------------------------------------------------- \n \nみんな大好きゲームを作りたい。けどついでにPythonで数学も進めてみよう! \nまずは中学1年生からだよ。変数にまで日本語を使っているからわかりやすく書いていきたいですがなかなかうまくいきません。\n\n[]: # Language: markdown \n[]: # Path: cyu1.ipynb \n \n\n# 正の数と負の数をコンソールで表示してみる\n\n\n```python\n# こいつらみんな整数 \n原点 = [0] # 0は自然数ではないけど整数\n自然数 = [1,2,3,4,5,6,7,8,9] # 自然数であり整数\n自然数にプラスがついても同じ = [+1,+2,+3,+4,+5,+6,+7,+8,+9] # プラスがついても同じ\n負数 = [-1,-2,-3,-4,-5,-6,-7,-8,-9] # 自然数ではない\n\nprint(\"整数を表示\" + str(負数) + str(原点) + str(自然数)) ## 整数を表示\nprint(\"自然数を表示します\" + str(自然数))## 自然数を表示\nprint(\"自然数にプラスがついても同じを表示します\" + str(自然数にプラスがついても同じ)) ## 自然数にプラスがついても同じ\nprint(\"負数を表示します\" + str(負数)) ## 負数を表示\n```\n\n 整数を表示[-1, -2, -3, -4, -5, -6, -7, -8, -9][0][1, 2, 3, 4, 5, 6, 7, 8, 9]\n 自然数を表示します[1, 2, 3, 4, 5, 6, 7, 8, 9]\n 自然数にプラスがついても同じを表示します[1, 2, 3, 4, 5, 6, 7, 8, 9]\n 負数を表示します[-1, -2, -3, -4, -5, -6, -7, -8, -9]\n\n\n## 正の数と負の数を図にしてみる\n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# --- 正の数負の数の基礎 -----------------------------------------------------\n\n原点 = [0] # 0は自然数ではないけど整数\n自然数 = [1,2,3,4,5,6,7,8,9,10] # 自然数であり整数(+がついても同じ)\n負数 = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] # 自然数ではない\n\n# ---------------------------------------------------------------------------\n\n# ラベル用\nfig, ax = plt.subplots() # 初期化\nax2 = ax.twinx() # 右側に表示\n\n# 邪魔なラベルを消す\nax.get_xaxis().set_visible(False) # x軸\nplt.xticks([]) # x軸のラベル\nax2.get_yaxis().set_visible(False) # y軸\nplt.yticks([]) # y軸のラベル\n\n# グラフの設定\nplt.title(\"整数を表示\",fontname=\"MS Gothic\") # タイトル\nax.set_ylabel('負数 < 整数 > 正数',fontname=\"MS Gothic\") # 日本語で読みやすく \nax.plot(負数, color='red', linestyle='-', linewidth=0, label='負数') # 負数のグラフは非表示にする\nax.plot(原点, color='blue', linestyle='-', linewidth=2, label='原点') # 原点\nax.plot(自然数, color='green', linestyle='-', linewidth=0, label='自然数') # 自然数のグラフは非表示にする\nplt.quiver(0,10,scale=1,color='green') # 棒グラフを表示するためベクトル\nplt.quiver(0,-10,scale=1,color='red') # 棒グラフを表示するためベクトル\nax.set_ylim(-10,10) # y軸の小数点は切り捨てる\nax.set_yticks(np.arange(-10,10,1)) # 1刻みで表示\nax.grid(True) # グリッドを表示\nax.plot(0, 0, 'o', color='blue', markersize=10) # 原点を表示\nax.text(0.3, -0.3, '原点: 0 (自然じゃない)',fontname=\"MS Gothic\", fontsize=16) # 原点のラベル\nax.text(1, -4, '負数: -1,-2,-3,-4,-5,-6,-7,-8,-9',fontname=\"MS Gothic\", fontsize=16) # 負数のラベル\nax.text(1, 5, '正数: 1,2,3,4,5,6,7,8,9',fontname=\"MS Gothic\", fontsize=16) # 自然数のラベル\nax.text(1, 3, '正数(上と同じ): +1,+2,+3,+4,+5,+6,+7,+8,+9',fontname=\"MS Gothic\", fontsize=12) # +がついても同じのラベル\nplt.show() # グラフを表示\n\n```\n\n \n0より大きい数は正の数です。 \n0より小さい数は負の数です。 \n0は正でも負でもない数です。 \n \n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# plot全体の高さを指定\nfig = plt.figure(figsize=(10,1)) #figsize=(width,height)\n\nx = np.arange(-9,10,1)\ny = np.zeros(len(x))#y軸は直線表示のみ\nplt.yticks([])#y軸のラベルを非表示\nplt.title(\"正の数、負の数\",fontname=\"MS Gothic\")#タイトルを設定\nplt.xticks(np.arange(-9,10,1))#小数点以下は切り捨て整数のみ表示\nplt.grid(True)\n\nx = np.arange(-9,1,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='red',linestyle='-',linewidth=3)\nplt.text(-8.5, 0, '負の数',fontname=\"MS Gothic\", fontsize=16)\n\nx = np.arange(0,10,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='green',linestyle='-',linewidth=3)\nplt.text(8.5, 0, '正の数',fontname=\"MS Gothic\", fontsize=16)\n\nx = np.arange(0,0.1,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='blue',linestyle='-',linewidth=3)\nplt.text(-0.5, 0, '原点',fontname=\"MS Gothic\", fontsize=18)\n\nplt.show()\n\n```\n\n赤い線が負の数です、0を含まない-1から-9の部分が赤くなりました。 \n原点と呼ばれる0はちょうど正と負の間です。0は正でも負でもありません。 \n緑の部分は0より大きい数です。これは正の数です。 \n \n- 原点より右が正の数\n- 原点より左が負の数\n- 原点の0は正でも負でもありません。\n \nそして右に行くほど正の数が大きくなります。それはおこずかいが0円から9円のおこづかいになるようなものです。 \nそして左に行くほど負の数が大きくなります。それはおこずかいの9円が0円になるようなものです。酷い話ですね \n\n## 原点からの計算方法(絶対値の計算方法)\n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# plot全体の高さを指定\nfig = plt.figure(figsize=(10,1)) #figsize=(width,height)\n\n\n# 0から4までの自然数を表示\nx = np.arange(0.1,4,0.1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='green',linestyle='-',linewidth=6)\nplt.text(0, 0, '原点0から数える',fontname=\"MS Gothic\", fontsize=16)\n\n\nx = np.arange(-9,9,1)\ny = np.zeros(len(x))\n\nx = np.arange(-9,10,1)\ny = np.zeros(len(x))#y軸は直線表示のみ\nplt.yticks([])#y軸のラベルを非表示\nplt.title(\"原点からの計算で絶対値の距離を求める\",fontname=\"MS Gothic\")#タイトルを設定\nplt.xticks(np.arange(-9,10,1))#小数点以下は切り捨て整数のみ表示\nplt.grid(True)\n\n\n\nplt.show()\n```\n\n0は原点と覚えましたね。\n\n> 0からの距離からの決めた数までの距離をを 絶対値 と呼びます。 \nこの図の場合には0から数えて 4 ですね?つまり 絶対値は 4 になります \n \n### 次の図で絶対値がいくつになるか考えてみてください。 \n\n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# plot全体の高さを指定\nfig = plt.figure(figsize=(10,1)) #figsize=(width,height)\n\n\n# 0から4までの自然数を表示\nx = np.arange(0.1,6,0.1) #グラフの軸合わせで適当に加算\ny = np.zeros(len(x))\nplt.plot(x,y,color='green',linestyle='-',linewidth=6)\nplt.text(0, 0, '原点0から数える',fontname=\"MS Gothic\", fontsize=16)\n\n\nx = np.arange(-9,9,1)\ny = np.zeros(len(x))\n\nx = np.arange(-9,10,1)\ny = np.zeros(len(x))#y軸は直線表示のみ\nplt.yticks([])#y軸のラベルを非表示\nplt.title(\"原点からの計算で絶対値の距離を求める クイズ\",fontname=\"MS Gothic\")#タイトルを設定\nplt.xticks(np.arange(-9,10,1))#小数点以下は切り捨て整数のみ表示\nplt.grid(True)\n\nplt.show()\n```\n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# plot全体の高さを指定\nfig = plt.figure(figsize=(10,1)) #figsize=(width,height)\n\n\n# 0から4までの自然数を表示\nx = np.arange(-2.9,0.1,0.1) #グラフの軸合わせで適当に加算\ny = np.zeros(len(x))\nplt.plot(x,y,color='green',linestyle='-',linewidth=6)\nplt.text(0, 0, '原点0から数える',fontname=\"MS Gothic\", fontsize=16)\n\n\nx = np.arange(-9,9,1)\ny = np.zeros(len(x))\n\nx = np.arange(-9,10,1)\ny = np.zeros(len(x))#y軸は直線表示のみ\nplt.yticks([])#y軸のラベルを非表示\nplt.title(\"原点からの計算で絶対値の距離を求める クイズ\",fontname=\"MS Gothic\")#タイトルを設定\nplt.xticks(np.arange(-9,10,1))#小数点以下は切り捨て整数のみ表示\nplt.grid(True)\n\nplt.show()\n```\n\n \n> さてこの場合はどうなるでしょうか?絶対値0からマイナス方向に向かっています。
\n答えは3です。絶対値から数えるだけでプラスもマイナスも関係ありません。\n絶対値からの距離です。\n\n家から南に進んで50メートル、北に進んでも50メートルは50メートルです。\n\n原点は家だとすると考え方は簡単です。わかりにくいものは何かにたとえて考えます。\n\n# 初歩的パイソンで数学を学ぶ 正の数と負の数\n\n\n```python\n# 分数を考える\nA = 1/2 # Aは2分の1 分母が後ろにある\n\n# 表示してみる\nprint(A)\n\n```\n\n 0.5\n\n\n>Aという変数に2分1をを入れてみました。\n>print(A)というのは()で囲んだAの内容を表示しています。\n>これはAの値が2分1です。\n>print(A) \n\nそして答えが0.5になりました!\n\n\n\n```python\nfrom numpy.random import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n%matplotlib inline\n\n# plot全体の高さを指定\nfig = plt.figure(figsize=(10,1)) #figsize=(width,height)\n\nx = np.arange(-9,10,1)\ny = np.zeros(len(x))#y軸は直線表示のみ\nplt.yticks([])#y軸のラベルを非表示\nplt.title(\"これらは整数\",fontname=\"MS Gothic\")#タイトルを設定\nplt.xticks(np.arange(-9,10,1))#小数点以下は切り捨て整数のみ表示\nplt.grid(True)\n\nx = np.arange(-9,1,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='red',linestyle='-',linewidth=3)\nplt.text(-8.5, 0, '負の数',fontname=\"MS Gothic\", fontsize=16)\n\nx = np.arange(0,10,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='green',linestyle='-',linewidth=3)\nplt.text(8.5, 0, '正の数',fontname=\"MS Gothic\", fontsize=16)\n\nx = np.arange(0,0.1,1)\ny = np.zeros(len(x))\nplt.plot(x,y,color='blue',linestyle='-',linewidth=3)\nplt.text(-0.5, 0, '原点',fontname=\"MS Gothic\", fontsize=18)\n\nplt.show()\n```\n\n0は整数です \nそして0より0.5は大きい数です。つまり正の数になります。 \n0より大きければ正 \n0より小さければ負です。 \n \n簡単パイソンの言語で答えを表示することができます。\n\n```\nA = 1/2\nprint(A)\n```\nAという変数で分数を計算できます。\nA=はAに入れるという意味です。(実際はメモリがうんたらという話になりますが今は覚える必要はありません)\n数学とゲームを作る環境において変数を使うのは簡単です。\n\n答えは2分の1が 0.5 になりました。 \n図と照らし合わせて0.5の位置を指さしてみましょう。 \n0と1の間にありますね? \n \n緑色の部分は0より大きい数です。これは正の数です。 \nこれはしつこいくらい言っています。なぜなら紛らわしいからです。 \n\n$\n\\begin{align}\n \\frac{4}{8}\n \\frac{5}{6}\n \\frac{2}{4}\n\\end{align}\n$\n\nここに3個の分数があります。これらも正の数です。分数に符号がついていなければ正の数です。\n\n\n\n```python\n# 分数を考える\nA = 4/8 # Aは4分の8 分母が後ろにある\nB = 5/6 # Bは5分の6 分母が後ろにある\nC = 2/4 # Cは2分の4 分母が後ろにある\n\n# 表示してみる\nprint(A)\nprint(B)\nprint(C)\n```\n\n 0.5\n 0.8333333333333334\n 0.5\n\n\n答えが出ました。0より大きいので正の数です。 \nこのようにパイソンで計算することができれば数学の構造がわかりやすくなります。\n\n少し気になる人もいると思うのでこんなのやってみます。\n#\n$\n\\begin{align*}\nA = \\frac{-1}{3}\n\\end{align*}\n$\n\n\n```python\nA = -1/3 # Aは-1分の3 分母が後ろにある\nprint(A)\n```\n\n -0.3333333333333333\n\n\nマイナスがつきました、つまり負の数です。\n\n# 大なり小なりで比較をします\n\n < > こんな形の記号です\n > 1は2より小さい、2は1より大きい \n 1 < 2 \n > 2は6より小さい、6は2より大きい\n 6 > 2\nパックマンの口が開いてる方が大きいということです。\n\n\\begin{align*}\n \\frac{0.5}{3}\n \n \\frac{5}{6}\n \n \\frac{3}{5}\n \n 0.7 を比較します\n\\end{align*}\n\n<>記号で比較します。\n\nそのためにまず 通分 という面倒なことをします。(本当に面倒)\nだがしかしパイソンがあるから面倒なことはないでしょう(きっとです)\n\n\n\n\n\n```python\n# とにかく変数に入れてみましょう\nA = 0.5/3 # 分母が後ろにあるのは覚えていますか?\nB = 5/6\nC = 3/5\nD = 0.7\n\n# 表示してみる\nprint(\"Aの答え\", A)\nprint(\"Bの答え\", B)\nprint(\"Cの答え\", C)\nprint(\"Dの答え\", D)\n\n```\n\n Aの答え 0.16666666666666666\n Bの答え 0.8333333333333334\n Cの答え 0.6\n Dの答え 0.7\n\n\nコードを書き換えて大なり小なりで比較してみましょう。\n\n\n```python\n# とにかく変数に入れてみましょう\nA = 0.5/3 # 分母が後ろにあるのは覚えていますか?\nB = 5/6\nC = 3/5\nD = 0.7\n\n# 表示してみる\nprint(\"Aの答え\", A)\nprint(\"Bの答え\", B)\nprint(\"Cの答え\", C)\nprint(\"Dの答え\", D)\n\n# AとBとCとDをリストにしてみましょう\n\n数 = [A,B,C,D]\n\nprint(\"リストに入れた数を表示\",数)\n数.sort(reverse=True) # 数を絶対値(0)から離れてる順番でソートします\nprint(\"これできちんと並びました\",数)\n\n\nprint(\"----------------------------------------------------\")\n# これではわかりずらいのでABCDの形を維持したまま\n# A:中身の答えのように辞書形式の配列にしてみましょう。\n\nA = 0.5/3\nB = 5/6\nC = 3/5\nD = 0.7\n\n辞書配列A = {'エリエール':A}\n辞書配列B = {'スコッティ':B}\n辞書配列C = {'マントヒヒ':C}\n辞書配列D = {'ポテトサラダ':D}\n\n# 辞書配列から数値のみを取り出してみましょう\nprint(\"辞書配列Aの中身\",辞書配列A['エリエール'])\nprint(\"辞書配列Bの中身\",辞書配列B['スコッティ'])\nprint(\"辞書配列Cの中身\",辞書配列C['マントヒヒ'])\nprint(\"辞書配列Dの中身\",辞書配列D['ポテトサラダ'])\n\n```\n\n Aの答え 0.16666666666666666\n Bの答え 0.8333333333333334\n Cの答え 0.6\n Dの答え 0.7\n リストに入れた数を表示 [0.16666666666666666, 0.8333333333333334, 0.6, 0.7]\n これできちんと並びました [0.8333333333333334, 0.7, 0.6, 0.16666666666666666]\n ----------------------------------------------------\n 辞書配列Aの中身 0.16666666666666666\n 辞書配列Bの中身 0.8333333333333334\n 辞書配列Cの中身 0.6\n 辞書配列Dの中身 0.7\n\n\n辞書配列というのは キーワード:中身 のような考え方がわかりやすい覚え方です。 \n\nエリエールの中にAをいれてみました。 \nA = 0.5/3 エリエール \nB = 5/6 スコッティ \nC = 3/5 マントヒヒ \nD = 0.7 ポテトサラダ \n\n紛らわしいです\n名前とペアで付けられるので、いろいろな用途に使えます。 \n意味不明な変数名をつけるとわかりずらくなるのでやめましょう\n\n\n```python\n# 辞書配列をリスト配列にしてみましょう\n辞書配列A = {'エリエール':A}\n辞書配列B = {'スコッティ':B}\n辞書配列C = {'マントヒヒ':C}\n辞書配列D = {'ポテトサラダ':D}\n\n# 辞書配列の中身を表示\nprint(\"辞書配列Aの中身\",辞書配列A)\nprint(\"辞書配列Bの中身\",辞書配列B)\nprint(\"辞書配列Cの中身\",辞書配列C)\nprint(\"辞書配列Dの中身\",辞書配列D)\n\n# 辞書配列から取り出した数値のみを取り出す\n辞書配列数値 = [辞書配列A['エリエール'],辞書配列B['スコッティ'],辞書配列C['マントヒヒ'],辞書配列D['ポテトサラダ']]\n辞書配列数値 = list(辞書配列数値) # リストに変換\n\n# 表示してみる\nprint(\"リストにした数値のみを表示してみる\")\nprint(\"辞書配列数値\",辞書配列数値)\n\n# sortで降順に並び替え\n辞書配列数値.sort(reverse=True)\n\n# 表示してみる\nprint(\"リストにした数値のみを表示してみる(ソート済み)\")\nprint(\"辞書配列数値\",辞書配列数値)\n\n```\n\n 辞書配列Aの中身 {'エリエール': 0.16666666666666666}\n 辞書配列Bの中身 {'スコッティ': 0.8333333333333334}\n 辞書配列Cの中身 {'マントヒヒ': 0.6}\n 辞書配列Dの中身 {'ポテトサラダ': 0.7}\n リストにした数値のみを表示してみる\n 辞書配列数値 [0.16666666666666666, 0.8333333333333334, 0.6, 0.7]\n リストにした数値のみを表示してみる(ソート済み)\n 辞書配列数値 [0.8333333333333334, 0.7, 0.6, 0.16666666666666666]\n\n\nここで使った関数は sort そして list さらに辞書であるDictionaryも使用しました。 \n紛らわしい変数名がいかに混乱を生むかが体験できました。 \n\n\n```python\nA = 0.5/3\nB = 5/6\nC = 3/5\nD = 0.7\n\n# AやBは小数点があるので、一桁で表示してみましょう\nA = round(A,1)\nB = round(B,1)\nprint(\"Aの答え\",A)\nprint(\"Bの答え\",B)\n\n辞書 = [{'式':'0.5/3', '解':A},{'式':'5/6', '解':B},{'式':'3/5', '解':C},{'式':'0.7', '解':D}]\n並び変えた辞書 = sorted(辞書, key=lambda x:x['解'])\nprint(並び変えた辞書)\n```\n\n Aの答え 0.2\n Bの答え 0.8\n [{'式': '0.5/3', '解': 0.2}, {'式': '3/5', '解': 0.6}, {'式': '0.7', '解': 0.7}, {'式': '5/6', '解': 0.8}]\n\n\n> これでほぼ元の形でみることができます。\n\n\\begin{align*}\n \\frac{0.5}{3}\n \n \\frac{5}{6}\n \n \\frac{3}{5}\n \n 0.7 を比較します\n\n\\end{align*}\n\n結果が示す通りの順番で0の原点から順に並んでいます。\n0.2 < 0.6 < 0.7 < 0.8\n\n\\begin{align*}\n \\frac{0.5}{3} < \\frac{5}{6} < \\frac{3}{5} < 0.7\n\\end{align*}\n\n大なり小なりです、パックマンの口が開いている方が大きいということです。\n", "meta": {"hexsha": "5bfe235c9ba9c80850f3d099a399127ef26ff582", "size": 103526, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chu1.ipynb", "max_stars_repo_name": "narukisosu/chu1sugaku", "max_stars_repo_head_hexsha": "6a8a03db3094b644a9b23b5a3211c15543b26bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chu1.ipynb", "max_issues_repo_name": "narukisosu/chu1sugaku", "max_issues_repo_head_hexsha": "6a8a03db3094b644a9b23b5a3211c15543b26bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chu1.ipynb", "max_forks_repo_name": "narukisosu/chu1sugaku", "max_forks_repo_head_hexsha": "6a8a03db3094b644a9b23b5a3211c15543b26bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 113.8899889989, "max_line_length": 26666, "alphanum_fraction": 0.857243591, "converted": true, "num_tokens": 7104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18088619075629198}} {"text": "```python\n\"\"\"\nIPython Notebook v4.0 para python 2.7\nLibrerías adicionales: numpy, matplotlib\nContenido bajo licencia CC-BY 4.0. Código bajo licencia MIT. (c) Sebastian Flores.\n\"\"\"\n\n# Configuracion para recargar módulos y librerías \n%reload_ext autoreload\n%autoreload 2\n\nfrom IPython.core.display import HTML\n\nHTML(open(\"style/mat281.css\", \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n

\n\n\n
\n




\n# MAT281\n## Aplicaciones de la Matemática en la Ingeniería\n\n### Sebastián Flores\n\nhttps://www.github.com/sebastiandres/mat281\n\n\n## Clase anterior\n\n* Teorema $\\Pi$.\n\n## ¿Qué contenido aprenderemos hoy?\n\n* Adimensionalización de ecuaciones.\n* Diseño de experimentos.\n\n## ¿Porqué aprenderemos ese contenido?\n\n* **Adimensionalización de ecuaciones.**\n\nPermite estudiar las ecuaciones con el mínimo número de parámetros.\n\n* **Diseño de experimentos.**\n\nPermite simular un experimento con el menor número de ejecuciones.\n\n## Contradicción.\n¿Han notado la contradicción de las últimas clases?\n\n* Clase $i$: Las dimensiones son lo más importante de un problema.\n\n* Clase $i+1$: Es mejor hacer un análisis en adimensional.\n\n## Motivación\nSi el teorema $\\Pi$ es tan bueno, ¿para qué necesitamos ecuaciones?\n\n* **Teorema de $\\Pi$ o Teorema Buckingham**: Conocimiento indicativo de cómo se podrían relacionar las variables.\n* **Adimensionalización de ecuaciones**: Conocimiento funcional de cómo se relacionan las variables y la importancia relativa de cada término.\n\nEn términos de información:\n\nEcuaciones dimensionales $>>$ Ecuaciones Adimensionales $>>$ Teorema $\\Pi$\n\n#### Análisis dimensional\n## Ejemplo\nConsideremos el ejemplo clásico de una barra de longitud infinita, de sección transversal $A$ y que se encuentra inicialmente a una temperatura $\\tau_a$.\n\nEn $t = 0$ la barra se calienta en $x = 0$ a una temperatura $\\tau_b$. \n\n¿Cómo evoluciona la temperatura en las distintas posiciones de la barra, para los tiempos posteriores? \n\nEn particular, ¿cuál es la temperatura de la barra en el tiempo $t$ en la posición $x$?\n\n¿Qué nos dice el Teorema $\\Pi$? ¿Qué nos dice el análisis dimensional de las ecuaciones?\n\n#### Ejemplo\n## Teorema Pi\n¿Que variables hay? Hint: son 9.\n\n* $t$: tiempo. Dimensión. [$T$].\n* $x$: posición. Dimensión [$L$]. \n* Temperaturas. Dimensión [$\\tau$]\n * $\\tau_a$: Temperatura inicial de la barra.\n * $\\tau_b$: Temperatura en extremo.\n * $\\tau$: Temperatura en $x$ y $t$.\n* $A$: sección transversal. Dimensión $[L^2]$.\n* $\\rho$: densidad. Dimensión $\\Big[\\frac{M}{L^3}\\Big]$.\n* $c_p$: calor específico. Dimensión $\\Big[\\frac{L^2}{T^2 \\theta}\\Big]$.\n* $k$: conductividad térmica. Dimensión $\\Big[\\frac{M L }{T^3 \\theta}\\Big]$.\n\n# Densidad: $\\rho$\n* Relaciona masa con volumen.\n* Unidades: $$\\frac{kg}{m^3}$$\n* Dimensión: $$\\Big[\\frac{M}{L^3}\\Big]$$\n* Ejemplos: \n * Cobre: 8960 $\\frac{kg}{m^3}$\n * Hierro: 7870 $\\frac{kg}{m^3}$\n * Oro: 19320 $\\frac{kg}{m^3}$\n\n# Calor Específico: $c_p$\n* Relaciona energía proporcionada con aumento de temperatura.\n* El calor específico es cantidad de calor (energía) a suministrar a 1 kg de material para aumentar la temperatura en 1 grado Kelvin.\n* Unidades: $$\\frac{J}{kg K}$$\n* Dimensión: $$\\Big[\\frac{L^2}{T^2 \\theta}\\Big]$$\n* Ejemplos: \n * Cobre: 385 $\\frac{J}{kg K}$\n * Hierro: 450 $\\frac{J}{kg K}$\n * Oro: 129 $\\frac{J}{kg K}$\n\n## Conductividad térmica: $k$\n* Se relaciona con el flujo de calor dentro un material.\n* La conductividad térmica es una propiedad del material, e indica cuanto calor (energía) se transmitiría en un segundo entre 2 caras de un metro cuadrado separadas a un metro de distancia. \n* Unidades: $$\\frac{W}{m K}$$\n* Dimensión: $$\\Big[\\frac{M L}{T^3 \\theta}\\Big]$$\n* Ejemplos: \n * Cobre: 380 $\\frac{W}{m K}$\n * Hierro: 80 $\\frac{W}{m K}$\n * Oro: 308 $\\frac{W}{m K}$\n\n#### Ejemplo\n## Teorema Pi\nHay $9$ variables y $4$ dimensiones, por lo que el problema requiere definir $9-4=5$ parámetros adimensionales.\n\nSi elegimos como base: $\\tau_a$, $x$, $t$, $c_p$.\n\n$$\\Pi_{\\tau} = \\Phi(\\Pi_{\\tau_b} , \\Pi_{A} , \\Pi_{\\rho} , \\Pi_{k} )$$\nNo es particularmente prometedor. Sabemos que existe una relación, pero no sabemos cómo obtenerla.\n\n¿Es lo mejor que podemos hacer?\n\n¿Cómo mejora la situación si sabemos cómo se relacionan físicamente las variables?\n\n#### Ejemplo\n## Modelamiento físico\n\nSabemos que para este problema aplican las siguientes ecuaciones, donde $q$ es el flujo de calor:\n\n* Conservación de calor:\n$$ \n\\rho c_p \\frac{\\partial \\tau}{\\partial t} = - \\frac{\\partial q}{\\partial x}\n$$\n* Ley de Fourier:\n$$\nq = -k \\frac{\\partial \\tau}{\\partial x}$$\nOBS: No hay referencia a la sección transversal.\n\n#### Ejemplo\n## Modelamiento físico\nSi suponemos $k$ constante obtenemos:\n$$\n\\frac{\\partial \\tau}{\\partial t} = \\frac{k}{\\rho c_p} \\frac{\\partial^2 \\tau}{\\partial x^2}$$\n\nLa constante $D =\\frac{k}{\\rho c_p}$ se llama **constante de difusividad** y tiene dimensión $\\Big[ \\frac{L^2}{T} \\Big]$.\n\nNormalmente los problemas hablan directamente de $D$ y olvidan las aproximaciones realizadas.\n\nEjemplos: \n * Cobre: $1.10 \\cdot 10^{-4}$ $\\frac{m^2}{s}$\n * Hierro: $2.25 \\cdot 10^{-5}$ $\\frac{m^2}{s}$\n * Oro: $1.23 \\cdot 10^{-4}$ $\\frac{m^2}{s}$\n\n\n#### Ejemplo\n## Sistema dimensional\nHemos obtenido\n$$\n\\begin{align}\n\\frac{\\partial \\tau}{\\partial t} &= \\Big( \\frac{k}{\\rho c_p} \\Big) \\frac{\\partial^2 \\tau}{\\partial x^2}\\\\\n\\tau(x=0, t=0)&= \\tau_b \\\\\n\\tau(x\\neq 0, t=0)&= \\tau_a \\\\\n\\end{align}\n$$\nCon ello tenemos que $\\tau= \\Phi(x, t, \\frac{k}{\\rho c_p}, \\tau_a, \\tau_b)$. \n* Hemos obtenido que la temperatura depende de 2 variables y 3 parámetros.\n* Esto es similar en complejidad a lo que se obtenida con el teorema $\\Pi$.\n* Simplificación no ha utilizado las dimensiones, sino la física del problema.\n\n#### Ejemplo\n## Adimensionalización\nAdimensionalicemos las ***variables*** de la ecuación anterior. \n\nPartamos por las variables dependientes:\n$$\n\\begin{align}\n\\tau &= \\tau_0 \\ \\hat{\\tau} \\\\\nx &= x_0 \\ \\hat{x} \\\\\nt &= t_0 \\ \\hat{t}\n\\end{align}\n$$\nDonde todavía no decidimos que utilizaremos como factores de escalamiento $\\tau_0$, $x_0$ y $t_0$.\n\n\n#### Ejemplo\n## Adimensionalización de derivadas\nPara la derivada temporal\n$$\n\\begin{align}\n\\frac{\\partial \\tau}{\\partial t} & = \\frac{\\partial \\tau_0 \\hat{\\tau}}{\\partial t} = \\tau_0 \\frac{\\partial \\hat{\\tau}}{\\partial t} \\\\\n& = \\tau_0 \\frac{\\partial \\hat{\\tau}}{t_0 \\partial \\hat{t}}\n= \\frac{\\tau_0}{t_0} \\frac{\\partial \\hat{\\tau}}{\\partial \\hat{t}}\n\\end{align}\n$$\ny similarmente para la segunda derivada espacial\n$$\n\\begin{align}\n\\frac{\\partial^2 \\tau}{\\partial x^2} &= \n\\frac{\\partial}{\\partial x} \\frac{\\partial \\tau}{\\partial x} = \n\\frac{1}{x_0} \\frac{\\partial}{\\partial \\hat{x}} \\frac{\\tau_0}{x_0} \\frac{\\partial \\hat{\\tau}}{\\partial \\hat{x}} \\\\\n&= \\frac{\\tau_0}{x_0^2} \\frac{\\partial}{\\partial \\hat{x}} \\frac{\\partial \\hat{\\tau}}{\\partial \\hat{x}} = \\frac{\\tau_0}{x_0^2} \\frac{\\partial^2 \\hat{\\tau}}{\\partial \\hat{x}^2} \n\\end{align}\n$$\n\n\n#### Ejemplo\n## Adimensionalización de ecuación\nUtilizando lo anterior\n$$\n\\frac{\\partial \\tau}{\\partial t} = \\frac{k}{\\rho c_p} \\frac{\\partial^2 \\tau}{\\partial x^2}\n$$\nse convierte en\n$$\n\\frac{\\tau_0}{t_0} \\frac{\\partial \\hat{\\tau}}{\\partial \\hat{t}} = \\frac{k}{\\rho c_p} \\frac{\\tau_0}{x_0^2} \\frac{\\partial^2 \\hat{\\tau}}{\\partial \\hat{x}^2}\n$$\nes decir\n$$\n\\frac{\\partial \\hat{\\tau}}{\\partial \\hat{t}} = \\Big( \\frac{k}{\\rho c_p} \\frac{t_0}{x_0^2} \\Big) \\frac{\\partial^2 \\hat{\\tau}}{\\partial \\hat{x}^2}\n$$\n\n#### Ejemplo\n## Adimensionalización de Condiciones Iniciales\n$$ \n\\begin{align}\n\\tau(x=0, t=0)&= \\tau_b \\\\\n\\tau(x\\neq 0, t=0)&= \\tau_a \\\\\n\\end{align}\n$$\nse convierte en\n$$\n\\begin{align}\n\\hat{\\tau}(\\hat{x}=0, \\hat{t}=0)&= \\frac{\\tau_b}{\\tau_0} \\\\\n\\hat{\\tau}(\\hat{x}\\neq 0, \\hat{t}=0)&= \\frac{\\tau_a}{\\tau_0} \\\\\n\\end{align}\n$$\n\n#### Ejemplo\n## Sistema adimensional final\nHemos obtenido\n$$\n\\begin{align}\n\\frac{\\partial \\hat{\\tau}}{\\partial \\hat{t}} &= \\Big( \\frac{k}{\\rho c_p} \\frac{t_0}{x_0^2} \\Big) \\frac{\\partial^2 \\hat{\\tau}}{\\partial \\hat{x}^2}\\\\\n\\hat{\\tau}(\\hat{x}=0, \\hat{t}=0)&= \\frac{\\tau_b}{\\tau_0} \\\\\n\\hat{\\tau}(\\hat{x}\\neq 0, \\hat{t}=0)&= \\frac{\\tau_a}{\\tau_0} \\\\\n\\end{align}\n$$\nEs posible y conveniente elegir la adimensionalización de modo que \n$$\\begin{align}\n\\frac{k}{\\rho c_p} \\frac{t_0}{x_0^2} &= 1 \\\\ \n\\frac{\\tau_a}{\\tau_0} &=1\n\\end{align}$$\n\n#### Ejemplo\n## Elección de adimensionalización\nSi sabemos que se simulará hasta un tiempo máximo $t_{max}$, es conveniente tomar:\n$$\n\\begin{align}\nt_0 &= t_{max} \\\\\nx_0 &= \\sqrt{\\frac{k}{\\rho c_p} t_{max}}\\\\\n\\tau_0 &= \\tau_a\n\\end{align}\n$$\n\n#### Ejemplo\n## Elección de adimensionalización\nSi sabemos que se estudiará un punto $x_L$ en específico, es conveniente tomar:\n$$\n\\begin{align}\nt_0 &= \\frac{\\rho c_p}{k} x_0^2\\\\\nx_0 &= x_L\\\\\n\\tau_0 &= \\tau_a\n\\end{align}\n$$\n\n#### Ejemplo\n## Sistema adimensional final\nIndependiente de la adimensionalización, se obtiene finalmente el sistema:\n$$\n\\begin{align}\n\\frac{\\partial \\hat{\\tau}}{\\partial \\hat{t}} &= \\frac{\\partial^2 \\hat{\\tau}}{\\partial \\hat{x}^2}\\\\\n\\hat{\\tau}(\\hat{x}=0, \\hat{t}=0)&= \\frac{\\tau_b}{\\tau_a} \\\\\n\\hat{\\tau}(\\hat{x}\\neq 0, \\hat{t}=0)&= 1\n\\end{align}\n$$\n\n#### Ejemplo\n## Balance\nLa temperatura adimensional depende de 2 variables $\\hat{x}$ y $\\hat{t}$ y un parámetro adimensional $\\frac{\\tau_b}{\\tau_a}$, esto es,\n\n$$\\hat{\\tau}= \\Phi\\Big(\\hat{x}, \\hat{t}, \\frac{\\tau_b}{\\tau_a}\\Big)$$\n\nUn problema que inicialmente dependía de 6 parámetros físicos ($A$, $c_p$, $k$, $\\rho$, $\\tau_a$, $\\tau_b$), puede ser resuelto solamente por 1 parámetro ($\\tau_b/\\tau_a$) y luego escalado correctamente.\n\n## Balance\nNo sólo hemos resuelto para un menor número de parámetros, sino que la ecuación anterior indica que basta resolver para una combinación $\\tau_b/\\tau_a$ específica y que luego podemos recuperar la temperatura dimensional para cualquier valor $c_p$ y $k$ simplemente escalando correctamente.\n\nEsto es, si resolvemos y conocemos\n$$\\hat{\\tau}= \\Phi\\Big(\\hat{x}, \\hat{t}, \\tau_b/\\tau_a\\Big)$$\npodemos ahora calcular la versión dimensional utilizando\n$$\\tau = t_0 \\hat{\\tau}= t_0 \\Phi\\Big(x/x_0, t/t_0, \\tau_b/\\tau_a\\Big)$$\nLos coeficientes $\\rho$, $c_p$ y $k$ se encuentran \"camuflados\" en las definiciones de $x_0$ y $t_0$.\n\n## Moralejas\n* Una ecuación contiene mucha más información que el teorema de Buckingham.\n* Adimensionalizar ecuaciones permite chequear factibilidad, reducir a términos elementales y estudiar casos límites.\n* Teorema de Buckingham es útil para realizar estimaciones de comportamiento global, pero no para comportamiento local.\n\n## Aplicación\nSupongamos que para un experimento queremos saber cuánto tiempo se demora en llegar al 50% de la temperatura deseada, estando a 0.50 metro del origen, en funcion de los parámetros. \n* ¿Cómo varía el resultado en función de las temperaturas $\\tau_a$ (inicial) y $\\tau_b$ (fija)?\n* ¿Cómo varía el resultado en función de los coeficientes $\\rho$, $c_p$ y $k$?\n\n#### Aplicación\n## Simulación con parametros dimensionales\nPara resolver el problema con parametros dimensionales ($\\tau_a$, $\\tau_b$, $\\rho$, $c_p$, $k$) deberíamos realizar simulaciones en un gran espacio.\n\nSi discretizamos el espacio de cada parámetro en 10 valores, se requerirían $10^5$ simulaciones.\nSi cada simulacion toma $1$ segundo, se requerirán $10^5$ segundos, es decir, $27$ horas.\n\nSi discretizamos el espacio de cada parámetro en 20 valores, se requerirían $20^5$ simulaciones.\nSi cada simulacion toma $1$ segundo, se requerirán $20^5$ segundos, es decir, $36$ días.\n\n\n#### Aplicación\n## Simulación con parametros adimensionales\n\nPara resolver el problema con parametros dimensionales deberíamos realizar simulaciones simplemente discretizando el parámetro $\\tau_b/\\tau_a$.\n\n\n#### Aplicación\n## Simulación con parametros adimensionales\nTomemos el caso del cobre:\n* Pensemos que $\\tau_a$ y $\\tau_b$ se mueven en el rango 273-373 grados Kelvin.\n* Eso significa que $\\frac{273}{373} \\leq \\frac{\\tau_b}{\\tau_a} \\leq \\frac{373}{273}$.\n* Recordemos que deseamos llegar al 50% de la temperatura $\\tau_b$, estando a 0.50 metro del origen. \n\n## Solución\nEn python y magia HTML\n\n\n```python\nfrom IPython.display import HTML\nfrom mat281_code import heat\nHTML(heat.run())\n```\n\n\n\n\n
$\\tau_b / \\tau_a$ [1]$\\hat{t}^*$ [1]
0.7319034852550.38064993368
0.8023920275930.38064993368
0.8728805699320.38064993368
0.943369112270.38064993368
1.013857654610.38064993368
1.084346196950.38064993368
1.154834739290.38064993368
1.225323281620.38064993368
1.295811823960.38064993368
1.36630036630.38064993368
\n\n\n\n## Interpretación\n\nEl tiempo (adimensional) que le toma llegar a la mitad de la temperatura es independiente de las temperaturas elegidas.\n\nVolviendo a parametros dimensionales, tenemos:\n$$ t^* = t_0 \\hat{t}^* = \\frac{x_0^2}{D} \\ \\ \\hat{t}^* = \\frac{\\rho c_p}{k} x_0^2 \\ \\ \\hat{t}^*$$\n\n* Si el material fuera oro, el tiempo requerido hubiese sido $t^* = \\frac{0.5^2}{1.23E-4} \\times 0.381 \\approx 774.4$ segundos (13 minutos).\n* Si el material fuera cobre, el tiempo requerido hubiese sido $t^* = \\frac{0.5^2}{1.10E-4} \\times 0.381 \\approx 865.5$ segundos (15 minutos).\n* Si el material fuera fierro, el tiempo requerido hubiese sido $t^* = \\frac{0.5^2}{2.25E-5} \\times 0.381 \\approx 4329.5$ segundos (72 minutos).\n\n\n## Discusión del problema\n¿Que tan real es el problema?\n* ¿Barra infinita?\n* ¿Fijar temperatura en $x=0$ a una temperatura fija?\n", "meta": {"hexsha": "d196e4542a41a2b71cb3fc7d580e584fac82d0a8", "size": 24421, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase03-EcuacionesAdimensionales/EcuacionesAdimensionales.ipynb", "max_stars_repo_name": "sebastiandres/mat281", "max_stars_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-12T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-12T19:23:25.000Z", "max_issues_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase03-EcuacionesAdimensionales/EcuacionesAdimensionales.ipynb", "max_issues_repo_name": "sebastiandres/mat281", "max_issues_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase03-EcuacionesAdimensionales/EcuacionesAdimensionales.ipynb", "max_forks_repo_name": "sebastiandres/mat281", "max_forks_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-06T15:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-06T15:01:54.000Z", "avg_line_length": 30.7182389937, "max_line_length": 622, "alphanum_fraction": 0.5251627697, "converted": true, "num_tokens": 5059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1801961899336904}} {"text": "\n# Oscillations\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA and Department of Physics, University of Oslo, Norway \n\n **[Scott Pratt](https://pa.msu.edu/profile/pratts/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA \n\n **[Carl Schmidt](https://pa.msu.edu/profile/schmidt/)**, Department of Physics and Astronomy, Michigan State University, USA\n\nDate: **Feb 10, 2020**\n\nCopyright 1999-2020, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n\n\n## Harmonic Oscillator\n\nThe harmonic oscillator is omnipresent in physics. Although you may think \nof this as being related to springs, it, or an equivalent\nmathematical representation, appears in just about any problem where a\nmode is sitting near its potential energy minimum. At that point,\n$\\partial_x V(x)=0$, and the first non-zero term (aside from a\nconstant) in the potential energy is that of a harmonic oscillator. In\na solid, sound modes (phonons) are built on a picture of coupled\nharmonic oscillators, and in relativistic field theory the fundamental\ninteractions are also built on coupled oscillators positioned\ninfinitesimally close to one another in space. The phenomena of a\nresonance of an oscillator driven at a fixed frequency plays out\nrepeatedly in atomic, nuclear and high-energy physics, when quantum\nmechanically the evolution of a state oscillates according to\n$e^{-iEt}$ and exciting discrete quantum states has very similar\nmathematics as exciting discrete states of an oscillator.\n\nThe potential energy for a single particle as a function of its position $x$ can be written as a Taylor expansion about some point $x_0$\n\n\n
\n\n$$\n\\begin{equation}\nV(x)=V(x_0)+(x-x_0)\\left.\\partial_xV(x)\\right|_{x_0}+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0}\n+\\frac{1}{3!}\\left.\\partial_x^3V(x)\\right|_{x_0}+\\cdots\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nIf the position $x_0$ is at the minimum of the resonance, the first two non-zero terms of the potential are\n\n$$\n\\begin{eqnarray}\nV(x)&\\approx& V(x_0)+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\n&=&V(x_0)+\\frac{1}{2}k(x-x_0)^2,~~~~k\\equiv \\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\nF&=&-\\partial_xV(x)=-k(x-x_0).\n\\end{eqnarray}\n$$\n\nPut into Newton's 2nd law (assuming $x_0=0$),\n\n$$\n\\begin{eqnarray}\nm\\ddot{x}&=&-kx,\\\\\nx&=&A\\cos(\\omega_0 t-\\phi),~~~\\omega_0=\\sqrt{k/m}.\n\\end{eqnarray}\n$$\n\nHere $A$ and $\\phi$ are arbitrary. Equivalently, one could have\nwritten this as $A\\cos(\\omega_0 t)+B\\sin(\\omega_0 t)$, or as the real\npart of $Ae^{i\\omega_0 t}$. In this last case $A$ could be an\narbitrary complex constant. Thus, there are 2 arbitrary constants\n(either $A$ and $B$ or $A$ and $\\phi$, or the real and imaginary part\nof one complex constant. This is the expectation for a second order\ndifferential equation, and also agrees with the physical expectation\nthat if you know a particle's initial velocity and position you should\nbe able to define its future motion, and that those two arbitrary\nconditions should translate to two arbitrary constants.\n\nA key feature of harmonic motion is that the system repeats itself\nafter a time $T=1/f$, where $f$ is the frequency, and $\\omega=2\\pi f$\nis the angular frequency. The period of the motion is independent of\nthe amplitude. However, this independence is only exact when one can\nneglect higher terms of the potential, $x^3, x^4\\cdots$. Once can\nneglect these terms for sufficiently small amplitudes, and for larger\namplitudes the motion is no longer purely sinusoidal, and even though\nthe motion repeats itself, the time for repeating the motion is no\nlonger independent of the amplitude.\n\nOne can also calculate the velocity and the kinetic energy as a function of time,\n\n$$\n\\begin{eqnarray}\n\\dot{x}&=&-\\omega_0A\\sin(\\omega_0 t-\\phi),\\\\\n\\nonumber\nK&=&\\frac{1}{2}m\\dot{x}^2=\\frac{m\\omega_0^2A^2}{2}\\sin^2(\\omega_0t-\\phi),\\\\\n\\nonumber\n&=&\\frac{k}{2}A^2\\sin^2(\\omega_0t-\\phi).\n\\end{eqnarray}\n$$\n\nThe total energy is then\n\n\n
\n\n$$\n\\begin{equation}\nE=K+V=\\frac{1}{2}m\\dot{x}^2+\\frac{1}{2}kx^2=\\frac{1}{2}kA^2.\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nThe total energy then goes as the square of the amplitude.\n\n\nA pendulum is an example of a harmonic oscillator. By expanding the\nkinetic and potential energies for small angles find the frequency for\na pendulum of length $L$ with all the mass $m$ centered at the end by\nwriting the eq.s of motion in the form of a harmonic oscillator.\n\nThe potential energy and kinetic energies are (for $x$ being the displacement)\n\n$$\n\\begin{eqnarray*}\nV&=&mgL(1-\\cos\\theta)\\approx mgL\\frac{x^2}{2L^2},\\\\\nK&=&\\frac{1}{2}mL^2\\dot{\\theta}^2\\approx \\frac{m}{2}\\dot{x}^2.\n\\end{eqnarray*}\n$$\n\nFor small $x$ Newton's 2nd law becomes\n\n$$\nm\\ddot{x}=-\\frac{mg}{L}x,\n$$\n\nand the spring constant would appear to be $k=mg/L$, which makes the\nfrequency equal to $\\omega_0=\\sqrt{g/L}$. Note that the frequency is\nindependent of the mass.\n\n\n## Damped Oscillators\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{4}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([4](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto6} \\tag{7}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto7} \\tag{8}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $e{rt}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{9}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{10}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\n## Our Sliding Block Code\nHere we study first the case without additional friction term and scale our equation\nin terms of a dimensionless time $\\tau$.\n\nLet us remind ourselves about the differential equation we want to solve (the general case with damping due to friction)\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0.\n$$\n\nWe divide by $m$ and introduce $\\omega_0^2=\\sqrt{k/m}$ and obtain\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =0.\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$ (check\nthat the dimensionality is correct) and rewrite our equation as\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0^2}\\frac{dx}{d\\tau}+x(\\tau) =0,\n$$\n\nwhich gives us\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{k}\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nWe then define $\\gamma = b/2k$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nThis is the equation we will code below. The first version employs the Euler-Cromer method.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 30 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as compact 2-dimensional arrays\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.5\n# Start integrating using Euler's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]\n # update velocity, time and position using Euler's forward method\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"BlockEulerCromer\")\nplt.show()\n```\n\nWhen setting up the value of $\\gamma$ we see that for $\\gamma=0$ we get the simple oscillatory motion with no damping.\nChoosing $\\gamma < 1/2$ leads to the classical underdamped case with oscillatory motion, but where the motion comes to an end.\n\nChoosing $\\gamma =1/2$ leads to what normally is called critical damping and $\\gamma> 1/2$ leads to critical overdamping.\nTry it out and try also to change the initial position and velocity.\n\n## Sinusoidally Driven Oscillators\n\nHere, we consider the force\n\n\n
\n\n$$\n\\begin{equation}\nF=-kx-b\\dot{x}+F_0\\cos\\omega t,\n\\label{_auto8} \\tag{11}\n\\end{equation}\n$$\n\nwhich leads to the differential equation\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:drivenosc} \\tag{12}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=(F_0/m)\\cos\\omega t.\n\\end{equation}\n$$\n\nConsider a single solution with no arbitrary constants, which we will\ncall a {\\it particular solution}, $x_p(t)$. It should be emphasized\nthat this is {\\bf A} particular solution, because there exists an\ninfinite number of such solutions because the general solution should\nhave two arbitrary constants. Now consider solutions to the same\nequation without the driving term, which include two arbitrary\nconstants. These are called either {\\it homogenous solutions} or {\\it\ncomplementary solutions}, and were given in the previous section,\ne.g. Eq. ([9](#eq:homogsolution)) for the underdamped case. The\nhomogenous solution already incorporates the two arbitrary constants,\nso any sum of a homogenous solution and a particular solution will\nrepresent the {\\it general solution} of the equation. The general\nsolution incorporates the two arbitrary constants $A$ and $B$ to\naccommodate the two initial conditions. One could have picked a\ndifferent particular solution, i.e. the original particular solution\nplus any homogenous solution with the arbitrary constants $A_p$ and\n$B_p$ chosen at will. When one adds in the homogenous solution, which\nhas adjustable constants with arbitrary constants $A'$ and $B'$, to\nthe new particular solution, one can get the same general solution by\nsimply adjusting the new constants such that $A'+A_p=A$ and\n$B'+B_p=B$. Thus, the choice of $A_p$ and $B_p$ are irrelevant, and\nwhen choosing the particular solution it is best to make the simplest\nchoice possible.\n\nTo find a particular solution, one first guesses at the form,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{13}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$\n\nand rewrite the differential equation as\n\n\n
\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto9} \\tag{14}\n\\end{equation}\n$$\n\nOne can now use angle addition formulas to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$\n\nBoth the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$\n\nAfter dividing by $\\cos\\delta$, the lower expression leads to\n\n\n
\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto10} \\tag{15}\n\\end{equation}\n$$\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos\\^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,\n\n$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$\n\nInserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{16}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$\n\nFor a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n## Alternative Derivation for Driven Oscillators\n\nHere, we derive the same expressions as in Equations ([13](#eq:partform)) and ([16](#eq:Ddrive)) but express the driving forces as\n\n$$\n\\begin{eqnarray}\nF(t)&=&F_0e^{i\\omega t},\n\\end{eqnarray}\n$$\n\nrather than as $F_0\\cos\\omega t$. The real part of $F$ is the same as before. For the differential equation,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:compdrive} \\tag{17}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x&=&\\frac{F_0}{m}e^{i\\omega t},\n\\end{eqnarray}\n$$\n\none can treat $x(t)$ as an imaginary function. Because the operations\n$d^2/dt^2$ and $d/dt$ are real and thus do not mix the real and\nimaginary parts of $x(t)$, Eq. ([17](#eq:compdrive)) is effectively 2\nequations. Because $e^{\\omega t}=\\cos\\omega t+i\\sin\\omega t$, the real\npart of the solution for $x(t)$ gives the solution for a driving force\n$F_0\\cos\\omega t$, and the imaginary part of $x$ corresponds to the\ncase where the driving force is $F_0\\sin\\omega t$. It is rather easy\nto solve for the complex $x$ in this case, and by taking the real part\nof the solution, one finds the answer for the $\\cos\\omega t$ driving\nforce.\n\nWe assume a simple form for the particular solution\n\n\n
\n\n$$\n\\begin{equation}\nx_p=De^{i\\omega t},\n\\label{_auto11} \\tag{18}\n\\end{equation}\n$$\n\nwhere $D$ is a complex constant.\n\nFrom Eq. ([17](#eq:compdrive)) one inserts the form for $x_p$ above to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2+2i\\beta\\omega+\\omega_0^2\\right\\}e^{i\\omega t}=(F_0/m)e^{i\\omega t},\\\\\n\\nonumber\nD=\\frac{F_0/m}{(\\omega_0^2-\\omega^2)+2i\\beta\\omega}.\n\\end{eqnarray}\n$$\n\nThe norm and phase for $D=|D|e^{-i\\delta}$ can be read by inspection,\n\n\n
\n\n$$\n\\begin{equation}\n|D|=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}},~~~~\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto12} \\tag{19}\n\\end{equation}\n$$\n\nThis is the same expression for $\\delta$ as before. One then finds $x_p(t)$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven1} \\tag{20}\nx_p(t)&=&\\Re\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\cos(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nThis is the same answer as before.\nIf one wished to solve for the case where $F(t)= F_0\\sin\\omega t$, the imaginary part of the solution would work\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven2} \\tag{21}\nx_p(t)&=&\\Im\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nConsider the damped and driven harmonic oscillator worked out above. Given $F_0, m,\\beta$ and $\\omega_0$, solve for the complete solution $x(t)$ for the case where $F=F_0\\sin\\omega t$ with initial conditions $x(t=0)=0$ and $v(t=0)=0$. Assume the underdamped case.\n\nThe general solution including the arbitrary constants includes both the homogenous and particular solutions,\n\n$$\n\\begin{eqnarray*}\nx(t)&=&\\frac{F_0}{m}\\frac{\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\n+A\\cos\\omega't e^{-\\beta t}+B\\sin\\omega't e^{-\\beta t}.\n\\end{eqnarray*}\n$$\n\nThe quantities $\\delta$ and $\\omega'$ are given earlier in the\nsection, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2},\n\\delta=\\tan^{-1}(2\\beta\\omega/(\\omega_0^2-\\omega^2)$. Here, solving\nthe problem means finding the arbitrary constants $A$ and\n$B$. Satisfying the initial conditions for the initial position and\nvelocity:\n\n$$\n\\begin{eqnarray*}\nx(t=0)=0&=&-\\eta\\sin\\delta+A,\\\\\nv(t=0)=0&=&\\omega\\eta\\cos\\delta-\\beta A+\\omega'B,\\\\\n\\eta&\\equiv&\\frac{F_0}{m}\\frac{1}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray*}\n$$\n\nThe problem is now reduced to 2 equations and 2 unknowns, $A$ and $B$. The solution is\n\n$$\n\\begin{eqnarray}\nA&=& \\eta\\sin\\delta ,~~~B=\\frac{-\\omega\\eta\\cos\\delta+\\beta\\eta\\sin\\delta}{\\omega'}.\n\\end{eqnarray}\n$$\n\n## Resonance Widths; the $Q$ factor\n\nFrom the previous two sections, the particular solution for a driving force, $F=F_0\\cos\\omega t$, is\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\\cos(\\omega_t-\\delta),\\\\\n\\nonumber\n\\delta&=&\\tan^{-1}\\left(\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nIf one fixes the driving frequency $\\omega$ and adjusts the\nfundamental frequency $\\omega_0=\\sqrt{k/m}$, the maximum amplitude\noccurs when $\\omega_0=\\omega$ because that is when the term from the\ndenominator $(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2$ is at a\nminimum. This is akin to dialing into a radio station. However, if one\nfixes $\\omega_0$ and adjusts the driving frequency one minimize with\nrespect to $\\omega$, e.g. set\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{d\\omega}\\left[(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2\\right]=0,\n\\label{_auto13} \\tag{22}\n\\end{equation}\n$$\n\nand one finds that the maximum amplitude occurs when\n$\\omega=\\sqrt{\\omega_0^2-2\\beta^2}$. If $\\beta$ is small relative to\n$\\omega_0$, one can simply state that the maximum amplitude is\n\n\n
\n\n$$\n\\begin{equation}\nx_{\\rm max}\\approx\\frac{F_0}{2m\\beta \\omega_0}.\n\\label{_auto14} \\tag{23}\n\\end{equation}\n$$\n\n$$\n\\begin{eqnarray}\n\\frac{4\\omega^2\\beta^2}{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}=\\frac{1}{2}.\n\\end{eqnarray}\n$$\n\nFor small damping this occurs when $\\omega=\\omega_0\\pm \\beta$, so the $FWHM\\approx 2\\beta$. For the purposes of tuning to a specific frequency, one wants the width to be as small as possible. The ratio of $\\omega_0$ to $FWHM$ is known as the {\\it quality} factor, or $Q$ factor,\n\n\n
\n\n$$\n\\begin{equation}\nQ\\equiv \\frac{\\omega_0}{2\\beta}.\n\\label{_auto15} \\tag{24}\n\\end{equation}\n$$\n\n\n## Principle of Superposition and Periodic Forces (Fourier Transforms)\n\nIf one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\nthe particular solution to each $F_n$, $x_{pn}(t)$, and the particular\nsolution for the entire driving force is\n\n\n
\n\n$$\n\\begin{equation}\nx_p(t)=\\sum_nx_{pn}(t).\n\\label{_auto16} \\tag{25}\n\\end{equation}\n$$\n\nThis is known as the principal of superposition. It only applies when\nthe homogenous equation is linear. If there were an anharmonic term\nsuch as $x^3$ in the homogenous equation, then when one summed various\nsolutions, $x=(\\sum_n x_n)^2$, one would get cross\nterms. Superposition is especially useful when $F(t)$ can be written\nas a sum of sinusoidal terms, because the solutions for each\nsinusoidal term is analytic, and are given in the previous two\nsubsections.\n\nDriving forces are often periodic, even when they are not\nsinusoidal. Periodicity implies that for some time $\\tau$\n\n$$\n\\begin{eqnarray}\nF(t+\\tau)=F(t). \n\\end{eqnarray}\n$$\n\nOne example of a non-sinusoidal periodic force is a square wave. Many\ncomponents in electric circuits are non-linear, e.g. diodes, which\nmakes many wave forms non-sinusoidal even when the circuits are being\ndriven by purely sinusoidal sources.\n\nFor the sinusoidal example studied in the previous subsections the\nperiod is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\nsatisfy the periodicity requirement. In general, any force that\nsatisfies the periodicity requirement can be expressed as a sum over\nharmonics,\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n\\label{_auto17} \\tag{26}\n\\end{equation}\n$$\n\nFrom the previous subsection, one can write down the answer for\n$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$ into Eq.s\n([20](#eq:fastdriven1)) or ([21](#eq:fastdriven2)) respectively. By\nwriting each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n2\\pi/\\tau$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:fourierdef1} \\tag{27}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n\\end{equation}\n$$\n\nThe solutions for $x(t)$ then come from replacing $\\omega$ with\n$n\\omega$ for each term in the particular solution in Equations\n([13](#eq:partform)) and ([16](#eq:Ddrive)),\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n\\nonumber\n\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nBecause the forces have been applied for a long time, any non-zero\ndamping eliminates the homogenous parts of the solution, so one need\nonly consider the particular solution for each $n$.\n\nThe problem will considered solved if one can find expressions for the\ncoefficients $f_n$ and $g_n$, even though the solutions are expressed\nas an infinite sum. The coefficients can be extracted from the\nfunction $F(t)$ by\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fourierdef2} \\tag{28}\nf_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n\\nonumber\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n\\end{eqnarray}\n$$\n\nTo check the consistency of these expressions and to verify\nEq. ([28](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\nEq. ([27](#eq:fourierdef1)) into the expression for the coefficients in\nEq. ([28](#eq:fourierdef2)) and see whether\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\n\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\n\\right\\}\\cos(n\\omega t).\n\\end{eqnarray}\n$$\n\nImmediately, one can throw away all the terms with $g_m$ because they\nconvolute an even and an odd function. The term with $f_0/2$\ndisappears because $\\cos(n\\omega t)$ is equally positive and negative\nover the interval and will integrate to zero. For all the terms\n$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\nformulas to see that $\\cos(m\\omega t)\\cos(n\\omega\nt)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\nto zero unless $m=n$. In that case the $m=n$ term gives\n\n\n
\n\n$$\n\\begin{equation}\n\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n\\label{_auto18} \\tag{29}\n\\end{equation}\n$$\n\nand\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2\\\\\n\\nonumber\n&=&f_n~\\checkmark.\n\\end{eqnarray}\n$$\n\nThe same method can be used to check for the consistency of $g_n$.\n\n\nConsider the driving force:\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=At/\\tau,~~-\\tau/2\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fouriersolution} \\tag{31}\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2}dt~\\sin(n\\omega t) \\frac{At}{\\tau}\\\\\n\\nonumber\nu&=&t,~dv=\\sin(n\\omega t)dt,~v=-\\cos(n\\omega t)/(n\\omega),\\\\\n\\nonumber\ng_n&=&\\frac{-2A}{n\\omega \\tau^2}\\int_{-\\tau/2}^{\\tau/2}dt~\\cos(n\\omega t)\n+\\left.2A\\frac{-t\\cos(n\\omega t)}{n\\omega\\tau^2}\\right|_{-\\tau/2}^{\\tau/2}.\n\\end{eqnarray}\n$$\n\nThe first term is zero because $\\cos(n\\omega t)$ will be equally\npositive and negative over the interval. Using the fact that\n$\\omega\\tau=2\\pi$,\n\n$$\n\\begin{eqnarray}\ng_n&=&-\\frac{2A}{2n\\pi}\\cos(n\\omega\\tau/2)\\\\\n\\nonumber\n&=&-\\frac{A}{n\\pi}\\cos(n\\pi)\\\\\n\\nonumber\n&=&\\frac{A}{n\\pi}(-1)^{n+1}.\n\\end{eqnarray}\n$$\n\n## Response to Transient Force\n\nConsider a particle at rest in the bottom of an underdamped harmonic\noscillator, that then feels a sudden impulse, or change in momentum,\n$I=F\\Delta t$ at $t=0$. This increases the velocity immediately by an\namount $v_0=I/m$ while not changing the position. One can then solve\nthe trajectory by solving Eq. ([9](#eq:homogsolution)) with initial\nconditions $v_0=I/m$ and $x_0=0$. This gives\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I}{m\\omega'}e^{-\\beta t}\\sin\\omega't, ~~t>0.\n\\label{_auto20} \\tag{32}\n\\end{equation}\n$$\n\nHere, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2}$. For an impulse $I_i$ that\noccurs at time $t_i$ the trajectory would be\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I_i}{m\\omega'}e^{-\\beta (t-t_i)}\\sin[\\omega'(t-t_i)] \\Theta(t-t_i),\n\\label{_auto21} \\tag{33}\n\\end{equation}\n$$\n\nwhere $\\Theta(t-t_i)$ is a step function, i.e. $\\Theta(x)$ is zero for\n$x<0$ and unity for $x>0$. If there were several impulses linear\nsuperposition tells us that we can sum over each contribution,\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\sum_i\\frac{I_i}{m\\omega'}e^{-\\beta(t-t_i)}\\sin[\\omega'(t-t_i)]\\Theta(t-t_i)\n\\label{_auto22} \\tag{34}\n\\end{equation}\n$$\n\nNow one can consider a series of impulses at times separated by\n$\\Delta t$, where each impulse is given by $F_i\\Delta t$. The sum\nabove now becomes an integral,\n\n\n
\n\n$$\n\\begin{eqnarray}\\label{eq:Greeny} \\tag{35}\nx(t)&=&\\int_{-\\infty}^\\infty dt'~F(t')\\frac{e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]}{m\\omega'}\\Theta(t-t')\\\\\n\\nonumber\n&=&\\int_{-\\infty}^\\infty dt'~F(t')G(t-t'),\\\\\n\\nonumber\nG(\\Delta t)&=&\\frac{e^{-\\beta\\Delta t}\\sin[\\omega' \\Delta t]}{m\\omega'}\\Theta(\\Delta t)\n\\end{eqnarray}\n$$\n\nThe quantity\n$e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]/m\\omega'\\Theta(t-t')$ is called a\nGreen's function, $G(t-t')$. It describes the response at $t$ due to a\nforce applied at a time $t'$, and is a function of $t-t'$. The step\nfunction ensures that the response does not occur before the force is\napplied. One should remember that the form for $G$ would change if the\noscillator were either critically- or over-damped.\n\nWhen performing the integral in Eq. ([35](#eq:Greeny)) one can use\nangle addition formulas to factor out the part with the $t'$\ndependence in the integrand,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:Greeny2} \\tag{36}\nx(t)&=&\\frac{1}{m\\omega'}e^{-\\beta t}\\left[I_c(t)\\sin(\\omega't)-I_s(t)\\cos(\\omega't)\\right],\\\\\n\\nonumber\nI_c(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\cos(\\omega't'),\\\\\n\\nonumber\nI_s(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\sin(\\omega't').\n\\end{eqnarray}\n$$\n\nIf the time $t$ is beyond any time at which the force acts,\n$F(t'>t)=0$, the coefficients $I_c$ and $I_s$ become independent of\n$t$.\n\n\nConsider an undamped oscillator ($\\beta\\rightarrow 0$), with\ncharacteristic frequency $\\omega_0$ and mass $m$, that is at rest\nuntil it feels a force described by a Gaussian form,\n\n$$\n\\begin{eqnarray*}\nF(t)&=&F_0 \\exp\\left\\{\\frac{-t^2}{2\\tau^2}\\right\\}.\n\\end{eqnarray*}\n$$\n\nFor large times ($t>>\\tau$), where the force has died off, find\n$x(t)$.\\\\ Solve for the coefficients $I_c$ and $I_s$ in\nEq. ([36](#eq:Greeny2)). Because the Gaussian is an even function,\n$I_s=0$, and one need only solve for $I_c$,\n\n$$\n\\begin{eqnarray*}\nI_c&=&F_0\\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}\\cos(\\omega_0 t')\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}e^{i\\omega_0 t'}\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-(t'-i\\omega_0\\tau^2)^2/(2\\tau^2)}e^{-\\omega_0^2\\tau^2/2}\\\\\n&=&F_0\\tau \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}.\n\\end{eqnarray*}\n$$\n\nThe third step involved completing the square, and the final step used the fact that the integral\n\n$$\n\\begin{eqnarray*}\n\\int_{-\\infty}^\\infty dx~e^{-x^2/2}&=&\\sqrt{2\\pi}.\n\\end{eqnarray*}\n$$\n\nTo see that this integral is true, consider the square of the integral, which you can change to polar coordinates,\n\n$$\n\\begin{eqnarray*}\nI&=&\\int_{-\\infty}^\\infty dx~e^{-x^2/2}\\\\\nI^2&=&\\int_{-\\infty}^\\infty dxdy~e^{-(x^2+y^2)/2}\\\\\n&=&2\\pi\\int_0^\\infty rdr~e^{-r^2/2}\\\\\n&=&2\\pi.\n\\end{eqnarray*}\n$$\n\nFinally, the expression for $x$ from Eq. ([36](#eq:Greeny2)) is\n\n$$\n\\begin{eqnarray*}\nx(t>>\\tau)&=&\\frac{F_0\\tau}{m\\omega_0} \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}\\sin(\\omega_0t).\n\\end{eqnarray*}\n$$\n\n## Sliding Block tied to a Wall\nAnother classical case is that of simple harmonic oscillations, here represented by a block sliding on a horizontal frictionless surface. The block is tied to a wall with a spring. If the spring is not compressed or stretched too far, the force on the block at a given position $x$ is\n\n$$\nF=-kx.\n$$\n\nThe negative sign means that the force acts to restore the object to an equilibrium position. Newton's equation of motion for this idealized system is then\n\n$$\nm\\frac{d^2x}{dt^2}=-kx,\n$$\n\nor we could rephrase it as\n\n\n
\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{k}{m}x=-\\omega_0^2x,\n\\label{eq:newton1} \\tag{37}\n$$\n\nwith the angular frequency $\\omega_0^2=k/m$. \n\nThe above differential equation has the advantage that it can be solved analytically with solutions on the form\n\n$$\nx(t)=Acos(\\omega_0t+\\nu),\n$$\n\nwhere $A$ is the amplitude and $\\nu$ the phase constant. This provides in turn an important test for the numerical\nsolution and the development of a program for more complicated cases which cannot be solved analytically.\n\n\n\n\n## Simple Example, Block tied to a Wall\n\nWith the position $x(t)$ and the velocity $v(t)=dx/dt$ we can reformulate Newton's equation in the following way\n\n$$\n\\frac{dx(t)}{dt}=v(t),\n$$\n\nand\n\n$$\n\\frac{dv(t)}{dt}=-\\omega_0^2x(t).\n$$\n\nWe are now going to solve these equations using first the standard forward Euler method. Later we will try to improve upon this.\n\n\n## Simple Example, Block tied to a Wall\n\nBefore proceeding however, it is important to note that in addition to the exact solution, we have at least two further tests which can be used to check our solution. \n\nSince functions like $cos$ are periodic with a period $2\\pi$, then the solution $x(t)$ has also to be periodic. This means that\n\n$$\nx(t+T)=x(t),\n$$\n\nwith $T$ the period defined as\n\n$$\nT=\\frac{2\\pi}{\\omega_0}=\\frac{2\\pi}{\\sqrt{k/m}}.\n$$\n\nObserve that $T$ depends only on $k/m$ and not on the amplitude of the solution. \n\n\n## Simple Example, Block tied to a Wall\n\nIn addition to the periodicity test, the total energy has also to be conserved. \n\nSuppose we choose the initial conditions\n\n$$\nx(t=0)=1\\hspace{0.1cm} \\mathrm{m}\\hspace{1cm} v(t=0)=0\\hspace{0.1cm}\\mathrm{m/s},\n$$\n\nmeaning that block is at rest at $t=0$ but with a potential energy\n\n$$\nE_0=\\frac{1}{2}kx(t=0)^2=\\frac{1}{2}k.\n$$\n\nThe total energy at any time $t$ has however to be conserved, meaning that our solution has to fulfil the condition\n\n$$\nE_0=\\frac{1}{2}kx(t)^2+\\frac{1}{2}mv(t)^2.\n$$\n\n## Simple Example, Block tied to a Wall\n\nAn algorithm which implements these equations is included below.\n * Choose the initial position and speed, with the most common choice $v(t=0)=0$ and some fixed value for the position. \n\n * Choose the method you wish to employ in solving the problem.\n\n * Subdivide the time interval $[t_i,t_f] $ into a grid with step size\n\n$$\nh=\\frac{t_f-t_i}{N},\n$$\n\nwhere $N$ is the number of mesh points. \n * Calculate now the total energy given by\n\n$$\nE_0=\\frac{1}{2}kx(t=0)^2=\\frac{1}{2}k.\n$$\n\n* Choose ODE solver to obtain $x_{i+1}$ and $v_{i+1}$ starting from the previous values $x_i$ and $v_i$.\n\n * When we have computed $x(v)_{i+1}$ we upgrade $t_{i+1}=t_i+h$.\n\n * This iterative process continues till we reach the maximum time $t_f$.\n\n * The results are checked against the exact solution. Furthermore, one has to check the stability of the numerical solution against the chosen number of mesh points $N$. \n\n## Simple Example, Block tied to a Wall, python code\n\nThe following python program performs essentially the same calculations as the previous c++ code.\n\n\n```python\n#\n# This program solves Newtons equation for a block sliding on\n# an horizontal frictionless surface.\n# The block is tied to the wall with a spring, so N's eq takes the form:\n#\n# m d^2x/dt^2 = - kx\n#\n# In order to make the solution dimless, we set k/m = 1.\n# This results in two coupled diff. eq's that may be written as:\n#\n# dx/dt = v\n# dv/dt = -x\n#\n# The user has to specify the initial velocity and position,\n# and the number of steps. The time interval is fixed to\n# t \\in [0, 4\\pi) (two periods)\n#\n# Note that this is a highly simplifyed rk4 code, intended\n# for conceptual understanding and experimentation.\n\nimport sys\nimport numpy, math\n\n#Global variables\nofile = None;\nE0 = 0.0\n\ndef sim(x_0, v_0, N):\n ts = 0.0\n te = 4*math.pi\n h = (te-ts)/float(N)\n\n t = ts;\n x = x_0\n v = v_0\n while (t < te):\n kv1 = -h*x\n kx1 = h*v\n\n kv2 = -h*(x+kx1/2)\n kx2 = h*(v+kv1/2)\n\n kv3 = -h*(x+kx2/2)\n kx3 = h*(v+kv2/2)\n\n kv4 = -h*(x+kx3/2)\n kx4 = h*(v+kv3/2)\n\n #Write the old values to file\n output(t,x,v)\n\n #Update\n x = x + (kx1 + 2*(kx2+kx3) + kx4)/6\n v = v + (kv1 + 2*(kv2+kv3) + kv4)/6\n t = t+h\n \ndef output(t,x,v):\n de = 0.5*x**2+0.5*v**2 - E0;\n ofile.write(\"%15.8E %15.8E %15.8E %15.8E %15.8E\\n\"\\\n %(t, x, v, math.cos(t),de));\n\n\n#MAIN PROGRAM:\n\n#Get input\nif len(sys.argv) == 5:\n ofilename = sys.argv[1];\n x_0 = float(sys.argv[2])\n v_0 = float(sys.argv[3])\n N = int(sys.argv[4])\nelse:\n print \"Usage:\", sys.argv[0], \"ofilename x0 v0 N\"\n sys.exit(0)\n\n#Setup\nofile = open(ofilename, 'w')\nE0 = 0.5*x_0**2+0.5*v_0**2\n\n#Run simulation\nsim(x_0,v_0,N)\n\n#Cleanup\nofile.close()\n```\n\n## The classical pendulum and scaling the equations\n\nThe angular equation of motion of the pendulum is given by\nNewton's equation and with no external force it reads\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+mgsin(\\theta)=0,\n\\label{_auto23} \\tag{38}\n\\end{equation}\n$$\n\nwith an angular velocity and acceleration given by\n\n\n
\n\n$$\n\\begin{equation}\n v=l\\frac{d\\theta}{dt},\n\\label{_auto24} \\tag{39}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n a=l\\frac{d^2\\theta}{dt^2}.\n\\label{_auto25} \\tag{40}\n\\end{equation}\n$$\n\n## More on the Pendulum\n\nWe do however expect that the motion will gradually come to an end due a viscous drag torque acting on the pendulum. \nIn the presence of the drag, the above equation becomes\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=0, \\label{eq:pend1} \\tag{41}\n\\end{equation}\n$$\n\nwhere $\\nu$ is now a positive constant parameterizing the viscosity\nof the medium in question. In order to maintain the motion against\nviscosity, it is necessary to add some external driving force. \nWe choose here a periodic driving force. The last equation becomes then\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=Asin(\\omega t), \\label{eq:pend2} \\tag{42}\n\\end{equation}\n$$\n\nwith $A$ and $\\omega$ two constants representing the amplitude and \nthe angular frequency respectively. The latter is called the driving frequency.\n\n\n\n\n## More on the Pendulum\n\nWe define\n\n$$\n\\omega_0=\\sqrt{g/l},\n$$\n\nthe so-called natural frequency and the new dimensionless quantities\n\n$$\n\\hat{t}=\\omega_0t,\n$$\n\nwith the dimensionless driving frequency\n\n$$\n\\hat{\\omega}=\\frac{\\omega}{\\omega_0},\n$$\n\nand introducing the quantity $Q$, called the *quality factor*,\n\n$$\nQ=\\frac{mg}{\\omega_0\\nu},\n$$\n\nand the dimensionless amplitude\n\n$$\n\\hat{A}=\\frac{A}{mg}\n$$\n\n## More on the Pendulum\n\nWe have\n\n$$\n\\frac{d^2\\theta}{d\\hat{t}^2}+\\frac{1}{Q}\\frac{d\\theta}{d\\hat{t}} \n +sin(\\theta)=\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThis equation can in turn be recast in terms of two coupled first-order differential equations as follows\n\n$$\n\\frac{d\\theta}{d\\hat{t}}=\\hat{v},\n$$\n\nand\n\n$$\n\\frac{d\\hat{v}}{d\\hat{t}}=-\\frac{\\hat{v}}{Q}-sin(\\theta)+\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThese are the equations to be solved. The factor $Q$ represents the number of oscillations of the undriven system that must occur before its energy is significantly reduced due to the viscous drag. The amplitude $\\hat{A}$ is measured in units of the maximum possible gravitational torque while $\\hat{\\omega}$ is the angular frequency of the external torque measured in units of the pendulum's natural frequency.\n", "meta": {"hexsha": "05231ff30562a858dcf466eacd0ea56276a21e9c", "size": 89181, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/harmonic/ipynb/.ipynb_checkpoints/harmonic-checkpoint.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/pub/harmonic/ipynb/.ipynb_checkpoints/harmonic-checkpoint.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/pub/harmonic/ipynb/.ipynb_checkpoints/harmonic-checkpoint.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 35.902173913, "max_line_length": 16912, "alphanum_fraction": 0.6161850618, "converted": true, "num_tokens": 14521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.3812195592260441, "lm_q1q2_score": 0.18019618094701675}} {"text": "\n# Nuclear Talent course on Machine Learning in Nuclear Experiment and Theory\n\n \n**[Daniel Bazin](https://www.nscl.msu.edu/directory/bazin.html)**, Department of Physics and Astronomy and Facility for Rare Ion Beams and National Superconducting Cyclotron Laboratory, Michigan State University, East Lansing, Michigan, USA \n\n **[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams and National Superconducting Cyclotron Laboratory, Michigan State University, East Lansing, Michigan, USA and Department of Physics and Center for Computing in Science Education, University of Oslo, Oslo, Norway \n\n **[Michelle Kuchera](https://www.davidson.edu/academics/physics/faculty-and-staff/michelle-kuchera)**, Physics Department, Davidson College, Davidson, North Carolina, USA \n\n **[Sean Liddick](https://www.nscl.msu.edu/directory/liddick.html)**, Department of Chemistry and Facility for Rare Ion Beams and National Superconducting Cyclotron Laboratory, Michigan State University, East Lansing, Michigan, USA \n\n **[Raghuram Ramanujan](https://www.davidson.edu/academics/mathematics-and-computer-science/faculty-and-staff/raghuram-ramanujan)**, Department of Mathematics and Computer Science, Davidson College, Davidson, North Carolina, USA\n\nDate: **Jun 21, 2020**\n\n## Introduction\n\nDuring the last two decades there has been a swift and amazing\ndevelopment of Machine Learning techniques and algorithms that impact\nmany areas in not only Science and Technology but also the Humanities,\nSocial Sciences, Medicine, Law, indeed, almost all possible\ndisciplines. The applications are incredibly many, from self-driving\ncars to solving high-dimensional differential equations or complicated\nquantum mechanical many-body problems. Machine Learning is perceived\nby many as one of the main disruptive techniques nowadays. \n\nStatistics, Data science and Machine Learning form important\nfields of research in modern science. They describe how to learn and\nmake predictions from data, as well as allowing us to extract\nimportant correlations about physical process and the underlying laws\nof motion in large data sets. The latter, big data sets, appear\nfrequently in essentially all disciplines, from the traditional\nScience, Technology, Mathematics and Engineering fields to Life\nScience, Law, education research, the Humanities and the Social\nSciences.\n\n## Overview of these introductory notes\n\nThe aim of these notes is to give you a birds view over overarching issues on Machine Learning, a brief review of programming with Python and libraries we will use in this course, a reminder on statistics and finally our first encounters of Machine Learning methods applied to an evergreen in Nuclear Physics, fitting nuclear binding energies.\nIf you are familiar with basic Python programming and statistics, you can easily jump some of the introductory material here.\n\nAfter these introductory words, the set of lectures will contain the following themes:\n* Linear Regression\n\n* Logistic Regression\n\n* Decision Trees, Random Forests, Bagging and Boosting\n\n* Neural Networks and Deep Learning methods\n\n* Convolutional and Recurrent Neural Networks and how to analyze experimental results\n\n* Generative Models\n\n* Reinforcement Learning\n\n* The experimental data we will analyze are based on experiments from $\\beta$-decay experiments and data from Active Target experiments\n\n\n\n## Machine Learning, short overview\n\n\n## Machine Learning, a small (and probably biased) introduction\n\n\nIdeally, machine learning represents the science of giving computers\nthe ability to learn without being explicitly programmed. The idea is\nthat there exist generic algorithms which can be used to find patterns\nin a broad class of data sets without having to write code\nspecifically for each problem. The algorithm will build its own logic\nbased on the data. You should however always keep in mind that\nmachines and algorithms are to a large extent developed by humans. The\ninsights and knowledge we have about a specific system, play a central\nrole when we develop a specific machine learning algorithm. \n\n## Machine Learning, an extremely rich field\n\nMachine learning is an extremely rich field, in spite of its young\nage. The increases we have seen during the last decades in\ncomputational capabilities have been followed by developments of\nmethods and techniques for analyzing and handling large date sets,\nrelying heavily on statistics, computer science and mathematics. The\nfield is rather new and developing rapidly. Popular software libraries\nwritten in Python for machine learning like\n[Scikit-learn](http://scikit-learn.org/stable/),\n[Tensorflow](https://www.tensorflow.org/),\n[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\nfreely available at their respective GitHub sites, encompass\ncommunities of developers in the thousands or more. And the number of\ncode developers and contributors keeps increasing.\n\n## A multidisciplinary approach\n\nNot all the\nalgorithms and methods can be given a rigorous mathematical\njustification (for example decision trees and random forests), opening up thereby large rooms for experimenting and\ntrial and error and thereby exciting new developments. However, a\nsolid command of linear algebra, multivariate theory, probability\ntheory, statistical data analysis, understanding errors and Monte\nCarlo methods are central elements in a proper understanding of many\nof the algorithms and methods we will discuss.\n\n\n\n## Learning outcomes\n\nThese sets of lectures aim at giving you an overview of central aspects of\nstatistical data analysis as well as some of the central algorithms\nused in machine learning. We will introduce a variety of central\nalgorithms and methods essential for studies of data analysis and\nmachine learning. \n\nHands-on projects and experimenting with data and algorithms play a central role in\nthese lectures, and our hope is, through the various examples discussed in this series of lectures,\nto expose you to fundamental\nresearch problems in these fields, with the aim to reproduce state of\nthe art scientific results. \nMore specifically, you will\n\n1. Learn about basic data analysis, data optimization and machine learning;\n\n2. Be capable of extending the acquired knowledge to other systems and cases;\n\n3. Have an understanding of central algorithms used in data analysis and machine learning;\n\n4. Methods we will focus on are Linear and Logistic Regression, Decision trees, random forests, bagging and boosting and various variants of deep learning methods, from feed forward neural networks to more advanced methods;\n\n5. Work on numerical examples to illustrate the theory; \n\n\n\n## Types of Machine Learning\n\n\nThe approaches to machine learning are many, but are often split into\ntwo main categories. In *supervised learning* we know the answer to a\nproblem, and let the computer deduce the logic behind it. On the other\nhand, *unsupervised learning* is a method for finding patterns and\nrelationship in data sets without any prior knowledge of the system.\nSome authours also operate with a third category, namely\n*reinforcement learning*. This is a paradigm of learning inspired by\nbehavioral psychology, where learning is achieved by trial-and-error,\nsolely from rewards and punishment.\n\nAnother way to categorize machine learning tasks is to consider the\ndesired output of a system. Some of the most common tasks are:\n\n* Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is often supervised learning.\n\n* Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n\n* Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n\n\n\n\n## Essential elements of ML\n\nThe methods we cover have three main topics in common, irrespective of\nwhether we deal with supervised or unsupervised learning.\n* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n\n* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n\n* The last ingredient is a so-called **cost/loss** function (or error function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n\n\n\n\n\n## An optimization/minimization problem\n\nAt the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n\n## A Frequentist approach to data analysis\n\nWhen you hear phrases like **predictions and estimations** and\n**correlations and causations**, what do you think of? May be you think\nof the difference between classifying new data points and generating\nnew data points.\nOr perhaps you consider that correlations represent some kind of symmetric statements like\nif $A$ is correlated with $B$, then $B$ is correlated with\n$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\nnecessarily cause $A$.\n\nThese concepts are in some sense the difference between machine\nlearning and statistics. In machine learning and prediction based\ntasks, we are often interested in developing algorithms that are\ncapable of learning patterns from given data in an automated fashion,\nand then using these learned patterns to make predictions or\nassessments of newly given data. In many cases, our primary concern\nis the quality of the predictions or assessments, and we are less\nconcerned about the underlying patterns that were learned in order\nto make these predictions.\n\nIn machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\nwhere the aim is to make predictions and find correlations. We focus\nless on for example extracting a probability distribution function (PDF). The PDF can be\nused in turn to make estimations and find causations such as given $A$\nwhat is the likelihood of finding $B$.\n\n\n## What is a good model?\n\nIn science and engineering we often end up in situations where we want to infer (or learn) a\nquantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n\nAs we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\nstraight line, or if we wish to be more sophisticated to a more complex\nfunction.\n\nThe reason for inferring such a model is that it\nserves many useful purposes. On the one hand, the model can reveal information\nencoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\ncorelations that relate interesting physics interpretations.\n\nIn addition, it can simplify the representation of the given data set and help\nus in making predictions about future data samples.\n\nA first important consideration to keep in mind is that inferring the *correct* model\nfor a given data set is an elusive, if not impossible, task. The fundamental difficulty\nis that if we are not specific about what we mean by a *correct* model, there\ncould easily be many different models that fit the given data set *equally well*.\n\n\nThe central question is this: what leads us to say that a model is correct or\noptimal for a given data set? To make the model inference problem well posed, i.e.,\nto guarantee that there is a unique optimal model for the given data, we need to\nimpose additional assumptions or restrictions on the class of models considered. To\nthis end, we should not be looking for just any model that can describe the data.\nInstead, we should look for a **model** $M$ that is the best among a restricted class\nof models. In addition, to make the model inference problem computationally\ntractable, we need to specify how restricted the class of models needs to be. A\ncommon strategy is to start \nwith the simplest possible class of models that is just necessary to describe the data\nor solve the problem at hand. More precisely, the model class should be rich enough\nto contain at least one model that can fit the data to a desired accuracy and yet be\nrestricted enough that it is relatively simple to find the best model for the given data.\n\nThus, the most popular strategy is to start from the\nsimplest class of models and increase the complexity of the models only when the\nsimpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\nmay first try the simplest class of models, namely linear models, followed obviously by more complex models.\n\nHow to evaluate which model fits best the data is something we will come back to over and over again in these set of lectures.\n\n## Practicalities, choice of programming language and other computational issues\n\n## Choice of Programming Language\n\nPython plays nowadays a central role in the development of machine\nlearning techniques and tools for data analysis. In particular, seen\nthe wealth of machine learning and data analysis libraries written in\nPython, easy to use libraries with immediate visualization(and not the\nleast impressive galleries of existing examples), the popularity of the\nJupyter notebook framework with the possibility to run **R** codes or\ncompiled programs written in C++, and much more made our choice of\nprogramming language for this series of lectures easy. However,\nsince the focus here is not only on using existing Python libraries such\nas **Scikit-Learn**, **Tensorflow** and **Pytorch**, but also on developing your own\nalgorithms and codes, we will as far as possible present many of these\nalgorithms either as a Python codes or C++ or Fortran (or other languages) codes. \n\n\n\n\n\n\n## Software and needed installations\n\nWe will make extensive use of Python as programming language and its\nmyriad of available libraries. You will find\nJupyter notebooks invaluable in your work. You can run **R**\ncodes in the Jupyter/IPython notebooks, with the immediate benefit of\nvisualizing your data. You can also use compiled languages like C++,\nRust, Julia, Fortran etc if you prefer. The focus in these lectures will be\non Python.\n\n\nIf you have Python installed (we strongly recommend Python3) and you feel\npretty familiar with installing different packages, we recommend that\nyou install the following Python packages via **pip** as \n\n1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n\nFor Python3, replace **pip** with **pip3**.\n\nFor OSX users we recommend, after having installed Xcode, to\ninstall **brew**. Brew allows for a seamless installation of additional\nsoftware via for example \n\n1. brew install python3\n\nFor Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\nyou can use **pip** as well and simply install Python as \n\n1. sudo apt-get install python3 (or python for pyhton2.7)\n\netc etc. \n\n\n## Python installers\n\nIf you don't want to perform these operations separately and venture\ninto the hassle of exploring how to set up dependencies and paths, we\nrecommend two widely used distrubutions which set up all relevant\ndependencies for Python, namely \n\n* [Anaconda](https://docs.anaconda.com/), \n\nwhich is an open source\ndistribution of the Python and R programming languages for large-scale\ndata processing, predictive analytics, and scientific computing, that\naims to simplify package management and deployment. Package versions\nare managed by the package management system **conda**. \n\n* [Enthought canopy](https://www.enthought.com/product/canopy/) \n\nis a Python\ndistribution for scientific and analytic computing distribution and\nanalysis environment, available for free and under a commercial\nlicense.\n\nFurthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \nno setup and runs entirely in the cloud. Try it out!\n\n## Useful Python libraries\nHere we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n\n* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n\n* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n\n* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n\n* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n\n* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n\n* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n\n* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n\n* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n\n* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n\n* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n\n* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n\n## More Practicalities, handling arrays\n\n\n## Basic Matrix Features, Numpy examples and Important Matrix and vector handling packages\n\n**Matrix properties reminder.**\n\n$$\n\\mathbf{A} =\n \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n a_{21} & a_{22} & a_{23} & a_{24} \\\\\n a_{31} & a_{32} & a_{33} & a_{34} \\\\\n a_{41} & a_{42} & a_{43} & a_{44}\n \\end{bmatrix}\\qquad\n\\mathbf{I} =\n \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 1 & 0 \\\\\n 0 & 0 & 0 & 1\n \\end{bmatrix}\n$$\n\nThe inverse of a matrix is defined by\n\n$$\n\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n$$\n\n\n\n\n\n\n\n\n\n\n\n\n
Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$
\n\n\n\n## Some famous Matrices\n\n * Diagonal if $a_{ij}=0$ for $i\\ne j$\n\n * Upper triangular if $a_{ij}=0$ for $i > j$\n\n * Lower triangular if $a_{ij}=0$ for $i < j$\n\n * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n\n * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n\n * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n\n * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n\n * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n\n * Banded, block upper triangular, block lower triangular....\n\n## More Basic Matrix Features\n\n**Some Equivalent Statements.**\n\nFor an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n\n * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n\n * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n\n * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n\n * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n\n * $\\mathbf{A}$ is a product of elementary matrices.\n\n * $0$ is not eigenvalue of $\\mathbf{A}$.\n\n\n\n## Numpy and arrays\n[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as\n\n\n```python\nimport numpy as np\n```\n\nHere follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,\n\n\n```python\nn = 10\nx = np.random.normal(size=n)\nprint(x)\n```\n\nWe defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\nAnother alternative is to declare a vector as follows\n\n\n```python\nimport numpy as np\nx = np.array([1, 2, 3])\nprint(x)\n```\n\nHere we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\nstart numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4, 7, 8]))\nprint(x)\n```\n\n## More Examples\n\nIn the last example we used Numpy's unary function $np.log$. This function is\nhighly tuned to compute array elements since the code is vectorized\nand does not require looping. We normaly recommend that you use the\nNumpy intrinsic functions instead of the corresponding **log** function\nfrom Python's **math** module. The looping is done explicitely by the\n**np.log** function. The alternative, and slower way to compute the\nlogarithms of a vector would be to write\n\n\n```python\nimport numpy as np\nfrom math import log\nx = np.array([4, 7, 8])\nfor i in range(0, len(x)):\n x[i] = log(x[i])\nprint(x)\n```\n\nWe note that our code is much longer already and we need to import the **log** function from the **math** module. \nThe attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4, 7, 8], dtype = np.float64))\nprint(x)\n```\n\nor simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x)\n```\n\nTo check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as\n\n\n```python\nimport numpy as np\nx = np.log(np.array([4.0, 7.0, 8.0])\nprint(x.itemsize)\n```\n\n## Matrices in Python\n\nHaving defined vectors, we are now ready to try out matrices. We can\ndefine a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\nlowercase letters for vectors and uppercase letters for matrices)\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\nprint(A)\n```\n\nIf we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[:,0])\n```\n\nWe can continue this was by printing out other columns or rows. The example here prints out the second column\n\n\n```python\nimport numpy as np\nA = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n# print the first column, row-major order and elements start with 0\nprint(A[1,:])\n```\n\nNumpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to zero\nA = np.zeros( (n, n) )\nprint(A)\n```\n\nor initializing all elements to\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to one\nA = np.ones( (n, n) )\nprint(A)\n```\n\nor as unitarily distributed random numbers (see the material on random number generators in the statistics part)\n\n\n```python\nimport numpy as np\nn = 10\n# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\nA = np.random.rand(n, n)\nprint(A)\n```\n\n## More Examples, Covariance matrix\n\nAs we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\nAs an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n$\\hat{x}, \\hat{y}, \\hat{z}$ with $n$ elements each. The covariance matrix is defined as\n\n$$\n\\hat{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n \\end{bmatrix},\n$$\n\nwhere for example\n\n$$\n\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n$$\n\nThe Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. \nThe following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $3\\times n$ matrix $\\hat{W}$\n\n$$\n\\hat{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n x_1 & y_1 & z_1 \\\\\n x_2 & y_2 & z_2 \\\\\n \\dots & \\dots & \\dots \\\\\n x_{n-2} & y_{n-2} & z_{n-2} \\\\\n x_{n-1} & y_{n-1} & z_{n-1}\n \\end{bmatrix},\n$$\n\n## More on the Covariance Matrix\n\nOur matrix is in turn converted into into the $3\\times 3$ covariance matrix\n$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can also calculate\nthe mean value of each set of samples $\\hat{x}$ etc using the Numpy\nfunction **np.mean(x)**. We can also extract the eigenvalues of the\ncovariance matrix through the **np.linalg.eig()** function.\n\n\n```python\n# Importing various packages\nimport numpy as np\n\nn = 100\nx = np.random.normal(size=n)\nprint(np.mean(x))\ny = 4+3*x+np.random.normal(size=n)\nprint(np.mean(y))\nz = x**3+np.random.normal(size=n)\nprint(np.mean(z))\nW = np.vstack((x, y, z))\nSigma = np.cov(W)\nprint(Sigma)\nEigvals, Eigvecs = np.linalg.eig(Sigma)\nprint(Eigvals)\n```\n\n## Practicalities, Reminder on Statistics\n\n\n\n## Brief Reminder on Statistical Analysis\nThe *probability distribution function (PDF)* is a function\n$p(x)$ on the domain which, in the discrete case, gives us the\nprobability or relative frequency with which these values of $X$ occur:\n\n$$\np(x) = \\mathrm{prob}(X=x)\n$$\n\nIn the continuous case, the PDF does not directly depict the\nactual probability. Instead we define the probability for the\nstochastic variable to assume any value on an infinitesimal interval\naround $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\nthe *density* of the probability rather than the probability\nitself. The probability for a stochastic variable to assume any value\non a non-infinitesimal interval $[a,\\,b]$ is then just the integral:\n\n$$\n\\mathrm{prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx\n$$\n\nQualitatively speaking, a stochastic variable represents the values of\nnumbers chosen as if by chance from some specified PDF so that the\nselection of a large set of these numbers reproduces this PDF.\n\n\n\n\n## Statistics, moments\nA particularly useful class of special expectation values are the\n*moments*. The $n$-th moment of the PDF $p$ is defined as\nfollows:\n\n$$\n\\langle x^n\\rangle \\equiv \\int\\! x^n p(x)\\,dx\n$$\n\nThe zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\nand often denoted by the letter $\\mu$:\n\n$$\n\\langle x\\rangle = \\mu \\equiv \\int\\! x p(x)\\,dx\n$$\n\n## Statistics, central moments\nA special version of the moments is the set of *central moments*,\nthe n-th central moment defined as:\n\n$$\n\\langle (x-\\langle x \\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n$$\n\nThe zero-th and first central moments are both trivial, equal $1$ and\n$0$, respectively. But the second central moment, known as the\n*variance* of $p$, is of particular interest. For the stochastic\nvariable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{var}(X)$:\n\n\n
\n\n$$\n\\begin{equation}\n\\sigma^2_X\\ \\ =\\ \\ \\mathrm{var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n\\int\\! (x-\\langle x\\rangle)^2 p(x)\\,dx\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\int\\! \\left(x^2 - 2 x \\langle x\\rangle^{2} +\n \\langle x\\rangle^2\\right)p(x)\\,dx\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n = \\langle x^2\\rangle - \\langle x\\rangle^2\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nThe square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square)\nvalue of the deviation of the PDF from its mean value, interpreted\nqualitatively as the *spread* of $p$ around its mean.\n\n\n\n## Statistics, covariance\nAnother important quantity is the so called covariance, a variant of\nthe above defined variance. Consider again the set $\\{X_i\\}$ of $n$\nstochastic variables (not necessarily uncorrelated) with the\nmultivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\nof the stochastic variables, $X_i$ and $X_j$, is defined as follows:\n\n$$\n\\mathrm{cov}(X_i,\\,X_j) \\equiv \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n\\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\n\\int\\!\\cdots\\!\\int\\!(x_i-\\langle x_i \\rangle)(x_j-\\langle x_j \\rangle)\\,\nP(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n\\label{eq:def_covariance} \\tag{5}\n\\end{equation}\n$$\n\nwith\n\n$$\n\\langle x_i\\rangle =\n\\int\\!\\cdots\\!\\int\\!x_i\\,P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n$$\n\n## Statistics, more covariance\nIf we consider the above covariance as a matrix $C_{ij}=\\mathrm{cov}(X_i,\\,X_j)$, then the diagonal elements are just the familiar\nvariances, $C_{ii} = \\mathrm{cov}(X_i,\\,X_i) = \\mathrm{var}(X_i)$. It turns out that\nall the off-diagonal elements are zero if the stochastic variables are\nuncorrelated. This is easy to show, keeping in mind the linearity of\nthe expectation value. Consider the stochastic variables $X_i$ and\n$X_j$, ($i\\neq j$):\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{cov}(X_i,\\,X_j) = \\langle(x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \n\\label{_auto6} \\tag{7}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j\\rangle +\n\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\n\\label{_auto7} \\tag{8}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n\\langle x_i\\rangle\\langle x_j\\rangle\n\\label{_auto8} \\tag{9}\n\\end{equation}\n$$\n\n\n
\n\n$$\n\\begin{equation} \n=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n\\label{_auto9} \\tag{10}\n\\end{equation}\n$$\n\n## Statistics, independent variables\nIf $X_i$ and $X_j$ are independent, we get \n$\\langle x_i x_j\\rangle =\\langle x_i\\rangle\\langle x_j\\rangle$, resulting in $\\mathrm{cov}(X_i, X_j) = 0\\ \\ (i\\neq j)$.\n\nAlso useful for us is the covariance of linear combinations of\nstochastic variables. Let $\\{X_i\\}$ and $\\{Y_i\\}$ be two sets of\nstochastic variables. Let also $\\{a_i\\}$ and $\\{b_i\\}$ be two sets of\nscalars. Consider the linear combination:\n\n$$\nU = \\sum_i a_i X_i \\qquad V = \\sum_j b_j Y_j\n$$\n\nBy the linearity of the expectation value\n\n$$\n\\mathrm{cov}(U, V) = \\sum_{i,j}a_i b_j \\mathrm{cov}(X_i, Y_j)\n$$\n\n## Statistics, more variance\nNow, since the variance is just $\\mathrm{var}(X_i) = \\mathrm{cov}(X_i, X_i)$, we get\nthe variance of the linear combination $U = \\sum_i a_i X_i$:\n\n\n
\n\n$$\n\\begin{equation}\n\\mathrm{var}(U) = \\sum_{i,j}a_i a_j \\mathrm{cov}(X_i, X_j)\n\\label{eq:variance_linear_combination} \\tag{11}\n\\end{equation}\n$$\n\nAnd in the special case when the stochastic variables are\nuncorrelated, the off-diagonal elements of the covariance are as we\nknow zero, resulting in:\n\n2\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\mathrm{var}(\\sum_i a_i X_i) = \\sum_i a_i^2 \\mathrm{var}(X_i)\n$$\n\nwhich will become very useful in our study of the error in the mean\nvalue of a set of measurements.\n\n\n\n## Statistics and stochastic processes\nA *stochastic process* is a process that produces sequentially a\nchain of values:\n\n$$\n\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n$$\n\nWe will call these\nvalues our *measurements* and the entire set as our measured\n*sample*. The action of measuring all the elements of a sample\nwe will call a stochastic *experiment* since, operationally,\nthey are often associated with results of empirical observation of\nsome physical or mathematical phenomena; precisely an experiment. We\nassume that these values are distributed according to some \nPDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\nstochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\ntrying to determine the full distribution $p$ we are often only\ninterested in finding the few lowest moments, like the mean\n$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n\n\n\n\n\n## Statistics and sample variables\nIn practical situations a sample is always of finite size. Let that\nsize be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows:\n\n$$\n\\bar{x}_n \\equiv \\frac{1}{n}\\sum_{k=1}^n x_k\n$$\n\nThe *sample variance* is:\n\n$$\n\\mathrm{var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar{x}_n)^2\n$$\n\nits square root being the *standard deviation of the sample*. The\n*sample covariance* is:\n\n$$\n\\mathrm{cov}(x)\\equiv\\frac{1}{n}\\sum_{kl}(x_k - \\bar{x}_n)(x_l - \\bar{x}_n)\n$$\n\n## Statistics, sample variance and covariance\nNote that the sample variance is the sample covariance without the\ncross terms. In a similar manner as the covariance in Eq. ([5](#eq:def_covariance)) is a measure of the correlation between\ntwo stochastic variables, the above defined sample covariance is a\nmeasure of the sequential correlation between succeeding measurements\nof a sample.\n\nThese quantities, being known experimental values, differ\nsignificantly from and must not be confused with the similarly named\nquantities for stochastic variables, mean $\\mu_X$, variance $\\mathrm{var}(X)$\nand covariance $\\mathrm{cov}(X,Y)$.\n\n\n\n## Statistics, law of large numbers\nThe law of large numbers\nstates that as the size of our sample grows to infinity, the sample\nmean approaches the true mean $\\mu_X^{\\phantom X}$ of the chosen PDF:\n\n$$\n\\lim_{n\\to\\infty}\\bar{x}_n = \\mu_X^{\\phantom X}\n$$\n\nThe sample mean $\\bar{x}_n$ works therefore as an estimate of the true\nmean $\\mu_X^{\\phantom X}$.\n\nWhat we need to find out is how good an approximation $\\bar{x}_n$ is to\n$\\mu_X^{\\phantom X}$. In any stochastic measurement, an estimated\nmean is of no use to us without a measure of its error. A quantity\nthat tells us how well we can reproduce it in another experiment. We\nare therefore interested in the PDF of the sample mean itself. Its\nstandard deviation will be a measure of the spread of sample means,\nand we will simply call it the *error* of the sample mean, or\njust sample error, and denote it by $\\mathrm{err}_X^{\\phantom X}$. In\npractice, we will only be able to produce an *estimate* of the\nsample error since the exact value would require the knowledge of the\ntrue PDFs behind, which we usually do not have.\n\n\n\n\n## Statistics, more on sample error\nLet us first take a look at what happens to the sample error as the\nsize of the sample grows. In a sample, each of the measurements $x_i$\ncan be associated with its own stochastic variable $X_i$. The\nstochastic variable $\\overline X_n$ for the sample mean $\\bar{x}_n$ is\nthen just a linear combination, already familiar to us:\n\n$$\n\\overline X_n = \\frac{1}{n}\\sum_{i=1}^n X_i\n$$\n\nAll the coefficients are just equal $1/n$. The PDF of $\\overline X_n$,\ndenoted by $p_{\\overline X_n}(x)$ is the desired PDF of the sample\nmeans.\n\n\n\n## Statistics\nThe probability density of obtaining a sample mean $\\bar x_n$\nis the product of probabilities of obtaining arbitrary values $x_1,\nx_2,\\dots,x_n$ with the constraint that the mean of the set $\\{x_i\\}$\nis $\\bar x_n$:\n\n$$\np_{\\overline X_n}(x) = \\int p_X^{\\phantom X}(x_1)\\cdots\n\\int p_X^{\\phantom X}(x_n)\\ \n\\delta\\!\\left(x - \\frac{x_1+x_2+\\dots+x_n}{n}\\right)dx_n \\cdots dx_1\n$$\n\nAnd in particular we are interested in its variance $\\mathrm{var}(\\overline X_n)$.\n\n\n\n\n\n## Statistics, central limit theorem\nIt is generally not possible to express $p_{\\overline X_n}(x)$ in a\nclosed form given an arbitrary PDF $p_X^{\\phantom X}$ and a number\n$n$. But for the limit $n\\to\\infty$ it is possible to make an\napproximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity,\n$p_{\\overline X_n}(x)$ approaches a Gaussian distribution whose mean\nand variance equal the true mean and variance, $\\mu_{X}^{\\phantom X}$\nand $\\sigma_{X}^{2}$, respectively:\n\n\n
\n\n$$\n\\begin{equation}\n\\lim_{n\\to\\infty} p_{\\overline X_n}(x) =\n\\left(\\frac{n}{2\\pi\\mathrm{var}(X)}\\right)^{1/2}\ne^{-\\frac{n(x-\\bar x_n)^2}{2\\mathrm{var}(X)}}\n\\label{eq:central_limit_gaussian} \\tag{12}\n\\end{equation}\n$$\n\n## Covariance example\n\nSuppose we have defined three vectors $\\boldsymbol{x}, \\boldsymbol{y}, \\boldsymbol{z}$ with\n$n$ elements each. The covariance matrix is defined as\n\n$$\n\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz}\n \\end{bmatrix},\n$$\n\nwhere for example\n\n$$\n\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n$$\n\nThe Numpy function **np.cov** calculates the covariance elements using\nthe factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\nthe exact mean values.\n\nThe following simple function uses the **np.vstack** function which\ntakes each vector of dimension $1\\times n$ and produces a $3\\times n$\nmatrix $\\boldsymbol{W}$\n\n$$\n\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n x_1 & y_1 & z_1 \\\\\n x_2 & y_2 & z_2 \\\\\n \\dots & \\dots & \\dots \\\\\n x_{n-2} & y_{n-2} & z_{n-2} \\\\\n x_{n-1} & y_{n-1} & z_{n-1}\n \\end{bmatrix},\n$$\n\nwhich in turn is converted into into the $3\\times 3$ covariance matrix\n$\\boldsymbol{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can\nalso calculate the mean value of each set of samples $\\boldsymbol{x}$ etc\nusing the Numpy function **np.mean(x)**. We can also extract the\neigenvalues of the covariance matrix through the **np.linalg.eig()**\nfunction.\n\n\n## Covariance in numpy\n\n\n```python\n# Importing various packages\nimport numpy as np\n\nn = 100\nx = np.random.normal(size=n)\nprint(np.mean(x))\ny = 4+3*x+np.random.normal(size=n)\nprint(np.mean(y))\nz = x**3+np.random.normal(size=n)\nprint(np.mean(z))\nW = np.vstack((x, y, z))\nSigma = np.cov(W)\nprint(Sigma)\n```\n\n## Practicalities, Useful Python Packages\n\n\n## Meet the Pandas\n\n\n\n\n\n

\n\n\n\n\n\nAnother useful Python package is\n[pandas](https://pandas.pydata.org/), which is an open source library\nproviding high-performance, easy-to-use data structures and data\nanalysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n\nThe following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data.\n\n\n```python\nimport pandas as pd\nfrom IPython.display import display\ndata = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n }\ndata_pandas = pd.DataFrame(data)\ndisplay(data_pandas)\n```\n\n## Data Frames in Pandas\n\nIn the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\nand reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\nDisplaying these results, we see that the indices are given by the default numbers from zero to three.\n**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as\n\n\n```python\ndata_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\ndisplay(data_pandas)\n```\n\nThereafter we display the content of the row which begins with the index **Aragorn**\n\n\n```python\ndisplay(data_pandas.loc['Aragorn'])\n```\n\nWe can easily append data to this, for example\n\n\n```python\nnew_hobbit = {'First Name': [\"Peregrin\"],\n 'Last Name': [\"Took\"],\n 'Place of birth': [\"Shire\"],\n 'Date of Birth T.A.': [2990]\n }\ndata_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\ndisplay(data_pandas)\n```\n\n## More Pandas\n\nHere are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \nof dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display\nnp.random.seed(100)\n# setting up a 10 x 5 matrix\nrows = 10\ncols = 5\na = np.random.randn(rows,cols)\ndf = pd.DataFrame(a)\ndisplay(df)\nprint(df.mean())\nprint(df.std())\ndisplay(df**2)\n```\n\nThereafter we can select specific columns only and plot final results\n\n\n```python\ndf.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\ndf.index = np.arange(10)\n\ndisplay(df)\nprint(df['Second'].mean() )\nprint(df.info())\nprint(df.describe())\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndf.cumsum().plot(lw=2.0, figsize=(10,6))\nplt.show()\n\n\ndf.plot.bar(figsize=(10,6), rot=15)\nplt.show()\n```\n\nWe can produce a $4\\times 4$ matrix\n\n\n```python\nb = np.arange(16).reshape((4,4))\nprint(b)\ndf1 = pd.DataFrame(b)\nprint(df1)\n```\n\nand many other operations. \n\n\n## Pandas Series\n\n\nThe **Series** class is another important class included in\n**pandas**. You can view it as a specialization of **DataFrame** but where\nwe have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\nmost operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\nAs we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\nFor multidimensional arrays, we also recommend [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**. \n\n\n\n\n## Our first Machine Learning Encounter\n\n## Reading Data and Fitting\n\nIn order to study various Machine Learning algorithms, we need to\naccess data. Acccessing data is an essential step in all machine\nlearning algorithms. In particular, setting up the so-called **design\nmatrix** (to be defined below) is often the first element we need in\norder to perform our calculations. To set up the design matrix means\nreading (and later, when the calculations are done, writing) data\nin various formats, The formats span from reading files from disk,\nloading data from databases and interacting with online sources\nlike web application programming interfaces (APIs).\n\nIn handling various input formats, as discussed above, we will often stay with **pandas**,\na Python package which allows us, in a seamless and painless way, to\ndeal with a multitude of formats, from standard **csv** (comma separated\nvalues) files, via **excel**, **html** to **hdf5** formats. With **pandas**\nand the **DataFrame** and **Series** functionalities we are able to convert text data\ninto the calculational formats we need for a specific algorithm. And our code is going to be \npretty close the basic mathematical expressions.\n\nOur first data set is going to be a classic from nuclear physics, namely all\navailable data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. \n\nWe will show some of the\nstrengths of packages like **Scikit-Learn** in fitting nuclear binding energies to\nspecific functions using linear regression first. Then, as a teaser, we will show you how \nyou can easily implement other algorithms like decision trees and random forests and neural networks.\n\nBut before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as,\n(don't be offended) fitting straight lines!\n\n## Simple linear regression model using **scikit-learn**\n\nWe start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n\nWhat follows is a simple Python code where we have defined a function\n$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \nThe numbers in the vector $\\hat{x}$ are given\nby random numbers generated with a uniform distribution with entries\n$x_i \\in [0,1]$ (more about probability distribution functions\nlater). These values are then used to define a function $y(x)$\n(tabulated again as a vector) with a linear dependence on $x$ plus a\nrandom noise added via the normal distribution.\n\n\n## Simple linear regression model using **scikit-learn**, Numpy functions\n\nThe Numpy functions are imported used the **import numpy as np**\nstatement and the random number generator for the uniform distribution\nis called using the function **np.random.rand()**, where we specificy\nthat we want $100$ random variables. Using Numpy we define\nautomatically an array with the specified number of elements, $100$ in\nour case. With the Numpy function **randn()** we can compute random\nnumbers with the normal distribution (mean value $\\mu$ equal to zero and\nvariance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\ndependence as function of $x$\n\n$$\ny = 2x+N(0,1),\n$$\n\nwhere $N(0,1)$ represents random numbers generated by the normal\ndistribution. From **Scikit-Learn** we import then the\n**LinearRegression** functionality and make a prediction $\\tilde{y} =\n\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\ndata $(\\hat{x},\\hat{y})$ for our training data. The Python package\n**scikit-learn** has also a functionality which extracts the above\nfitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\ndistinguish between training data and test data.\n\n## Simple linear regression model using **scikit-learn**, Matplotlib\n\nFor plotting we use the Python package\n[matplotlib](https://matplotlib.org/) which produces publication\nquality figures. Feel free to explore the extensive\n[gallery](https://matplotlib.org/gallery/index.html) of examples. In\nthis example we plot our original values of $x$ and $y$ as well as the\nprediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\ndata with a straight line.\n\nThe Python code follows here.\n\n\n```python\n%matplotlib inline\n\n# Importing various packages\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\nx = np.random.rand(100,1)\ny = 2*x+np.random.randn(100,1)\nlinreg = LinearRegression()\nlinreg.fit(x,y)\nxnew = np.array([[0],[1]])\nypredict = linreg.predict(xnew)\n\nplt.plot(xnew, ypredict, \"r-\")\nplt.plot(x, y ,'ro')\nplt.axis([0,1.0,0, 5.0])\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\nplt.title(r'Simple Linear Regression')\nplt.show()\n```\n\n## Simple linear regression model, what to expect\n\nThis example serves several aims. It allows us to demonstrate several\naspects of data analysis and later machine learning algorithms. The\nimmediate visualization shows that our linear fit is not\nimpressive. It goes through the data points, but there are many\noutliers which are not reproduced by our linear regression. We could\nnow play around with this small program and change for example the\nfactor in front of $x$ and the normal distribution. Try to change the\nfunction $y$ to\n\n$$\ny = 10x+0.01 \\times N(0,1),\n$$\n\nwhere $x$ is defined as before. Does the fit look better? Indeed, by\nreducing the role of the noise given by the normal distribution we see immediately that\nour linear prediction seemingly reproduces better the training\nset. However, this testing 'by the eye' is obviouly not satisfactory in the\nlong run. Here we have only defined the training data and our model, and \nhave not discussed a more rigorous approach to the **cost** function.\n\n\n## Simple linear regression model, how to evaluate the model\n\nWe need more rigorous criteria in defining whether we have succeeded or\nnot in modeling our training data. You will be surprised to see that\nmany scientists seldomly venture beyond this 'by the eye' approach. A\nstandard approach for the *cost* function is the so-called $\\chi^2$\nfunction (a variant of the mean-squared error (MSE))\n\n$$\n\\chi^2 = \\frac{1}{n}\n\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n$$\n\nwhere $\\sigma_i^2$ is the variance (to be defined later) of the entry\n$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\nhowever the aim of scaling the equations and make the cost function\ndimensionless. \n\n## Our first Cost/Loss function encounter\n\nMinimizing the cost function is a central aspect of\nour discussions to come. Finding its minima as function of the model\nparameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\ntheme in these series of lectures. Essentially all machine learning\nalgorithms we will discuss center around the minimization of the\nchosen cost function. This depends in turn on our specific\nmodel for describing the data, a typical situation in supervised\nlearning. Automatizing the search for the minima of the cost function is a\ncentral ingredient in all algorithms. Typical methods which are\nemployed are various variants of **gradient** methods. These will be\ndiscussed in more detail later. Again, you'll be surprised to hear that\nmany practitioners minimize the above function ''by the eye', popularly dubbed as \n'chi by the eye'. That is, change a parameter and see (visually and numerically) that \nthe $\\chi^2$ function becomes smaller. \n\n## Our first Cost/Loss function encounter\n\nThe terms cost and loss functions are often synonymous, sometimes you will also encounter the usage error function.\nThe more general scenario is to define an objective function first, which we want to optimize.\nIt is common to see statements like this however: **The loss function computes the error for a single training example, while the cost function is the average of the loss functions of the entire training set**.\n\n## Our first Cost/Loss function encounter, how do we define them?\n\n\nThere are many ways to define the cost/loss function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \nthe relative error (why would we prefer the MSE instead of the relative error?) as\n\n$$\n\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n$$\n\nThe squared cost function results in an arithmetic mean-unbiased\nestimator, and the absolute-value cost function results in a\nmedian-unbiased estimator (in the one-dimensional case, and a\ngeometric median-unbiased estimator for the multi-dimensional\ncase). The squared cost function has the disadvantage that it has the tendency\nto be dominated by outliers.\n\nWe can modify easily the above Python code and plot the relative error instead\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\nx = np.random.rand(100,1)\ny = 5*x+0.01*np.random.randn(100,1)\nlinreg = LinearRegression()\nlinreg.fit(x,y)\nypredict = linreg.predict(x)\n\nplt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\nplt.axis([0,1.0,0.0, 0.5])\nplt.xlabel(r'$x$')\nplt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\nplt.title(r'Relative error')\nplt.show()\n```\n\nDepending on the parameter in front of the normal distribution, we may\nhave a small or larger relative error. Try to play around with\ndifferent training data sets and study (graphically) the value of the\nrelative error.\n\n## **Scikit-Learn** functionality\n\n\nAs mentioned above, **Scikit-Learn** has an impressive functionality.\nWe can for example extract the values of $\\alpha$ and $\\beta$ and\ntheir error estimates, or the variance and standard deviation and many\nother properties from the statistical data analysis. \n\n\nHere we show an\nexample of the functionality of **Scikit-Learn**.\n\n\n```python\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom sklearn.linear_model import LinearRegression \nfrom sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n\nx = np.random.rand(100,1)\ny = 2.0+ 5*x+0.5*np.random.randn(100,1)\nlinreg = LinearRegression()\nlinreg.fit(x,y)\nypredict = linreg.predict(x)\nprint('The intercept alpha: \\n', linreg.intercept_)\nprint('Coefficient beta : \\n', linreg.coef_)\n# The mean squared error \nprint(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n# Explained variance score: 1 is perfect prediction \nprint('Variance score: %.2f' % r2_score(y, ypredict))\n# Mean squared log error \nprint('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n# Mean absolute error \nprint('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\nplt.plot(x, ypredict, \"r-\")\nplt.plot(x, y ,'ro')\nplt.axis([0.0,1.0,1.5, 7.0])\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\nplt.title(r'Linear Regression fit ')\nplt.show()\n```\n\nThe function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as\n\n$$\nMSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n$$\n\nThe smaller the value, the better the fit. Ideally we would like to\nhave an MSE equal zero. The attentive reader has probably recognized\nthis function as being similar to the $\\chi^2$ function defined above.\n\nThe **r2score** function computes $R^2$, the coefficient of\ndetermination. It provides a measure of how well future samples are\nlikely to be predicted by the model. Best possible score is 1.0 and it\ncan be negative (because the model can be arbitrarily worse). A\nconstant model that always predicts the expected value of $\\hat{y}$,\ndisregarding the input features, would get a $R^2$ score of $0.0$.\n\nIf $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as\n\n$$\nR^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n$$\n\nwhere we have defined the mean value of $\\hat{y}$ as\n\n$$\n\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n$$\n\nAnother quantity taht we will meet again in our discussions of regression analysis is \n the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\nThe MAE is defined as follows\n\n$$\n\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n$$\n\nWe present the \nsquared logarithmic (quadratic) error\n\n$$\n\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n$$\n\nwhere $\\log_e (x)$ stands for the natural logarithm of $x$. This error\nestimate is best to use when targets having exponential growth, such\nas population counts, average sales of a commodity over a span of\nyears etc. \n\n\nFinally, another cost function is the Huber cost function used in robust regression.\n\nThe rationale behind this possible cost function is its reduced\nsensitivity to outliers in the data set. In our discussions on\ndimensionality reduction and normalization of data we will meet other\nways of dealing with outliers.\n\nThe Huber cost function is defined as\n\n$$\nH_{\\delta}(a)=\\begin{bmatrix}\\frac {1}{2}}{a^{2}}&{\\text{for }}|a|\\leq \\delta ,\\\\\\delta (|a|-{\\frac {1}{2}}\\delta ),&{\\text{otherwise.}}\\end{bmatrix}.\n$$\n\nHere $a=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\nWe will discuss in more\ndetail these and other functions in the various lectures.\n\n## Cubic Polynomial\nWe conclude this part with another example. Instead of \na linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn.\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LinearRegression\n\nx=np.linspace(0.02,0.98,200)\nnoise = np.asarray(random.sample((range(200)),200))\ny=x**3*noise\nyn=x**3*100\npoly3 = PolynomialFeatures(degree=3)\nX = poly3.fit_transform(x[:,np.newaxis])\nclf3 = LinearRegression()\nclf3.fit(X,y)\n\nXplot=poly3.fit_transform(x[:,np.newaxis])\npoly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\nplt.plot(x,yn, color='red', label=\"True Cubic\")\nplt.scatter(x, y, label='Data', color='orange', s=15)\nplt.legend()\nplt.show()\n\ndef error(a):\n for i in y:\n err=(y-yn)/yn\n return abs(np.sum(err))/len(err)\n\nprint (error(y))\n```\n\n## Getting more serious, fitting Nuclear Binding Energies\n\n\n## To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n\nLet us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\nenergies. A basic quantity which can be measured for the ground\nstates of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\natomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n\nAtomic masses are usually tabulated in terms of the mass excess defined by\n\n$$\n\\Delta M(N, Z) = M(N, Z) - uA,\n$$\n\nwhere $u$ is the Atomic Mass Unit\n\n$$\nu = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n$$\n\nThe nucleon masses are\n\n$$\nm_p = 1.00727646693(9)u,\n$$\n\nand\n\n$$\nm_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n$$\n\nIn the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\nthere are data on masses and decays of 3437 nuclei.\n\nThe nuclear binding energy is defined as the energy required to break\nup a given nucleus into its constituent parts of $N$ neutrons and $Z$\nprotons. In terms of the atomic masses $M(N, Z)$ the binding energy is\ndefined by\n\n$$\nBE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n$$\n\nwhere $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\nIn terms of the mass excess the binding energy is given by\n\n$$\nBE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n$$\n\nwhere $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n\n\nA popular and physically intuitive model which can be used to parametrize \nthe experimental binding energies as function of $A$, is the so-called \n**liquid drop model**. The ansatz is based on the following expression\n\n$$\nBE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n$$\n\nwhere $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \nto the experimental data. \n\n\n\n\nTo arrive at the above expression we have assumed that we can make the following assumptions:\n\n * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n\n * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n\n * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n\n * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n\nWe could also add a so-called pairing term, which is a correction term that\narises from the tendency of proton pairs and neutron pairs to\noccur. An even number of particles is more stable than an odd number. \n\n\n### Organizing our data\n\nLet us start with reading and organizing our data. \nWe start with the compilation of masses and binding energies from 2016.\nAfter having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n\n\nWe start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**.\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sklearn.linear_model as skl\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\ninfile = open(data_path(\"MassEval2016.dat\"),'r')\n```\n\nOur next step is to read the data on experimental binding energies and\nreorganize them as functions of the mass number $A$, the number of\nprotons $Z$ and neutrons $N$ using **pandas**. Before we do this it is\nalways useful (unless you have a binary file or other types of compressed\ndata) to actually open the file and simply take a look at it!\n\n\nIn particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information.\n\n\n```python\n\"\"\" \nThis is taken from the data file of the mass 2016 evaluation. \nAll files are 3436 lines long with 124 character per line. \n Headers are 39 lines long. \n col 1 : Fortran character control: 1 = page feed 0 = line feed \n format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n These formats are reflected in the pandas widths variable below, see the statement \n widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n Pandas has also a variable header, with length 39 in this case. \n\"\"\"\n```\n\nThe data we are interested in are in columns 2, 3, 4 and 11, giving us\nthe number of neutrons, protons, mass numbers and binding energies,\nrespectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will\ncovert them into the **pandas** DataFrame structure.\n\n\n```python\n# Read the experimental data with Pandas\nMasses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n header=39,\n index_col=False)\n\n# Extrapolated values are indicated by '#' in place of the decimal place, so\n# the Ebinding column won't be numeric. Coerce to float and drop these entries.\nMasses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\nMasses = Masses.dropna()\n# Convert from keV to MeV.\nMasses['Ebinding'] /= 1000\n\n# Group the DataFrame by nucleon number, A.\nMasses = Masses.groupby('A')\n# Find the rows of the grouped DataFrame with the maximum binding energy.\nMasses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n```\n\nWe have now read in the data, grouped them according to the variables we are interested in. \nWe see how easy it is to reorganize the data using **pandas**. If we\nwere to do these operations in C/C++ or Fortran, we would have had to\nwrite various functions/subroutines which perform the above\nreorganizations for us. Having reorganized the data, we can now start\nto make some simple fits using both the functionalities in **numpy** and\n**Scikit-Learn** afterwards. \n\nNow we define five variables which contain\nthe number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves.\n\n\n```python\nA = Masses['A']\nZ = Masses['Z']\nN = Masses['N']\nElement = Masses['Element']\nEnergies = Masses['Ebinding']\nprint(Masses)\n```\n\nThe next step, and we will define this mathematically later, is to set up the so-called **design/feature matrix**. We will throughout label this matrix as $\\boldsymbol{X}$.\nIt has dimensionality $n\\times p$, where $n$ is the number of data points and $p$ are the so-called features/predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit.\n\n\n```python\n# Now we set up the design matrix X\nX = np.zeros((len(A),5))\nX[:,0] = 1\nX[:,1] = A\nX[:,2] = A**(2.0/3.0)\nX[:,3] = A**(-1.0/3.0)\nX[:,4] = A**(-1.0)\n```\n\nWith **scikitlearn** we are now ready to use linear regression and fit our data.\n\n\n```python\nclf = skl.LinearRegression().fit(X, Energies)\nfity = clf.predict(X)\n```\n\nPretty simple! \n\nNow we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data.\n\n\n```python\n# The mean squared error \nprint(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n# Explained variance score: 1 is perfect prediction \nprint('Variance score: %.2f' % r2_score(Energies, fity))\n# Mean absolute error \nprint('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\nprint(clf.coef_, clf.intercept_)\n\nMasses['Eapprox'] = fity\n# Generate a plot comparing the experimental with the fitted values values.\nfig, ax = plt.subplots()\nax.set_xlabel(r'$A = N + Z$')\nax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\nax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n label='Ame2016')\nax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n label='Fit')\nax.legend()\nsave_fig(\"Masses2016\")\nplt.show()\n```\n\n### Seeing the wood for the trees\n\nAs a teaser, let us now see how we can do this with decision trees using **scikit-learn**. We will discuss the method in more details later.\n\n\n```python\n\n#Decision Tree Regression\nfrom sklearn.tree import DecisionTreeRegressor\nregr_1=DecisionTreeRegressor(max_depth=5)\nregr_2=DecisionTreeRegressor(max_depth=7)\nregr_3=DecisionTreeRegressor(max_depth=9)\nregr_1.fit(X, Energies)\nregr_2.fit(X, Energies)\nregr_3.fit(X, Energies)\n\n\ny_1 = regr_1.predict(X)\ny_2 = regr_2.predict(X)\ny_3=regr_3.predict(X)\nMasses['Eapprox'] = y_3\n# Plot the results\nplt.figure()\nplt.plot(A, Energies, color=\"blue\", label=\"Data\", linewidth=2)\nplt.plot(A, y_1, color=\"red\", label=\"max_depth=5\", linewidth=2)\nplt.plot(A, y_2, color=\"green\", label=\"max_depth=7\", linewidth=2)\nplt.plot(A, y_3, color=\"m\", label=\"max_depth=9\", linewidth=2)\n\nplt.xlabel(\"$A$\")\nplt.ylabel(\"$E$[MeV]\")\nplt.title(\"Decision Tree Regression\")\nplt.legend()\nsave_fig(\"Masses2016Trees\")\nplt.show()\nprint(Masses)\nprint(np.mean( (Energies-y_1)**2))\n```\n\n### And what about using neural networks?\n\nThe **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \nfunctionality.\n\n\n```python\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import accuracy_score\nimport seaborn as sns\n\nX_train = X\nY_train = Energies\nn_hidden_neurons = 100\nepochs = 100\n# store models for later use\neta_vals = np.logspace(-5, 1, 7)\nlmbd_vals = np.logspace(-5, 1, 7)\n# store the models for later use\nDNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\ntrain_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\nsns.set()\nfor i, eta in enumerate(eta_vals):\n for j, lmbd in enumerate(lmbd_vals):\n dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n dnn.fit(X_train, Y_train)\n DNN_scikit[i][j] = dnn\n train_accuracy[i][j] = dnn.score(X_train, Y_train)\n\nfig, ax = plt.subplots(figsize = (10, 10))\nsns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\nax.set_title(\"Training Accuracy\")\nax.set_ylabel(\"$\\eta$\")\nax.set_xlabel(\"$\\lambda$\")\nplt.show()\n```\n\n## More on flexibility with pandas and xarray\n\nLet us study the $Q$ values associated with the removal of one or two nucleons from\na nucleus. These are conventionally defined in terms of the one-nucleon and two-nucleon\nseparation energies. With the functionality in **pandas**, two to three lines of code will allow us to plot the separation energies.\nThe neutron separation energy is defined as\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nand the proton separation energy reads\n\n$$\nS_p= -Q_p= BE(N,Z)-BE(N,Z-1).\n$$\n\nThe two-neutron separation energy is defined as\n\n$$\nS_{2n}= -Q_{2n}= BE(N,Z)-BE(N-2,Z),\n$$\n\nand the two-proton separation energy is given by\n\n$$\nS_{2p}= -Q_{2p}= BE(N,Z)-BE(N,Z-2).\n$$\n\nUsing say the neutron separation energies (alternatively the proton separation energies)\n\n$$\nS_n= -Q_n= BE(N,Z)-BE(N-1,Z),\n$$\n\nwe can define the so-called energy gap for neutrons (or protons) as\n\n$$\n\\Delta S_n= BE(N,Z)-BE(N-1,Z)-\\left(BE(N+1,Z)-BE(N,Z)\\right),\n$$\n\nor\n\n$$\n\\Delta S_n= 2BE(N,Z)-BE(N-1,Z)-BE(N+1,Z).\n$$\n\nThis quantity can in turn be used to determine which nuclei could be interpreted as magic or not. \nFor protons we would have\n\n$$\n\\Delta S_p= 2BE(N,Z)-BE(N,Z-1)-BE(N,Z+1).\n$$\n\nTo calculate say the neutron separation we need to multiply our masses with the nucleon number $A$ (why?).\nThereafter we pick the oxygen isotopes and simply compute the separation energies with two lines of code (note that most of the code here is a repeat of what you have seen before).\n\n\n```python\n# Common imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\ndef MakePlot(x,y, styles, labels, axlabels):\n plt.figure(figsize=(10,6))\n for i in range(len(x)):\n plt.plot(x[i], y[i], styles[i], label = labels[i])\n plt.xlabel(axlabels[0])\n plt.ylabel(axlabels[1])\n plt.legend(loc=0)\n\n\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\ninfile = open(data_path(\"MassEval2016.dat\"),'r')\n\n\n# Read the experimental data with Pandas\nMasses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n header=39,\n index_col=False)\n\n# Extrapolated values are indicated by '#' in place of the decimal place, so\n# the Ebinding column won't be numeric. Coerce to float and drop these entries.\nMasses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\nMasses = Masses.dropna()\n# Convert from keV to MeV.\nMasses['Ebinding'] /= 1000\nA = Masses['A']\nZ = Masses['Z']\nN = Masses['N']\nElement = Masses['Element']\nEnergies = Masses['Ebinding']*A\n\ndf = pd.DataFrame({'A':A,'Z':Z, 'N':N,'Element':Element,'Energies':Energies})\n# Her we pick the oyxgen isotopes\nNucleus = df.loc[lambda df: df.Z==8, :]\n# drop cases with no number\nNucleus = Nucleus.dropna()\n# Here we do the magic and obtain the neutron separation energies, one line of code!!\nNucleus['NeutronSeparationEnergies'] = Nucleus['Energies'].diff(+1)\nprint(Nucleus)\nMakePlot([Nucleus.A], [Nucleus.NeutronSeparationEnergies], ['b'], ['Neutron Separation Energy'], ['$A$','$S_n$'])\nsave_fig('Nucleus')\nplt.show()\n```\n", "meta": {"hexsha": "28242eb307660447677275d4eacf17a17b496972", "size": 112871, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/Introduction/ipynb/.ipynb_checkpoints/Introduction-checkpoint.ipynb", "max_stars_repo_name": "esleon97/MachineLearningECT", "max_stars_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 59, "max_stars_repo_stars_event_min_datetime": "2019-12-06T09:24:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T03:27:28.000Z", "max_issues_repo_path": "doc/pub/Introduction/ipynb/.ipynb_checkpoints/Introduction-checkpoint.ipynb", "max_issues_repo_name": "esleon97/MachineLearningECT", "max_issues_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-06-16T18:24:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-08T21:13:56.000Z", "max_forks_repo_path": "doc/pub/Introduction/ipynb/.ipynb_checkpoints/Introduction-checkpoint.ipynb", "max_forks_repo_name": "esleon97/MachineLearningECT", "max_forks_repo_head_hexsha": "97a218c9742b43a53e033a888f8a0b1074a2c48b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2019-11-30T00:37:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T21:30:09.000Z", "avg_line_length": 37.189785832, "max_line_length": 417, "alphanum_fraction": 0.5886188658, "converted": true, "num_tokens": 20977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.17864913658875853}} {"text": "# Lambda School Data Science Module 143\n\n## Introduction to Bayesian Inference\n\n!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_vs_bayesians.png)\n\n*[XKCD 1132](https://www.xkcd.com/1132/)*\n\n\n## Prepare - Bayes' Theorem and the Bayesian mindset\n\nBayes' theorem possesses a near-mythical quality - a bit of math that somehow magically evaluates a situation. But this mythicalness has more to do with its reputation and advanced applications than the actual core of it - deriving it is actually remarkably straightforward.\n\n### The Law of Total Probability\n\nBy definition, the total probability of all outcomes (events) if some variable (event space) $A$ is 1. That is:\n\n$$P(A) = \\sum_n P(A_n) = 1$$\n\nThe law of total probability takes this further, considering two variables ($A$ and $B$) and relating their marginal probabilities (their likelihoods considered independently, without reference to one another) and their conditional probabilities (their likelihoods considered jointly). A marginal probability is simply notated as e.g. $P(A)$, while a conditional probability is notated $P(A|B)$, which reads \"probability of $A$ *given* $B$\".\n\nThe law of total probability states:\n\n$$P(A) = \\sum_n P(A | B_n) P(B_n)$$\n\nIn words - the total probability of $A$ is equal to the sum of the conditional probability of $A$ on any given event $B_n$ times the probability of that event $B_n$, and summed over all possible events in $B$.\n\n### The Law of Conditional Probability\n\nWhat's the probability of something conditioned on something else? To determine this we have to go back to set theory and think about the intersection of sets:\n\nThe formula for actual calculation:\n\n$$P(A|B) = \\frac{P(A \\cap B)}{P(B)}$$\n\n\n\nThink of the overall rectangle as the whole probability space, $A$ as the left circle, $B$ as the right circle, and their intersection as the red area. Try to visualize the ratio being described in the above formula, and how it is different from just the $P(A)$ (not conditioned on $B$).\n\nWe can see how this relates back to the law of total probability - multiply both sides by $P(B)$ and you get $P(A|B)P(B) = P(A \\cap B)$ - replaced back into the law of total probability we get $P(A) = \\sum_n P(A \\cap B_n)$.\n\nThis may not seem like an improvement at first, but try to relate it back to the above picture - if you think of sets as physical objects, we're saying that the total probability of $A$ given $B$ is all the little pieces of it intersected with $B$, added together. The conditional probability is then just that again, but divided by the probability of $B$ itself happening in the first place.\n\n### Bayes Theorem\n\nHere is is, the seemingly magic tool:\n\n$$P(A|B) = \\frac{P(B|A)P(A)}{P(B)}$$\n\nIn words - the probability of $A$ conditioned on $B$ is the probability of $B$ conditioned on $A$, times the probability of $A$ and divided by the probability of $B$. These unconditioned probabilities are referred to as \"prior beliefs\", and the conditioned probabilities as \"updated.\"\n\nWhy is this important? Scroll back up to the XKCD example - the Bayesian statistician draws a less absurd conclusion because their prior belief in the likelihood that the sun will go nova is extremely low. So, even when updated based on evidence from a detector that is $35/36 = 0.972$ accurate, the prior belief doesn't shift enough to change their overall opinion.\n\nThere's many examples of Bayes' theorem - one less absurd example is to apply to [breathalyzer tests](https://www.bayestheorem.net/breathalyzer-example/). You may think that a breathalyzer test that is 100% accurate for true positives (detecting somebody who is drunk) is pretty good, but what if it also has 8% false positives (indicating somebody is drunk when they're not)? And furthermore, the rate of drunk driving (and thus our prior belief) is 1/1000.\n\nWhat is the likelihood somebody really is drunk if they test positive? Some may guess it's 92% - the difference between the true positives and the false positives. But we have a prior belief of the background/true rate of drunk driving. Sounds like a job for Bayes' theorem!\n\n$$\n\\begin{aligned}\nP(Drunk | Positive) &= \\frac{P(Positive | Drunk)P(Drunk)}{P(Positive)} \\\\\n&= \\frac{1 \\times 0.001}{0.08} \\\\\n&= 0.0125\n\\end{aligned}\n$$\n\nIn other words, the likelihood that somebody is drunk given they tested positive with a breathalyzer in this situation is only 1.25% - probably much lower than you'd guess. This is why, in practice, it's important to have a repeated test to confirm (the probability of two false positives in a row is $0.08 * 0.08 = 0.0064$, much lower), and Bayes' theorem has been relevant in court cases where proper consideration of evidence was important.\n\nQuick Derivation\n\n\\begin{align}\nP(A|B) &= \\frac{P(A \\cap B)}{P(B)}\\\\\n\\Rightarrow P(A|B)P(B) &= P(A \\cap B)\\\\\nP(B|A) &= \\frac{P(B \\cap A)}{P(A)}\\\\\n\\Rightarrow P(B|A)P(A) &= P(B \\cap A)\\\\\n\\Rightarrow P(A|B)P(B) &= P(B|A)P(A) \\\\\nP(A \\cap B) &= P(B \\cap A)\\\\\nP(A|B) &= \\frac{P(B|A) \\times P(A)}{P(B)}\n\\end{align}\n\n## Live Lecture - Deriving Bayes' Theorem, Calculating Bayesian Confidence\n\nNotice that $P(A|B)$ appears in the above laws - in Bayesian terms, this is the belief in $A$ updated for the evidence $B$. So all we need to do is solve for this term to derive Bayes' theorem. Let's do it together!\n\n\n```python\n# Activity 2 - Use SciPy to calculate Bayesian confidence intervals\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bayes_mvs.html#scipy.stats.bayes_mvs\n```\n\n\n```python\nfrom scipy import stats\nimport numpy as np\n```\n\n\n```python\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=0.5, size=5)\nprint(coinflips)\n```\n\n [0 1 1 1 0]\n\n\n\n```python\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean, mean-interval, mean+interval)\n```\n\n\n```python\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.6, -0.08008738065825705, 1.280087380658257)\n\n\n\n\n```python\nstats.bayes_mvs(coinflips, alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.6, minmax=(-0.08008738065825705, 1.280087380658257)),\n Variance(statistic=0.6000000000000001, minmax=(0.10768815552261896, 2.4771965946428014)),\n Std_dev(statistic=0.6864684246478268, minmax=(0.3281587352526502, 1.573911241030701)))\n\n\n\n\n```python\n\n```\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n\n```python\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n\n```python\ndef prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk):\n \n prob_drunk_given_positive = (prob_positive_drunk * prob_drunk_prior) / prob_positive\n \n return prob_drunk_given_positive\n```\n\n\n```python\nprob_drunk_given_positive(.0001,.08,1)\n```\n\n\n\n\n 0.00125\n\n\n\n\n```python\nbay_results = []\ninit_prob_drunk = .0001\nfor i in range(1,10):\n new_prob_drunk = prob_drunk_given_positive(init_prob_drunk,.08,1)\n bay_results.append(new_prob_drunk)\n init_prob_drunk = new_prob_drunk\n```\n\n\n```python\nbay_results[0:5]\n```\n\n\n\n\n [0.00125, 0.015625, 0.1953125, 2.44140625, 30.517578125]\n\n\n\n\n```python\nsns.lineplot(x=range(1,5),y=bay_results[0:4])\n```\n\n\n```python\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean, mean-interval, mean+interval)\n```\n\n\n```python\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=0.5, size=15)\n```\n\n\n```python\nnp.random.seed(seed=42)\n```\n\n\n```python\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.5333333333333333, 0.24736177494440975, 0.819304891722257)\n\n\n\n\n```python\nstats.bayes_mvs(coinflips)[0]\n```\n\n\n\n\n Mean(statistic=0.5333333333333333, minmax=(0.2984919818966858, 0.7681746847699809))\n\n\n\n\n```python\nfreq = []\nbays = []\n\nwhile i <= 30:\n coinflips = np.random.binomial(n=1, p=0.5, size=i)\n freq.append(confidence_interval(coinflips))\n bays.append(stats.bayes_mvs(coinflips)[0])\n i+=5\n```\n\n\n```python\nn_freq = []\nn_bays = []\ni=0\nwhile i < len(freq):\n n_freq.append(freq[:][i][1:3])\n n_bays.append(bays[:][i][1])\n i+=1\n```\n\n\n```python\ndf_freq = pd.DataFrame(n_freq)\ndf_bays = pd.DataFrame(n_bays)\n```\n\n\n```python\ni = 0\nwhile i < len(df_bays):\n line1 = plt.plot(df_bays.index[i:i+2].values,df_bays[i:i+2], 'r-')\n line2 = plt.plot(df_freq.index[i:i+2].values,df_freq[i:i+2], 'b-')\n plt.title('Confidence Intervals for Frequentist and Bayesian')\n plt.xlabel('Iteration (each step is 5 more coinflips)')\n plt.xticks(np.arange(5),labels=['5','10','15','20','25'])\n\n plt.ylabel('Confidence interval')\n leg = plt.legend(['Bayesian','Frequentist'])\n leg.legendHandles[0].set_color('red')\n leg.legendHandles[1].set_color('blue')\n i+=1\n```\n\nFrequentists only use descriptive statistics that are present in the dataset while Bayesians infer probabilities outside of the dataset to inform their decision.\n\nSince Bayesians use additional probabiliti\n\n\n```python\n# TODO - code!\n```\n\n## Resources\n\n- [Worked example of Bayes rule calculation](https://en.wikipedia.org/wiki/Bayes'_theorem#Examples) (helpful as it fully breaks out the denominator)\n- [Source code for mvsdist in scipy](https://github.com/scipy/scipy/blob/90534919e139d2a81c24bf08341734ff41a3db12/scipy/stats/morestats.py#L139)\n", "meta": {"hexsha": "57c372562ce91fb6febac48fc733ee22b122a9d5", "size": 54233, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_stars_repo_name": "RidleyLeisy/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_stars_repo_head_hexsha": "76e88517440f4e49cfdba7b63e48d0bb99075b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_issues_repo_name": "RidleyLeisy/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_issues_repo_head_hexsha": "76e88517440f4e49cfdba7b63e48d0bb99075b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module3-introduction-to-bayesian-inference/LS_DS_143_Introduction_to_Bayesian_Inference.ipynb", "max_forks_repo_name": "RidleyLeisy/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_forks_repo_head_hexsha": "76e88517440f4e49cfdba7b63e48d0bb99075b5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 85.2720125786, "max_line_length": 24492, "alphanum_fraction": 0.8314863644, "converted": true, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.17841450348862323}} {"text": "\n# Energy, Momentum and Conservation Laws\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA and Department of Physics, University of Oslo, Norway \n\n **[Scott Pratt](https://pa.msu.edu/profile/pratts/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA \n\n **[Carl Schmidt](https://pa.msu.edu/profile/schmidt/)**, Department of Physics and Astronomy, Michigan State University, USA\n\nDate: **Feb 3, 2020**\n\nCopyright 1999-2020, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n## Work, Energy, Momentum and Conservation laws\n\nEnergy conservation is most convenient as a strategy for addressing\nproblems where time does not appear. For example, a particle goes\nfrom position $x_0$ with speed $v_0$, to position $x_f$; what is its\nnew speed? However, it can also be applied to problems where time\ndoes appear, such as in solving for the trajectory $x(t)$, or\nequivalently $t(x)$.\n\nBefore we start formulating a strategy for energy conservation, we need to discuss integration methods and the concept of work and how it relates\nto energy.\n\n## Work and Energy\n\nTill our own material is placed here, we recommend reading chapters 10-14 of [Malthe-Sørenssen](https://www.springer.com/gp/book/9783319195957)\nand \"Taylor chapters 3 and 4\":\" .\" \n\nOn work, chapter 10 of Malthe-Sørenssen is a good read.\n\n\n\n## Energy Conservation\nEnergy is conserved in the case where the potential energy, $V(\\boldsymbol{r})$, depends only on position, and not on time. The force is determined by $V$,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}(\\boldsymbol{r})=-\\nabla V(\\boldsymbol{r}).\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nThe net energy, $E=V+K$ where $K$ is the kinetic energy, is then conserved,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}(K+V)&=&\\frac{d}{dt}\\left(\\frac{m}{2}(v_x^2+v_y^2+v_z^2)+V(\\boldsymbol{r})\\right)\\\\\n\\nonumber\n&=&m\\left(v_x\\frac{dv_x}{dt}+v_y\\frac{dv_y}{dt}+v_z\\frac{dv_z}{dt}\\right)\n+\\partial_xV\\frac{dx}{dt}+\\partial_yV\\frac{dy}{dt}+\\partial_zV\\frac{dz}{dt}\\\\\n\\nonumber\n&=&v_xF_x+v_yF_y+v_zF_z-F_xv_x-F_yv_y-F_zv_z=0.\n\\end{eqnarray}\n$$\n\nThe same proof can be written more compactly with vector notation,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\left(\\frac{m}{2}v^2+V(\\boldsymbol{r})\\right)\n&=&m\\boldsymbol{v}\\cdot\\dot{\\boldsymbol{v}}+\\nabla V(\\boldsymbol{r})\\cdot\\dot{\\boldsymbol{r}}\\\\\n\\nonumber\n&=&\\boldsymbol{v}\\cdot\\boldsymbol{F}-\\boldsymbol{F}\\cdot\\boldsymbol{v}=0.\n\\end{eqnarray}\n$$\n\nInverting the expression for kinetic energy,\n\n\n
\n\n$$\n\\begin{equation}\nv=\\sqrt{2K/m}=\\sqrt{2(E-V)/m},\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nallows one to solve for the one-dimensional trajectory $x(t)$, by finding $t(x)$,\n\n\n
\n\n$$\n\\begin{equation}\nt=\\int_{x_0}^x \\frac{dx'}{v(x')}=\\int_{x_0}^x\\frac{dx'}{\\sqrt{2(E-V(x'))/m}}.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nNote this would be much more difficult in higher dimensions, because\nyou would have to determine which points, $x,y,z$, the particles might\nreach in the trajectory, whereas in one dimension you can typically\ntell by simply seeing whether the kinetic energy is positive at every\npoint between the old position and the new position.\n\n\nConsider a simple harmonic oscillator potential, $V(x)=kx^2/2$, with a particle emitted from $x=0$ with velocity $v_0$. Solve for the trajectory $t(x)$,\n\n$$\n\\begin{eqnarray}\nt&=&\\int_{0}^x \\frac{dx'}{\\sqrt{2(E-kx^2/2)/m}}\\\\\n\\nonumber\n&=&\\sqrt{m/k}\\int_0^x~\\frac{dx'}{\\sqrt{x_{\\rm max}^2-x^{\\prime 2}}},~~~x_{\\rm max}^2=2E/k.\n\\end{eqnarray}\n$$\n\nHere $E=mv_0^2/2$ and $x_{\\rm max}$ is defined as the maximum\ndisplacement before the particle turns around. This integral is done\nby the substitution $\\sin\\theta=x/x_{\\rm max}$.\n\n$$\n\\begin{eqnarray}\n(k/m)^{1/2}t&=&\\sin^{-1}(x/x_{\\rm max}),\\\\\n\\nonumber\nx&=&x_{\\rm max}\\sin\\omega t,~~~\\omega=\\sqrt{k/m}.\n\\end{eqnarray}\n$$\n\n## Numerical Integration\n\nAs an example of an integral to solve numerically, consider the following integral. First, rewrite the integral as a sum,\n\n\n
\n\n$$\n\\begin{equation}\nt=\\sum_{n=1}^N \\Delta x [2(E-V(x_n)/m]^{-1/2},\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nwhere $\\Delta x=(x-x_0)/N$ and $x_n=x_0+(n-1/2)\\Delta x$. Note that\nfor best accuracy the value of $x_n$ has been placed in the center of\nthe $n^{\\rm th}$ interval. The accuracy will improve for higher values\nof $N$, or equivalently, smaller step size $\\Delta x$.\n\nMore material weill be added shortly.\n\n\n\n\n## Conservation of Momentum\n\n\nNewton's third law which we met earlier states that **For every action there is an equal and opposite reaction**, is more accurately stated as\n**If two bodies exert forces on each other, these forces are equal in magnitude and opposite in direction**.\n\nThis means that for two bodies $i$ and $j$, if the force on $i$ due to $j$ is called $\\boldsymbol{F}_{ij}$, then\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}. \n\\label{_auto5} \\tag{5}\n\\end{equation}\n$$\n\nNewton's second law, $\\boldsymbol{F}=m\\boldsymbol{a}$, can be written for a particle $i$ as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\sum_{j\\ne i} \\boldsymbol{F}_{ij}=m_i\\boldsymbol{a}_i,\n\\label{_auto6} \\tag{6}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{F}_i$ (a single subscript) denotes the net force acting on $i$. Because the mass of $i$ is fixed, one can see that\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\frac{d}{dt}m_i\\boldsymbol{v}_i=\\sum_{j\\ne i}\\boldsymbol{F}_{ij}.\n\\label{_auto7} \\tag{7}\n\\end{equation}\n$$\n\nNow, one can sum over all the particles and obtain\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\sum_i m_iv_i&=&\\sum_{ij, i\\ne j}\\boldsymbol{F}_{ij}\\\\\n\\nonumber\n&=&0.\n\\end{eqnarray}\n$$\n\nThe last step made use of the fact that for every term $ij$, there is\nan equivalent term $ji$ with opposite force. Because the momentum is\ndefined as $m\\boldsymbol{v}$, for a system of particles,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\sum_im_i\\boldsymbol{v}_i=0,~~{\\rm for~isolated~particles}.\n\\label{_auto8} \\tag{8}\n\\end{equation}\n$$\n\nBy \"isolated\" one means that the only force acting on any particle $i$\nare those originating from other particles in the sum, i.e. \"no\nexternal\" forces. Thus, Newton's third law leads to the conservation\nof total momentum,\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{P}&=&\\sum_i m_i\\boldsymbol{v}_i,\\\\\n\\nonumber\n\\frac{d}{dt}\\boldsymbol{P}&=&0.\n\\end{eqnarray}\n$$\n\nConsider the rocket of mass $M$ moving with velocity $v$. After a\nbrief instant, the velocity of the rocket is $v+\\Delta v$ and the mass\nis $M-\\Delta M$. Momentum conservation gives\n\n$$\n\\begin{eqnarray*}\nMv&=&(M-\\Delta M)(v+\\Delta v)+\\Delta M(v-v_e)\\\\\n0&=&-\\Delta Mv+M\\Delta v+\\Delta M(v-v_e),\\\\\n0&=&M\\Delta v-\\Delta Mv_e.\n\\end{eqnarray*}\n$$\n\nIn the second step we ignored the term $\\Delta M\\Delta v$ because it is doubly small. The last equation gives\n\n$$\n\\begin{eqnarray}\n\\Delta v&=&\\frac{v_e}{M}\\Delta M,\\\\\n\\nonumber\n\\frac{dv}{dt}&=&\\frac{v_e}{M}\\frac{dM}{dt}.\n\\end{eqnarray}\n$$\n\nIntegrating the expression with lower limits $v_0=0$ and $M_0$, one finds\n\n$$\n\\begin{eqnarray*}\nv&=&v_e\\int_{M_0}^M \\frac{dM'}{M'}\\\\\nv&=&-v_e\\ln(M/M_0)\\\\\n&=&-v_e\\ln[(M_0-\\alpha t)/M_0].\n\\end{eqnarray*}\n$$\n\nBecause the total momentum of an isolated system is constant, one can\nalso quickly see that the center of mass of an isolated system is also\nconstant. The center of mass is the average position of a set of\nmasses weighted by the mass,\n\n\n
\n\n$$\n\\begin{equation}\n\\bar{x}=\\frac{\\sum_im_ix_i}{\\sum_i m_i}.\n\\label{_auto9} \\tag{9}\n\\end{equation}\n$$\n\nThe rate of change of $\\bar{x}$ is\n\n$$\n\\begin{eqnarray}\n\\dot{\\bar{x}}&=&\\frac{1}{M}\\sum_i m_i\\dot{x}_i=\\frac{1}{M}P_x.\n\\end{eqnarray}\n$$\n\nThus if the total momentum is constant the center of mass moves at a\nconstant velocity, and if the total momentum is zero the center of\nmass is fixed.\n\n\n## Conservation of Angular Momentum\n\n\nConsider a case where the force always points radially,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}(\\boldsymbol{r})=F(r)\\hat{r},\n\\label{_auto10} \\tag{10}\n\\end{equation}\n$$\n\nwhere $\\hat{r}$ is a unit vector pointing outward from the origin. The angular momentum is defined as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{L}=\\boldsymbol{r}\\times\\boldsymbol{p}=m\\boldsymbol{r}\\times\\boldsymbol{v}.\n\\label{_auto11} \\tag{11}\n\\end{equation}\n$$\n\nThe rate of change of the angular momentum is\n\n$$\n\\begin{eqnarray}\n\\frac{d\\boldsymbol{L}}{dt}&=&m\\boldsymbol{v}\\times\\boldsymbol{v}+m\\boldsymbol{r}\\times\\dot{\\boldsymbol{v}}\\\\\n\\nonumber\n&=&m\\boldsymbol{v}\\times\\boldsymbol{v}+\\boldsymbol{r}\\times{\\boldsymbol{F}}=0.\n\\end{eqnarray}\n$$\n\nThe first term is zero because $\\boldsymbol{v}$ is parallel to itself, and the\nsecond term is zero because $\\boldsymbol{F}$ is parallel to $\\boldsymbol{r}$.\n\nAs an aside, one can see from the Levi-Civita symbol that the cross\nproduct of a vector with itself is zero. Here, we consider a vector\n\n$$\n\\begin{eqnarray}\n\\boldsymbol{V}&=&\\boldsymbol{A}\\times\\boldsymbol{A},\\\\\n\\nonumber\nV_i&=&(\\boldsymbol{A}\\times\\boldsymbol{A})_i=\\sum_{jk}\\epsilon_{ijk}A_jA_k.\n\\end{eqnarray}\n$$\n\nFor any term $i$, there are two contributions. For example, for $i$\ndenoting the $x$ direction, either $j$ denotes the $y$ direction and\n$k$ denotes the $z$ direction, or vice versa, so\n\n\n
\n\n$$\n\\begin{equation}\nV_1=\\epsilon_{123}A_2A_3+\\epsilon_{132}A_3A_2.\n\\label{_auto12} \\tag{12}\n\\end{equation}\n$$\n\nThis is zero by the antisymmetry of $\\epsilon$ under permutations.\n\nIf the force is not radial, $\\boldsymbol{r}\\times\\boldsymbol{F}\\ne 0$ as above, and angular momentum is no longer conserved,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d\\boldsymbol{L}}{dt}=\\boldsymbol{r}\\times\\boldsymbol{F}\\equiv\\boldsymbol{\\tau},\n\\label{_auto13} \\tag{13}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{\\tau}$ is the torque.\n\nFor a system of isolated particles, one can write\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\sum_i\\boldsymbol{L}_i&=&\\sum_{i\\ne j}\\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} \\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}+\\boldsymbol{r}_j\\times\\boldsymbol{F}_{ji}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} (\\boldsymbol{r}_i-\\boldsymbol{r}_j)\\times\\boldsymbol{F}_{ij}=0,\n\\end{eqnarray}\n$$\n\nwhere the last step used Newton's third law,\n$\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}$. If the forces between the particles are\nradial, i.e. $\\boldsymbol{F}_{ij} ~||~ (\\boldsymbol{r}_i-\\boldsymbol{r}_j)$, then each term in\nthe sum is zero and the net angular momentum is fixed. Otherwise, you\ncould imagine an isolated system that would start spinning\nspontaneously.\n\nOne can write the torque about a given axis, which we will denote as $\\hat{z}$, in polar coordinates, where\n\n$$\n\\begin{eqnarray}\nx&=&r\\sin\\theta\\cos\\phi,~~y=r\\sin\\theta\\cos\\phi,~~z=r\\cos\\theta,\n\\end{eqnarray}\n$$\n\nto find the $z$ component of the torque,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&xF_y-yF_x\\\\\n\\nonumber\n&=&-r\\sin\\theta\\left\\{\\cos\\phi \\partial_y-\\sin\\phi \\partial_x\\right\\}V(x,y,z).\n\\end{eqnarray}\n$$\n\nOne can use the chain rule to write the partial derivative w.r.t. $\\phi$ (keeping $r$ and $\\theta$ fixed),\n\n$$\n\\begin{eqnarray}\n\\partial_\\phi&=&\\frac{\\partial x}{\\partial\\phi}\\partial_x+\\frac{\\partial_y}{\\partial\\phi}\\partial_y\n+\\frac{\\partial z}{\\partial\\phi}\\partial_z\\\\\n\\nonumber\n&=&-r\\sin\\theta\\sin\\phi\\partial_x+\\sin\\theta\\cos\\phi\\partial_y.\n\\end{eqnarray}\n$$\n\nCombining the two equations,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&-\\partial_\\phi V(r,\\theta,\\phi).\n\\end{eqnarray}\n$$\n\nThus, if the potential is independent of the azimuthal angle $\\phi$,\nthere is no torque about the $z$ axis and $L_z$ is conserved.\n\n\n## Symmetries and Conservation Laws\n\nWhen we derived the conservation of energy, we assumed that the\npotential depended only on position, not on time. If it depended\nexplicitly on time, one can quickly see that the energy would have\nchanged at a rate $\\partial_tV(x,y,z,t)$. Note that if there is no\nexplicit dependence on time, i.e. $V(x,y,z)$, the potential energy can\ndepend on time through the variations of $x,y,z$ with time. However,\nthat variation does not lead to energy non-conservation. Further, we\njust saw that if a potential does not depend on the azimuthal angle\nabout some axis, $\\phi$, that the angular momentum about that axis is\nconserved.\n\nNow, we relate momentum conservation to translational\ninvariance. Considering a system of particles with positions,\n$\\boldsymbol{r}_i$, if one changed the coordinate system by a translation by a\ndifferential distance $\\boldsymbol{\\epsilon}$, the net potential would change\nby\n\n$$\n\\begin{eqnarray}\n\\delta V(\\boldsymbol{r}_1,\\boldsymbol{r}_2\\cdots)&=&\\sum_i \\boldsymbol{\\epsilon}\\cdot\\nabla_i V(\\boldsymbol{r}_1,\\boldsymbol{r}_2,\\cdots)\\\\\n\\nonumber\n&=&-\\sum_i \\boldsymbol{\\epsilon}\\cdot\\boldsymbol{F}_i\\\\\n\\nonumber\n&=&-\\frac{d}{dt}\\sum_i \\boldsymbol{\\epsilon}\\cdot\\boldsymbol{p}_i.\n\\end{eqnarray}\n$$\n\nThus, if the potential is unchanged by a translation of the coordinate\nsystem, the total momentum is conserved. If the potential is\ntranslationally invariant in a given direction, defined by a unit\nvector, $\\hat{\\epsilon}$ in the $\\boldsymbol{\\epsilon}$ direction, one can see\nthat\n\n$$\n\\begin{eqnarray}\n\\hat{\\epsilon}\\cdot\\nabla_i V(\\boldsymbol{r}_i)&=&0.\n\\end{eqnarray}\n$$\n\nThe component of the total momentum along that axis is conserved. This\nis rather obvious for a single particle. If $V(\\boldsymbol{r})$ does not\ndepend on some coordinate $x$, then the force in the $x$ direction is\n$F_x=-\\partial_xV=0$, and momentum along the $x$ direction is\nconstant.\n\nWe showed how the total momentum of an isolated system of particle was conserved, even if the particles feel internal forces in all directions. In that case the potential energy could be written\n\n$$\n\\begin{eqnarray}\nV=\\sum_{i,j\\le i}V_{ij}(\\boldsymbol{r}_i-\\boldsymbol{r}_j).\n\\end{eqnarray}\n$$\n\nIn this case, a translation leads to $\\boldsymbol{r}_i\\rightarrow\n\\boldsymbol{r}_i+\\boldsymbol{\\epsilon}$, with the translation equally affecting the\ncoordinates of each particle. Because the potential depends only on\nthe relative coordinates, $\\delta V$ is manifestly zero. If one were\nto go through the exercise of calculating $\\delta V$ for small\n$\\boldsymbol{\\epsilon}$, one would find that the term\n$\\nabla_i V(\\boldsymbol{r}_i-\\boldsymbol{r}_j)$ would be canceled by the term\n$\\nabla_jV(\\boldsymbol{r}_i-\\boldsymbol{r}_j)$.\n\nThe relation between symmetries of the potential and conserved\nquantities (also called constants of motion) is one of the most\nprofound concepts one should gain from this course. It plays a\ncritical role in all fields of physics. This is especially true in\nquantum mechanics, where a quantity $A$ is conserved if its operator\ncommutes with the Hamiltonian. For example if the momentum operator\n$-i\\hbar\\partial_x$ commutes with the Hamiltonian, momentum is\nconserved, and clearly this operator commutes if the Hamiltonian\n(which represents the total energy, not just the potential) does not\ndepend on $x$. Also in quantum mechanics the angular momentum operator\nis $L_z=-i\\hbar\\partial_\\phi$. In fact, if the potential is unchanged\nby rotations about some axis, angular momentum about that axis is\nconserved. We return to this concept, from a more formal perspective,\nlater in the course when Lagrangian mechanics is presented.\n\n\n## Bulding a code for the Earth-Sun system\n\nWe will now venture into a study of a system which is energy\nconserving. The aim is to see if we (since it is not possible to solve\nthe general equations analytically) we can develop stable numerical\nalgorithms whose results we can trust!\n\nWe solve the equations of motion numerically. We will also compute\nquantities like the energy numerically.\n\nWe start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is\n\n$$\n\\boldsymbol{F}_G=-\\frac{GM_{\\odot}M_E}{r^3}\\boldsymbol{r},\n$$\n\nwhere $G$ is the gravitational constant,\n\n$$\nM_E=6\\times 10^{24}\\mathrm{Kg},\n$$\n\nthe mass of Earth,\n\n$$\nM_{\\odot}=2\\times 10^{30}\\mathrm{Kg},\n$$\n\nthe mass of the Sun and\n\n$$\nr=1.5\\times 10^{11}\\mathrm{m},\n$$\n\nis the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.\nFrom Newton's second law we have then for the $x$ direction\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{F_{x}}{M_E},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=-\\frac{F_{y}}{M_E},\n$$\n\nfor the $y$ direction.\n\nHere we will use that $x=r\\cos{(\\theta)}$, $y=r\\sin{(\\theta)}$ and\n\n$$\nr = \\sqrt{x^2+y^2}.\n$$\n\nWe can rewrite\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nfor the $y$ direction.\n\n\nWe can rewrite these two equations\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nas four first-order coupled differential equations\n\n4\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\frac{dy}{dt}=v_y.\n$$\n\n## Building a code for the solar system, final coupled equations\n\nThe four coupled differential equations\n\n4\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n4\n9\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\frac{dy}{dt}=v_y,\n$$\n\ncan be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\\times 10^{11}$. \n\nUsing the equations from circular motion (with $r =1\\mathrm{AU}$)\n\n$$\n\\frac{M_E v^2}{r} = F = \\frac{GM_{\\odot}M_E}{r^2},\n$$\n\nwe have\n\n$$\nGM_{\\odot}=v^2r,\n$$\n\nand using that the velocity of Earth (assuming circular motion) is\n$v = 2\\pi r/\\mathrm{yr}=2\\pi\\mathrm{AU}/\\mathrm{yr}$, we have\n\n$$\nGM_{\\odot}= v^2r = 4\\pi^2 \\frac{(\\mathrm{AU})^3}{\\mathrm{yr}^2}.\n$$\n\n## Building a code for the solar system, discretized equations\n\nThe four coupled differential equations can then be discretized using Euler's method as (with step length $h$)\n\n5\n5\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n6\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n5\n7\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\ny_{i+1}=y_i+hv_{y,i},\n$$\n\n## Code Example with Euler's Method\n\nThe code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using Euler's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using Euler's forward method\n v[i+1] = v[i] + DeltaT*a\n r[i+1] = r[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunEuler\")\nplt.show()\n```\n\n## Problems with Euler's Method\n\nWe notice here that Euler's method doesn't give a stable orbit. It\nmeans that we cannot trust Euler's method. In a deeper way, as we will\nsee in homework 5, Euler's method does not conserve energy. It is an\nexample of an integrator which is not\n[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).\n\nHere we present thus two methods, which with simple changes allow us to avoid these pitfalls. The simplest possible extension is the so-called Euler-Cromer method.\nThe changes we need to make to our code are indeed marginal here.\nWe need simply to replace\n\n\n```python\n r[i+1] = r[i] + DeltaT*v[i]\n```\n\nin the above code with the velocity at the new time $t_{i+1}$\n\n\n```python\n r[i+1] = r[i] + DeltaT*v[i+1]\n```\n\nBy this simple caveat we get stable orbits.\nBelow we derive the Euler-Cromer method as well as one of the most utlized algorithms for sovling the above type of problems, the so-called Velocity-Verlet method. \n\n## Deriving the Euler-Cromer Method\n\nLet us repeat Euler's method.\nWe have a differential equation\n\n\n
\n\n$$\n\\begin{equation}\n y'(t_i)=f(t_i,y_i) \n\\label{_auto14} \\tag{14}\n\\end{equation}\n$$\n\nand if we truncate at the first derivative, we have from the Taylor expansion\n\n\n
\n\n$$\n\\begin{equation}\n y_{i+1}=y(t_i) + (\\Delta t) f(t_i,y_i) + O(\\Delta t^2), \\label{eq:euler} \\tag{15}\n\\end{equation}\n$$\n\nwhich when complemented with $t_{i+1}=t_i+\\Delta t$ forms\nthe algorithm for the well-known Euler method. \nNote that at every step we make an approximation error\nof the order of $O(\\Delta t^2)$, however the total error is the sum over all\nsteps $N=(b-a)/(\\Delta t)$ for $t\\in [a,b]$, yielding thus a global error which goes like\n$NO(\\Delta t^2)\\approx O(\\Delta t)$. \n\nTo make Euler's method more precise we can obviously\ndecrease $\\Delta t$ (increase $N$), but this can lead to loss of numerical precision.\nEuler's method is not recommended for precision calculation,\nalthough it is handy to use in order to get a first\nview on how a solution may look like.\n\nEuler's method is asymmetric in time, since it uses information about the derivative at the beginning\nof the time interval. This means that we evaluate the position at $y_1$ using the velocity\nat $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at\n$v_{n+1}$, that is (in a slightly more generalized form)\n\n\n
\n\n$$\n\\begin{equation} \n y_{n+1}=y_{n}+ v_{n+1}+O(\\Delta t^2)\n\\label{_auto15} \\tag{16}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n v_{n+1}=v_{n}+(\\Delta t) a_{n}+O(\\Delta t^2).\n\\label{_auto16} \\tag{17}\n\\end{equation}\n$$\n\nThe acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated\nas well. This is the Euler-Cromer method.\n\n**Exercise**: go back to the above code with Euler's method and add the Euler-Cromer method. \n\n\n## Deriving the Velocity-Verlet Method\n\nLet us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.\n\nWe have the Taylor expansion for the position given by\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_i+O((\\Delta t)^3).\n$$\n\nThe corresponding expansion for the velocity is\n\n$$\nv_{i+1} = v_i+(\\Delta t)a_i+\\frac{(\\Delta t)^2}{2}v^{(2)}_i+O((\\Delta t)^3).\n$$\n\nVia Newton's second law we have normally an analytical expression for the derivative of the velocity, namely\n\n$$\na_i= \\frac{d^2 x}{dt^2}\\vert_{i}=\\frac{d v}{dt}\\vert_{i}= \\frac{F(x_i,v_i,t_i)}{m}.\n$$\n\nIf we add to this the corresponding expansion for the derivative of the velocity\n\n$$\nv^{(1)}_{i+1} = a_{i+1}= a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2)=a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2),\n$$\n\nand retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have\n\n$$\n(\\Delta t)v^{(2)}_i\\approx a_{i+1}-a_i.\n$$\n\nWe can then rewrite the Taylor expansion for the velocity as\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left( a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\n## The velocity Verlet method\n\nOur final equations for the position and the velocity become then\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_{i}+O((\\Delta t)^3),\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left(a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nNote well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate \nthe position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time\n$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. \n\n\n## Adding the Velocity-Verlet Method\n\nWe can now easily add the Verlet method to our original code as\n\n\n```python\nDeltaT = 0.01\n#set up arrays \ntfinal = 10\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up forces, air resistance FD, note now that we need the norm of the vecto\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -4*(pi**2)*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('y[m]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunVV\")\nplt.show()\n```\n\nYou can easily generalize the calculation of the forces by defining a function\nwhich takes in as input the various variables. We leave this as a challenge to you.\n\n## Studying Energy Conservation\n\nIn order to study the conservation of energy, we will need to perform a numerical integration, unless we can integrate analytically. Here we present the Trapezoidal rule as a the simplest possible approximation.\n", "meta": {"hexsha": "b177dc8a2ec1473e0dc0285fcf2238765422ef97", "size": 135488, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/energyconserv/ipynb/.ipynb_checkpoints/energyconserv-checkpoint.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/pub/energyconserv/ipynb/.ipynb_checkpoints/energyconserv-checkpoint.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/pub/energyconserv/ipynb/.ipynb_checkpoints/energyconserv-checkpoint.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 73.5149213239, "max_line_length": 71844, "alphanum_fraction": 0.8111862305, "converted": true, "num_tokens": 8902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1778854005367229}} {"text": "The Fundamental Theorem of Calculus is a theorem that connects the two branches of calculus, differential and integral, into a single framework. We saw the computation of antiderivatives previously is the same process as integration; thus we know that differentiation and integration are inverse processes. The Fundamental Theorem of Calculus formalizes this connection. The theorem is given in two parts.\n\n### First Fundamental Theorem of Calculus\n\nThe first Fundamental Theorem of Calculus states:\n\nIf $f$ is continuous on an interval $[a, b]$, then the function $g$ defined by:\n\n$$ g(x) = \\int_a^x f(t) \\space dt \\qquad a \\leq x \\leq b $$\n\nis continuous on the interval $[a, b]$ and differentiable on $(a,b)$ and $g^\\prime(x) = f(x)$.\n\n### Second Fundamental Theorem of Calculus\n\nThe second Fundamental Theorem of Calculus states:\n\nIf $f$ is continuous on the interval $[a, b]$ then:\n\n$$ \\int_a^b f(x) \\space dx = F(b) - F(a) $$\n\nWhere $F$ is any antiderivative of $f$\n\n## Examples\n\n\n```python\nfrom sympy import symbols, limit, diff, sin, cos, log, tan, sqrt, init_printing, plot, integrate\nfrom mpmath import ln, e, pi\n\ninit_printing()\nx = symbols('x')\ny = symbols('y')\n```\n\n### Example 1: Evaluate the integral: $\\int_{-1}^2 (x^3 - 2x) \\space dx$\n\nApplying the second part of the Fundamental Theorem of Calculus, we take the antiderivative of the function and evaluate the integral.\n\n$$ \\int_{-1}^2 (x^3 - 2x) \\space dx = \\frac{1}{4} x^4 - x^2 \\Bigg\\rvert_{-1}^2 $$\n\n$$ = \\frac{1}{4} (-1)^4 - (-1)^2 - \\frac{1}{4} (2)^4 - (2)^2 = \\frac{3}{4} $$\n\nWe can verify our answer using SymPy's `integrate()` function.\n\n\n```python\nintegrate(x ** 3 - 2 * x, (x, -1, 2))\n```\n\n### Example 2: Evaluate $\\int_1^4 (5 - 2x + 3x^2) \\space dx$\n\nAs in the previous example, we take advantage of the second part of the Fundamental Theorem of Calculus:\n\n$$ \\int_1^4 (5 - 2x + 3x^2) \\space dx = 5x - x^2 + x^3 \\Bigg\\rvert_1^4 $$\n\n$$ = 5(4) - (4)^2 + (4)^3 - 5(1) - (1)^2 + (1)^3 = 63 $$\n\n\n```python\nintegrate(5 - 2 * x + 3 * x ** 2, (x, 1, 4))\n```\n\n### Example 3: Compute the integral $\\int_0^1 x^{\\frac{4}{5}} \\space dx$\n\n$$ \\int_0^1 x^{\\frac{4}{5}} \\space dx = \\frac{5}{9} x^{\\frac{9}{5}} \\Bigg\\rvert_0^1 $$\n\n$$ = \\frac{5}{9}(1)^\\frac{9}{5} - \\frac{5}{9}(0)^\\frac{9}{5} = \\frac{5}{9} $$\n\n\n```python\nintegrate(x ** (4/5), (x, 0, 1)) # Returned result will be in decimal form.\n```\n\n### Example 4: Determine the integral $\\int_1^2 \\frac{3}{x^4} \\space dx$\n\nRewriting the integral as $\\int_1^2 3x^{-4} \\space dx$:\n\n$$ \\int_1^2 3x^{-4} \\space dx = -x^{-3} = -\\frac{1}{x^3} \\Bigg\\rvert_1^2 $$\n\n$$ = -\\frac{1}{(2)^3} + \\frac{1}{(1)^3} = -\\frac{1}{8} + 1 = \\frac{7}{8} $$\n\n\n```python\nintegrate(3 / x ** 4, (x, 1, 2))\n```\n\n### Example 5: Compute the integral $\\int_0^2 x(2 + x^5) \\space dx$\n\nStart by factoring:\n\n$$ \\int_0^2 2x + x^6 \\space dx = x^2 + \\frac{1}{7} x^7 \\Bigg\\rvert_0^2 $$\n\n$$ = (2)^2 + \\frac{1}{7} 2^7 - (0)^2 + \\frac{1}{7} (0)^7 = 4 + \\frac{128}{7} = \\frac{28}{7} + \\frac{128}{7} = \\frac{156}{7} $$\n\n\n```python\nintegrate(x * (2 + x ** 5), (x, 0, 2))\n```\n\n## References\n\nFundamental theorem of calculus. (2017, December 2). In Wikipedia, The Free Encyclopedia. From https://en.wikipedia.org/w/index.php?title=Fundamental_theorem_of_calculus&oldid=813270221\n\n[Stewart, J. (2007). Essential calculus: Early transcendentals. Belmont, CA: Thomson Higher Education.](https://amzn.to/38dnRV0)\n\nWeisstein, Eric W. \"Fundamental Theorems of Calculus.\" From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/FundamentalTheoremsofCalculus.html\n", "meta": {"hexsha": "3d4f79f7f97352619546bc1f163120a4264d67ee", "size": 11335, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/posts/Fundamental Theorem of Calculus.ipynb", "max_stars_repo_name": "aschleg/aaronschlegel.me", "max_stars_repo_head_hexsha": "2f2e143218445da0b6298671c67f9c4afa055d59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-19T00:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:11:31.000Z", "max_issues_repo_path": "content/posts/Fundamental Theorem of Calculus.ipynb", "max_issues_repo_name": "aschleg/aaronschlegel.me", "max_issues_repo_head_hexsha": "2f2e143218445da0b6298671c67f9c4afa055d59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-26T00:11:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-26T00:11:30.000Z", "max_forks_repo_path": "content/posts/Fundamental Theorem of Calculus.ipynb", "max_forks_repo_name": "aschleg/aaronschlegel.me", "max_forks_repo_head_hexsha": "2f2e143218445da0b6298671c67f9c4afa055d59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.452887538, "max_line_length": 1238, "alphanum_fraction": 0.6332598147, "converted": true, "num_tokens": 1296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.3812195592260441, "lm_q1q2_score": 0.17722957212245846}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n\n```python\n#import json\n#import matplotlib\n#s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n#matplotlib.rcParams.update(s)\n```\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000, step=step, n_jobs=1)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2_log__]\n >Metropolis: [lambda_1_log__]\n Could not pickle model, sampling singlethreaded.\n Sequential sampling (4 chains in 1 job)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2_log__]\n >Metropolis: [lambda_1_log__]\n 100%|███████████████████████████████████████████████████████████████████████████████████████| 15000/15000 [01:42<00:00, 146.35it/s]\n 100%|███████████████████████████████████████████████████████████████████████████████████████| 15000/15000 [01:36<00:00, 155.64it/s]\n 100%|███████████████████████████████████████████████████████████████████████████████████████| 15000/15000 [01:42<00:00, 146.41it/s]\n 100%|███████████████████████████████████████████████████████████████████████████████████████| 15000/15000 [01:42<00:00, 145.72it/s]\n C:\\Anaconda3\\envs\\pymc3\\lib\\site-packages\\mkl_fft\\_numpy_fft.py:1044: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.\n output = mkl_fft.rfftn_numpy(a, s, axes)\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f5d81bac34c350c390410e5f8153988d271295f0", "size": 302642, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "Miguel-O-Matic/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "287cac5775a573afc56ed7c477953dd91f51912c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "Miguel-O-Matic/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "287cac5775a573afc56ed7c477953dd91f51912c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "Miguel-O-Matic/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "287cac5775a573afc56ed7c477953dd91f51912c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 278.6758747698, "max_line_length": 88088, "alphanum_fraction": 0.9003740393, "converted": true, "num_tokens": 11588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.1767751456154852}} {"text": "```python\nimport theme\ntheme.load_style()\n```\n\n# Lesson 2: Introduction to Python\n## Using Python in Scientific Computing\n\n\n\n\n\nThis lecture by Tim Fuller is licensed under the\nCreative Commons Attribution 4.0 International License. All code examples are also licensed under the [MIT license](http://opensource.org/licenses/MIT).\n\nThis book is intended for students in science/engineering/math and presumes an introductory knowledge of computer programming (be it whatever language). This book *is not* an introduction to computer programming.\n\nFor a complete introduction to IPython Notebooks, see the [IPython Notebook Tutorial](IPython Notebook Tutorial.ipynb).\n\n\n# Topics\n\n- [What is Python](#what_is) \n- [How do I use Python?](#how_to_py)\n- [Minimal Python Stack](#minimal_stack)\n - [numpy](#minimal_py_numpy)\n - [matplotlib](#minimal_py_matplotlib)\n - [sympy](#minimal_py_sympy)\n- [Dive in to Python](#dive_in_to_py)\n - [Variable Assignment](#var_assign)\n - [Variable Types](#var_types)\n - [Program Flow Control](#prog_flow)\n - [Indentation](#indentation)\n - [Branching](#branching)\n - [Looping](#looping)\n - [Functions](#functions)\n - [Modules](#modules)\n - [Numpy](#numpy)\n\n# What is Python?[](#top)\n\nAs your read through each section, you will see cells labeled with\n\n
Try it
\n\nwhich are places meant for you to try the new concept introduced. Keep in mind, that these Notebooks are interactive, fee free to modify values, move things, test things out.\n\n[Python](www.python.org) is an open source, general-purpose language, with hundreds of modules geared toward scientific computing. Some main features of Python are:\n\n - Object Oriented, Procedural, and Functional programming styles\n - Easy to interface with C/C++/Fortran/Java/etc\n - Interactive environment\n - Becoming the de-facto standard interfacing language for many commercial FE codes\n - Clean and simple\n - [Duck typed](http://en.wikipedia.org/wiki/Duck_typing)\n - Interpretive (no compiling necessary)\n - Automatic memory management\n \nSome relative advantages of Python\n\n - Ease of programming\n - Fast prototyping\n - Interfacing with other languages\n - Large library of modules and add-on packages\n - Open source\n \nSome relative disadvantages\n\n - Speed of execution compared to compiled languages\n - Programs can become platform/environment dependent\n \n\nThere is no way a short tutorial can describe everything in Python (I've been using/developing Python for 10+ years and learn new stuff all the time). But, it will introduce enough concepts to complete the first homework assignment and provide a foundation for future learning.\n\n# How do I use Python?[](#top)\n\nPython is synonomous with the programming language, the interactive Python shell, and the interpreter under the hood that actually reads and processes the code. There are several ways to write/interact with Python: the interactive python shell, the IPython notebook, and by interpreting program files containing python statemtns. This is one of Python's relative strengths: it allows users to select the environment that best suits their needs.\n\n## The Interactive Python Shell\n\nThe Python shell is a program that reads and executes Python statements as you enter them. It is opened by invoking the following at a command prompt\n\n $ python\n\n
\nTry it!
\nBefore moving, enter a python shell and execute the following\n
\n\n\n\nInteractive Python sessions are fantastic for quick calculations, or testing snippets of code.\n\n## IPython Notebook\n\n[Ipython Notebooks](http://ipython.org/notebook.html) provide an interactive environment for Python similar to Maple's worksheets or Mathematica's notebooks. It is based on the IPython shell (a modified interactive Python shell). IPython notebook sessions are stored locally as `json` files with a `.ipynb` file extension and are interpreted graphically as a web session using IPython's notebook server. This file is an example of an IPython Notebook file.\n\nThe IPython Notebook server is launched locally by executing the following at the command prompt:\n\n $ ipython notebook\n \nThis will open a new web browser (or tab in an existing window) in which notebooks can be created/edited/deleted. The fact that you are reading this means you have already launched the notebook server.\n\nIPython notebooks consist of a collection of text cells and code cells. `code` cells execute Python code in the notebook's kernel. Text cells are labeled `markdown`, `Raw NBConvert`, and `Heading1-6`. Different text cell types display their contents differently. Looking at the toolbar above, can you tell what type of cell this is? (`Markdown`).\n\nSee the full [IPython Tutorial](Lesson01_IPythonNotebookTutorial.ipynb) for more details.\n\n## Python Program Files\n\nOften, it is not convenient to work in an interactive or notebook environment. In those situations, Python statements can be saved in Python program files that are later interpreted and executed by the Python interpreter (this is not strictly true, but is true enough for now). Python program files (usually) have the file extension \"`.py`\", e.g. `baz.py`. \n\nWith the exception of comment lines, every line in a Python program file is considered to be a Python statement and statements are executed in order from the top of the file to the bottom. Any statement proceding a \"`#`\" (until the end of the line) is considered a comment. Python program files can be executed individually by executing the following at a command prompt:\n\n python filename.py\n\n
\nCAUTION
python files that you intend to later be imported should be valid python variable names. i.e., do not use special characters in Python program file names (+, -, /, *, @, $, etc.). More on this later.\n
\n\n# Minimal Software Stack for Scientific Computing in Python[](#top)\n\nThe strength of Python for scientific computing lies in the large number of add-on modules on which users can build applications. Many of the most important modules, namely \n\n - [`numpy`](http://www.numpy.org/‎)\n - [`scipy`](http://www.scipy.org/‎)\n - [`sympy`](http://www.sympy.org/‎)\n - [`matplotlib`](http://www.matplotlib.org/‎)\n - [`ipython notebook`](http://www.ipython.org/notebook.html)\n \nare not part of the standard Python distribution. Historically, users had to install each module (and their dependencies) individually. This painful process can, in large part, be bypassed by using one of the fantastic commercially available Python distributions. I recommend [annoconda](https://store.continuum.io/cshop/anaconda/) or [enthought](https://www.enthought.com/products/epd/‎). Both offer free and paid versions. The free versions offer all the utility that we will need in this book.\n\n## numpy\n\nThe `numpy` package is the foundation of most scientific computations performed in Python. It is implemented in C/Fortran, so performance is greatly improved over native Python data types. `numpy` provides:\n\n - the `ndarray` (n dimensinal array) is `numpy`'s primary object\n - fast array operations\n - large library of linear algebra procedures\n - and much, much, more...\n\n\n\n## matplotlib\n\n`matplotlib` is a 2D and 3D graphics library for generating scientific figures. `matplotlib`:\n\n - easy to use interface very similar to Matlabs\n - support for $\\LaTeX$ labels and text\n - publication quality output in most popular formats\n - GUI and batch modes\n\n## sympy\n\n`sympy` provides a Computer Algebra System (CAS) for Python. `sympy` is a regular Python module and integrates very well with IPython notebooks.\n\n# Dive in to Python[](#top)\n\n## Variable Assignment\n\nSince python is a dynamically interpreted language, a variable's type need not be declared - its type is inferred at the time of assignment. Variables are assigned a value by the assignment operateor \"`=`\"\n\n\n```python\nspam = 4\nspam\n```\n\nAn assignment statement assigns to the variable name on the left of the assignment operator the expression on the right.\n\n
\n\n Reminder: To execute the cell above move focus to the cell and press \n
\n
shift enter
\n\n
\n\n## Variable Types\n\nPython supports many `type`s of variables. The most commonly used in this course are `str`, `float`, `int`, `bool`, `list`, `tuple`, and `dict`.\n\n### Strings\n\nStrings are groups of one or more characters of type `str` enclosed by single or double quotes\n\n\n```python\nstring = \"foo\"\ntype(string)\n```\n\nString concatenation is by the \"+\" operator\n\n\n```python\npost = \" bar\"\nstring + post\n```\n\nPython's support for string parsing, manipulation, etc. is, in my opinion, one of its greatest strengths.\n\n### Numbers\n\nPython supports many types of numbers, the most common being reals and integers\n\nReal numbers are of type `float`\n\n\n```python\na = 4.\n```\n\n\n```python\na = float(4)\n```\n\n\n```python\na = float(\"4.\")\n```\n\n\n```python\ntype(a)\n```\n\nIntegers have type `int`\n\n\n```python\nb = 4\n```\n\n\n```python\nb = int(4.)\ntype(b)\n```\n\nBe careful when converting strings to integers\n\n\n```python\nb = int(\"4.\")\n```\n\nThe above code \"raised\" a `ValueError`. Instead, first convert to float, then integer\n\n\n```python\nb = int(float(\"4.\"))\nb\n```\n\nArithmetic is through the standard arithmetic operators\n\n\n```python\na = 3.\nb = 2.\na + b # addition\n```\n\n\n```python\na - b # subtraction\n```\n\n\n```python\na * b # multiplication\n```\n\n\n```python\na / b # division\n```\n\n
\n\"**Warning!** by default \"/\" is integer division\n
\n\n\n```python\n1 / 2\n```\n\n\n```python\na ** 2 # raising to power (note, do not use ^)\n```\n\n### Booleans\n\nPython supports a boolean type `bool` with two members `True` and `False`. Python also supports the related `None`.\n\n### Lists\n\nLists are mutable container objects of type `list`. Lists are composed of comma separated members enclosed by paired brackets\n\n\n```python\na = [1, 2, 3]\ntype(a)\n```\n\nLists can be appended to and extended by other lists\n\n\n```python\na.append(4)\na.extend([5, 6, 7])\na\n```\n\n
\n\n Important: In the cell above a is an object of type list. Put differently, a is an \"instance\" of the list class. The dot . following a above, is a special operator that accesses \"methods\" associated with a. Simplistically, methods are functions that are owned by a class and are accessible only by instances of the class through the dot operator. Classes will be covered more in depth later, it is sufficient for now to recognize the action of the dot operator.\n\n
\n\nList members need not be of the same type\n\n\n```python\nb = [1, 2, \"spam\", True, [3, 4]]\nb\n```\n\n
\n Attention: matlab and fortran users: in Python, indexing is 0 based\n
\n\n\n```python\nfirst = b[0]\nfirst\n```\n\n\n```python\nlast = b[-1]\nlast\n```\n\nSlices of lists can be accessed\n\n\n```python\nc = a[0:3]\nc\n```\n\n### Tuples\n\nTuples are container objects like lists, but are immutable (not modifiable after creation) and use parenthesis in place of brackets\n\n\n```python\na = (1, 2, 3, 4)\n```\n\nOnce created, immutable objects cannot be modified. For instance, attempting a number to the end of `a` will result in an error\n\n\n```python\n# a.append(4) # tuples are immutable, so this will result in an error\n```\n\n### Dictionaries\n\nLike lists and tuples, dictionaries are yet another container object (type: `dict`). Dictionaries consist of `key:value` pairs enclosed by braces. Valid keys are any immutable object (other items can be used, but for now immutable objects will suffice). For example, in the cell below a dictionary `d` is created with key `a` and value `5`. A new `key:value` pair is then added to `d`. \n\n\n```python\nd = {\"a\": 5}\nd[\"b\"] = \"spam\"\nd\n```\n\n\n```python\nd[\"b\"]\n```\n\nA `KeyError` is raised when attempting to access a non-existent key\n\n\n```python\n# d[12]\n```\n\nThe `dict` constructor can be used to create a dictionary from a list of tuples\n\n\n```python\nd = dict([('a', 5), ('b', 'spam'), (0, (1,2,3))])\nd\n```\n\n
\n\n Try it!
Add key:value pairs \"c\": [1,2,3] and \"d\": (3,4,5) to d.\n\n
\n\n
\n Note: dictionaries do not preserve order.\n
\n\n## Program Flow Control\n\n### Indentation\n\nUnlike many other languages that explicitly define the scope of code blocks (opening/closing braces, begin/end keywords, etc.), Python implicitly defines code block scope through indentation\n\n compound_statement \":\"\n code block\n \nThe Python language does not define a standard indentation depth, but the following advice should be followed:\n\n - Don't mix tabs and spaces\n - Spaces are preferred in new code\n - Be consistent with indentation\n - Use 4 spaces in new code (4 spaces will be used in this class)\n\n\nBranching (if, else, etc.)\n\nBranching within a code is handled by `if`, `elif`, and `else` clauses\n\n\n```python\nif True:\n print \"I'm True!\"\n```\n\n\n```python\na = 4\nif a < 3:\n print \"Less than 3\"\nelif a < 6:\n print \"Between 3 and 6\"\nelse:\n print \"Greater than 6\"\n```\n\nNotice that the indentation of the above code defines the scope of each block.\n\n### Looping\n\nPython provides two forms of looping: `for` and `while`.\n\n#### `for` Loops\n\n`for` loops in Python is one area that took me some time to become accustomed to, in comparison to C or Fortran. In C, Fortran, and many other languages, loops are constructed by incrementing an integer value from a starting value to an ending value. For example, in C\n\n for(int i=0; i<10; i++){\n std::cout << i << \"\\n\";\n }\n \nIn Python, `for` loops are performed by iterating through an \"iterable\". Iterables are objects, such as `lists`, `tuples`, and `dict`s, that support iteration. In python, the previous loop could be written:\n\n\n```python\nfor i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:\n print i\n```\n\nor,\n\n\n```python\nfor i in range(10):\n print i\n```\n\nStrings also support iteration. To loop through the values of a string,\n\n\n```python\nfor letter in \"a very long string\":\n print letter\n```\n\n
\nTry It!
\nInsert a new cell below and write a block of code that loops through integers 1-20 and prints those that are even.\n
\n\n#### `while` Loops\n\nSimilar to `for` loops, while loops iterate until a condition is met.\n\n\n```python\na = 1\nwhile a < 5:\n a += a # lhs += rhs is a shortcut for lhs = lhs + rhs\nprint a\n```\n\n### List Comprehension\n\nA list comprehension is a concise way of creating a `list`. Consider the following \n\n\n```python\na = []\nfor i in range(4):\n a.append(i ** 2)\na\n```\n\n
\nThe range function creates a list, starting from 0 by default, with n elements\n
\n\n\n```python\nrange(9)\n```\n\nThe above code can be simplified to\n\n\n```python\na = [i ** 2 for i in range(4)]\na\n```\n\nList comprehensions consist of an opening bracket, expression, a for loop, followed by 1 or more for loops and/or if statements and are ended with a closing bracket.\n\n
\nTry It!
\nOpen a cell below and create a list of the cubes of the first 5 integers using 1) a for loop and append statement and 2) a list comprehension.\n
\n\n## Functions\n\nFunctions contain collections of related Python code. Functions have the following syntax\n\n def function_name \"(\" [parameter_list] \")\" \":\"\n suite\n\nFor example\n\n\n```python\ndef print_hello():\n print \"Hello, World!\"\nprint_hello()\n```\n\n\n```python\ndef print_hello_with_args(a, b):\n print \"{0} says hello to {1}!\".format(a, b)\nprint_hello_with_args(\"Fred\", \"Sue\")\n```\n\n
\nThe .format string method, in its simplest form, replaces occurrences of {n} with its nth argument. For example\n
\n\n\n```python\n\"Mary {0} {3} {2} {1}\".format(\"had\", \"lambs\", \"little\", 5)\n```\n\nFunctions can return 1 or more objects\n\n\n```python\ndef add(a, b):\n c = a + b\n return c\nadd(4, 5)\n```\n\n### Lambda Functions\n\nAnother type of function is the `lambda` function, or \"anonymous\" function. `lambda`s allow the creation of functions on the fly\n\n\n```python\nf = lambda x: x ** 2\nf(4.)\n```\n\n`lambda` functions are useful in many situations and we'll have a chance to use them often throughtout this book.\n\n
\nTry It!
\nWrite a function that multiplies 2 numbers and returns the result.\n
\n\n## Modules\n\nPython modules are importable files containing Python code. Importing a module in to the current file exposes that modules contents to the current file. The syntax for importing a module takes one of several forms, demonstrated below.\n\n\n```python\nimport math\nmath.pi\n```\n\n\n```python\nmath.cos(0.)\n```\n\nModules names can be aliased for convenience with the ``as`` designator\n\n\n```python\nimport math as m\nm.pi\n```\n\nAlternatively, all contents of a module can be imported in to the current namespace\n\n\n```python\nfrom math import *\npi\n```\n\nHowever, this can lead to pollution of the current namespace and is not recommended - unless the module was designed to be imported in this way. For example, suppose you do\n\n from spam import *\n from eggs import *\n \n baz = foo\n \nfrom which module did `foo` come from?\n\nThe Python standard library comes with many useful modules. In this course we will also use heavily the nonstandard `numpy`, `sympy`, and `matplotlib` modules.\n\n
\nTry It!
\nImport the `os` module and determine your current working directory with its `cwd` method.\n
\n\n## `numpy`\n\n`numpy` is a powerful Python module that is the defacto standard for scientific computing in Python. It is customary to import `numpy` as\n\n\n```python\nimport numpy as np\n```\n\nThe power of `numpy` lies in the array object that it provides. `numpy` arrays are similar to Python lists, but are statically typed and contain only one object type. Arrays can be instantiated in a number of ways, \n\n- from an existing list\n\n\n```python\na = np.array([1., 2., 3.])\na\n```\n\n- the `numpy.linspace` function\n\n\n```python\na = np.linspace(0, 10, 5) # np.linspace takes (start, stop, number of elements)\na\n```\n\n- the `numpy.arange` function\n\n\n```python\na = np.arange(0, 5, 1.5) # np.arange takes (start, stop, step size)\na\n```\n\nAnd still others.\n\n### Linear Algebra with `numpy`\n\n`numpy` provides many common operations from linear algebra to operate on n dimensional arrays. Consider the following arrays\n\n\n```python\n# Define 1 and 2D arrays. 2D arrays are similar to matrices in matlab\na = np.array([3, 2, 6])\nb = np.array([1, 1, 7])\nM = np.array([[1, 5, 4], [5, 5, 3], [8, 2, 9]])\nL = np.array([[3, 1, 5], [5, 7, 2], [1, 0, 3]])\n```\n\n#### The transpose of an array\n\n\n```python\nnp.transpose(M)\n```\n\nThe `*` operator operates element wise on arrays, so `a * b` will not yield a scalar\n\n\n```python\na * b\n```\n\n#### The `dot` Product\n\nScalar product of two vectors\n\n\n```python\nnp.dot(a, b)\n```\n\nMatrix/Vector multiplication is also through the `dot` method\n\n\n```python\nnp.dot(M, a)\n```\n\nThink of the `dot` method in terms of the indicial summation representation of matrix operations, e.g. matrix/vector multiplication\n\n$\\{c\\} = [A]\\{b\\} \\Rightarrow c_i = \\sum_jA_{ij}b_{j}$\n\nwould be written\n\n c = np.dot(A, b)\n \nOr matrix multiplication,\n\n$[C] = [A][B] \\Rightarrow C_{ij} = \\sum_m A_{im}B_{mj}$\n\nis\n\n C = np.dot(A, B)\n \nOr the vector/vector (scalar) product\n\n$c = \\{v\\}\\cdot\\{w\\} = \\sum_i v_i w_i$\n\nis\n\n c = np.dot(v, w)\n \n\n#### Inverse of a square matrix\n\n\n```python\nnp.linalg.inv(M)\n```\n\n#### Determinant of a matrix\n\n\n```python\n# Determinant of a 2D array\nnp.linalg.det(M)\n```\n\n#### Solution of linear systems:\n\nsolve for $\\{x\\}$: $[M]\\{x\\} = \\{b\\}$\n\n\n```python\n# Solution to system of equations (using inv is *very* inefficient)\nx = np.dot(np.linalg.inv(M), b)\nx\n```\n\nBetter to use the `solve` method\n\n\n```python\nx = np.linalg.solve(M, b)\nx\n```\n\n## `sympy`\n\n`sympy` is a Computer Algebra System implemented in python. `sympy` allows the creation of symbols and functions (among many other objects) and allows algebraic manipulation of those objects.\n\n\n```python\nimport sympy as sp\nsp.init_printing() # allow pretty math output\n```\n\nVariables can be designated as `Symbol`s and used in symbolic computation\n\n\n```python\nx = sp.Symbol(\"x\")\ny, z = sp.symbols(\"y z\")\nf = x + y * sp.pi\nf\n```\n\nValues can be substituted in place of symbols\n\n\n```python\nf.subs({x: 2, y: 3})\n```\n\nEvaluate the value numerically\n\n\n```python\nf.subs({x: 2, y: 3}).evalf()\n```\n\n#### Calculus with `sympy`\n\nEvaluate the following integral: $\\int_{0}^{2} x \\,dx$\n\n\n```python\nexpr = sp.integrate(\"x\", (\"x\", 0, 2))\nexpr\n```\n\nLets compare with `numpy`'s built in `trapz` method\n\n\n```python\nfunc = lambda x: x\nxvals = np.linspace(0, 2, 5)\nfunc_vals = np.array([func(x) for x in xvals])\na = np.trapz(func_vals, x=xvals)\na\n```\n\n\n```python\nexpr.evalf() == a\n```\n\n### Differential Equations with Sympy\n\nFind $u(x)$ for $u'(x) + u(x) = x$, with $u(0) = 3$. Plot the solution on $x\\in[0,10]$\n\n\n```python\nx = sp.Symbol(\"x\")\nu = sp.Function(\"u\")\n\n# recast equation so that all terms appear on left hand side\nics = {u(0): 3}\nde = sp.diff(u(x), x) + u(x) - x\n\ngen_sol = sp.dsolve(de, u(x)).rhs\nspec_sol = sp.dsolve(de, u(x), ics=ics, simplify=False)\ngen_sol\n```\n\n\n```python\nspec_sol\n```\n\nFind the coefficients\n\n\n```python\ncoeffs = sp.solve([gen_sol.subs(x, 0) - 3], \"C1\")\nsol = gen_sol.subs(coeffs)\nsol\n```\n\nNow we plot with `matplotlib`. `matplotlib` offers plotting functionality very similar to Matlab\n\n\n```python\n# \"magic\" command below allows inline printing of plots\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n\n```python\ndx = .25\nxvals = np.arange(0, 10, dx)\nsol_vals = [float(sol.subs({x: xval}).evalf()) for xval in xvals]\nplt.plot(xvals, sol_vals)\n```\n\n#### Numeric Solution\n\nLet's now find $u(x)$ numerically using finite differencing.\n\nThe forward difference operator is\n\n$\\frac{df}{dx} \\approx \\frac{f(x + \\Delta{x}) - f(x)}{\\Delta{x}}$\n\nSubstituting the finite difference relation for $u'$ gives\n\n$u(x + \\Delta{x}) = u(x)(1 - \\Delta{x}) + x \\Delta{x}$\n\nSince $u(x=0)$ is known ($u(0) = 3$), we are now ready to solve for $u(x + \\Delta{x})$ iteratively\n\n\n```python\n# dx and xvals defined above\n\nu = [3.]\nfor x in xvals[1:]:\n u.append(u[-1] * (1 - dx) + x * dx)\nu = np.array(u)\n```\n\n##### Comparison\n\n\n```python\n# Evaluate solution over interval [0, 10] and plot\nplt.plot(xvals, sol_vals, label=\"Analytic\")\nplt.plot(xvals, u, \"r+\", label=\"Approximate\")\nplt.xlabel(\"x\")\nplt.ylabel(\"u(x)\")\nplt.legend(loc=\"best\");\n```\n", "meta": {"hexsha": "9569ac8bc3b38b63724c64e31e2bf9a015bcdb42", "size": 47542, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lessons/Lesson02_IntroductionToPython.ipynb", "max_stars_repo_name": "jzw0025/fem-with-python", "max_stars_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 148, "max_stars_repo_stars_event_min_datetime": "2015-11-05T16:32:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:42:26.000Z", "max_issues_repo_path": "Lessons/Lesson02_IntroductionToPython.ipynb", "max_issues_repo_name": "pinkieli/fem-with-python", "max_issues_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lessons/Lesson02_IntroductionToPython.ipynb", "max_forks_repo_name": "pinkieli/fem-with-python", "max_forks_repo_head_hexsha": "ff55de94475de382f916a8483c84dc2d300fcd0e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 74, "max_forks_repo_forks_event_min_datetime": "2016-02-17T13:23:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T07:48:27.000Z", "avg_line_length": 23.2820763957, "max_line_length": 536, "alphanum_fraction": 0.5391233015, "converted": true, "num_tokens": 6243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.17672493032740852}} {"text": "```python\n%pylab inline\n%config InlineBackend.figure_format = 'retina'\nfrom ipywidgets import interact\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\nTurn in an image (e.g., screenshot) or PDF copy of any code that is part of your answer. Make sure all images and PDF pages are properly rotated. Make sure that all pages are clearly visible. \n\nTips: Use the document scanner function on your smart phone to take better page \"scans\" using your camera. Make sure your screen is not shifted toward warmer colours (some devices filter blue light at night) giving it a dim and orange appearance. \n\n# Q1\n\n## A\nDerive a method for computing the determinant of a matrix $A\\in \\mathbb{R}^{n\\times n}$ using Gaussian elimination with partial pivoting. **Hint: use the fact that a permutation matrix is an orthogonal matrix.**\n\n------------------------------------------------------------------------------\n\nFor Gaussian elimination with partial pivoting we have \n$$ P A = LU, $$\nwhere $P$ is a permutation matrix. Since the permutation matrix is an orthogonal matrix, it is also nonsingular. Taking the determinant to both sides of the above equation yields $\\det(P) \\det(A) = \\det(L)\\det(U)$. Since $\\det(L) = 1$ we have that $\\det(A) = \\det(U)/\\det(P)$. If we know $\\det(P)$ then our formula is given by $\\det(A) = \\frac{1}{\\det(P)} \\prod_{i=1}^n u_{ii}$. This last follows from the fact that $U$ is upper triangular.\n\nSince $P$ is an orthogonal matrix we have that $I = P^T P$, and it follows that $1 = \\det(I) = \\det(P^T P) = \\det(P^T)\\det(P) = \\det(P)^2$. Hence $\\det(P) = \\pm 1$. to determine the sign of the determinant, we define $m$ to be the number of row swaps used in Gauassian elimination with partial pivoting, and we define $\\sigma = (-1)^m$. The matrix $P$ is rarely formed explicitly. Instead a vector of row permutations is stored and one can keep track of the number of row swaps that are used. One can show that $\\det(P) = \\sigma$. This last step requires no additional floating point operations to compute, since the information is obtained from the decomposition without extra work.\n\nOur final formula becomes\n$$\\det(A) = \\sigma\\prod_{i=1}^n u_{ii}.$$\n\n\n\n\n## B\nAssume that the LU decomposition has already been computed. Show that the method for computing the determinant requires $n$ floating point operations.\n\n------------------------------------------------------------------------------\n\nThe determinant formula in part A requires exactly $n$ multiplications.\n\n# Q2\nLet $b + \\delta b$ be a perturbation of the vector $b\\neq 0$ and let $x$ and $\\delta x$ be such that $Ax = b$ and $A(x + \\delta x) = b + \\delta b$, where $A$ is a given nonsingular matrix. Show that \n$$\n\\frac{\\Vert \\delta x \\Vert }{\\Vert x \\Vert } \\leq \\kappa(A) \\frac{\\Vert \\delta b \\Vert }{\\Vert b \\Vert }.\n$$\n\n------------------------------------------------------------------------------\n\nFrom $A(x + \\delta x) = b + \\delta b$ we use $Ax = b$ and solve for $\\delta x$ to get $ A\\delta x = \\delta b $.\nSince $A$ is invertible, we have $\\delta x = A^{-1}\\delta b$. Taking norms to both sides yields $\\Vert \\delta x \\Vert = \\Vert A^{-1}\\delta b \\Vert$. Using the submultiplicative property, we get $\\Vert \\delta x \\Vert \\leq \\Vert A^{-1}\\Vert \\Vert \\delta b \\Vert$. Since $A$ is nonsingular and $b \\neq 0$, we have that $\\Vert x \\Vert \\neq 0$. We can multiply and divide by $\\Vert x \\Vert$ to get $\\frac{\\Vert \\delta x \\Vert}{\\Vert x \\Vert} \\leq \\Vert A^{-1}\\Vert \\frac{\\Vert \\delta b \\Vert}{\\Vert x \\Vert}$. Using $\\Vert b \\Vert \\leq \\Vert A \\Vert \\Vert x \\Vert$ and $\\Vert A \\Vert \\neq 0$ (since $A$ is nonsingular) we have $\\frac{\\Vert \\delta x \\Vert}{\\Vert x \\Vert} \\leq \\Vert A^{-1}\\Vert \\frac{\\Vert \\delta b \\Vert}{\\Vert b \\Vert / \\Vert A \\Vert }$. The result follows after substitution of $\\kappa(A) = \\Vert A \\Vert \\Vert A^{-1} \\Vert$.\n\n\n# Q3\nThe book states without proof that if $\\Vert \\delta A \\Vert < \\frac{1}{\\Vert A^{-1}\\Vert}$ then the bound on the relative error can be written as\n$$ \n \\frac{\\Vert x - \\hat{x} \\Vert}{\\Vert x \\Vert} \\leq \\frac{\\kappa(A)}{1 - \\kappa(A)\\frac{\\Vert \\delta A\\Vert}{\\Vert A\\Vert}} \n \\left(\\frac{\\Vert \\delta b \\Vert}{\\Vert b\\Vert} + \\frac{\\Vert\\delta A \\Vert}{\\Vert A\\Vert} \\right). \n$$\n\nIn what follows, let $A$, $B$, and $\\delta A$ be real $n\\times n$ matrices. \n\nWe saw an incomplete proof in lecture that assumed $A + \\delta A$ is nonsingular. In the following, you will show that if $\\Vert \\delta A \\Vert < \\frac{1}{\\Vert A^{-1}\\Vert}$ then $A + \\delta A$ is nonsingular.\n\n## A\nShow that if the spectral radius $\\rho(A) < 1$ then the matrix $A - I$ is nonsingular. **Hint: use the definition of the spectral radius and the characteristic equation, $\\det(A-\\lambda I) = 0$, for the eigenvalues of $A$.**\n\n---------------------------------------------------------------------------------\n\nIf $\\rho(A) < 1$ then by definition all of the eigenvalues $\\vert \\lambda \\vert < 1$, which means that there are no eigenvalues on the unit circle in the complex plane. It follows that $\\det(A \\pm I) \\neq 0$. Hence $A - I$ is nonsingular.\n\n## B\nShow that if $A$ is nonsingular and $\\Vert A - B\\Vert < \\frac{1}{\\Vert A^{-1} \\Vert}$ then $B$ is nonsingular. **Hint: use $B = A[I - A^{-1}(A - B)]$ and part A**\n\n---------------------------------------------------------------------------------\n\nWe can write $B = A[I - A^{-1}(A - B)]$. It follows that since $A$ is nonsingular then $B$ is nonsingular if $I- A^{-1}(A - B)$ is nonsingular. From part A, we know that $I- A^{-1}(A - B)$ is nonsingular if $\\rho( A^{-1}(A - B)) < 1$. To show this we use the fact that for any square matrix $M$ that $\\rho(M) \\leq \\Vert M\\Vert$, and we use the assumption $\\Vert A - B\\Vert < \\frac{1}{\\Vert A^{-1} \\Vert}$. We have that\n$$\\rho(A^{-1}(A - B)) \\leq \\Vert A^{-1}(A - B) \\Vert \\leq \\Vert A^{-1}\\Vert \\Vert (A - B) \\Vert < 1.$$\n\n## C\nShow that if $A$ is nonsingular and $\\Vert \\delta A\\Vert < \\frac{1}{\\Vert A^{-1} \\Vert}$, then $A + \\delta A$ is nonsingular.\n\n---------------------------------------------------------------------------------\n\nLet $B = A + \\delta A$ and apply part B.\n\n# Q4\nTridiagonal matrices appear often. Due to their simple structure, it is possible to significantly speed up the computation of the LU decomposition.\n\n## A\nImplement Gaussian elimination for computing $A = LU$ of the form\n\\begin{equation}\n\\begin{bmatrix}\na_1 & c_1 & & & & \\\\\nb_2 & a_2 & c_2& & & \\\\\n & b_3& a_3& c_3& & \\\\\n & &\\ddots & \\ddots & \\ddots & \\\\\n & & & \\ddots & \\ddots& c_{n-1}\\\\\n & & & &b_n & a_n\n\\end{bmatrix} =\n\\begin{bmatrix}\n1 & & & & & \\\\\nl_2 & 1& & & & \\\\\n & l_3 & 1& & & \\\\\n & & \\ddots & \\ddots & & \\\\\n & & & \\ddots& \\ddots& \\\\\n & & & & l_n & 1\n\\end{bmatrix}\n\\begin{bmatrix}\n u_1& c_1& & & & \\\\\n & u_2& c_2 & & & \\\\\n & & u_3& c_3 & & \\\\\n & & & \\ddots& \\ddots& \\\\\n & & & & \\ddots& c_{n-1}\\\\\n & & & & & u_n\n\\end{bmatrix}\n\\end{equation}\nYour function should take three input arguments: the vectors `a`, `b`, and `c` containing the diagonals of the matrix $A$. It should return two vectors `l` and `u` containing the elements from the above $LU$ decomposition (ie the vectors $l$ and $u$ have entries $l_i$ and $u_i$).\n\n### Solution\nWe usually index vectors and matrices in linear algebra starting with the value 1. For example, the first value of a vector $x$ is $x_1$. In Python and most programming languages, indexing of array starts with the value 0. For example, the first value stored in an array `x` is `x[0]`. For this reason, our formulas and our code will use different indices. Let $i$ be the index of the vector $x$, and let `k` be the index for the array `x`. We set $i = $ `k+1`. Then $x_i = $ `x[i-1]` and `x[k]` $=x_{k+1}$. \n\n### Version 1\nIn this version, I pad the arrays `b` and `l` with a leading `nan` so that the indices line up. This way, $b_2$ corresponds to `b[1]` and $l_2$ corresponds to `l[1]`. Note that this is consistent with the other vectors; i.e., $a_1$ corresponds to `a[0]`.\n\n\n```python\ndef tridiag_solve_version1(a, b, c):\n n = a.size\n u = zeros(n)\n u[0] = a[0]\n l = zeros(n)\n l[0] = nan\n for i in arange(2, n+1):\n k = i-1\n l[k] = b[k]/u[k-1]\n u[k] = a[k] - l[k]*c[k-1]\n return l, u\n```\n\n### Version 2\nIn this version, I do not pad the arrays `b` and `l` with a leading entry to align the indices. Instead, I adjust the formulas so that $u_2$ and $l_2$ correspond to `u[0]` and `l[0]`, respectively. In other words, there is a different relationship between $i$ and the index for `u` and `l`. Let `p` $=i-2$ index these vectors, but not the others (for the others we have `k` $=i-1$).\n\n\n```python\ndef tridiag_solve_version2(a, b, c):\n n = a.size\n u = zeros(n)\n u[0] = a[0]\n l = zeros(n-1)\n for i in arange(2, n+1):\n k = i-1\n p = i-2\n l[p] = b[p]/u[k-1]\n u[k] = a[k] - l[p]*c[k-1]\n return l, u\n```\n\n## B\nUse your function from part A to compute the LU decomposition of \n$$ \nA = \n\\begin{bmatrix}\n1 & -\\frac{1}{2} & & & & \\\\\n-\\frac{2}{2} & 2& -\\frac{2}{2}& & & \\\\\n & -\\frac{3}{2}& 3& -\\frac{3}{2}& & \\\\\n & & \\ddots & \\ddots& \\ddots& \\\\\n & & & \\ddots& \\ddots& -\\frac{10-1}{2} \\\\\n & & & & -\\frac{10}{2}& 10\n\\end{bmatrix}.\n$$\nInclude a print out of the elements of `l` and `u` rounded to three decimal places.\n\n### Solution\n### Version 1\nIn this version, I pad the arrays `b` and `l` with a leading `nan` so that the indices line up. This way, $b_2$ corresponds to `b[1]` and $l_2$ corresponds to `l[1]`. Note that this is consistent with the other vectors; i.e., $a_1$ corresponds to `a[0]`. \n\n\n```python\nn = 10\na = arange(n) + 1.\nb = -(arange(n)-1 + 2.)/2.\nb[0] = nan\nc = -(arange(n-1) + 1.)/2.\n\n\nl, u = tridiag_solve_version1(a, b, c)\n\nprint(around(l, 3))\nprint(around(u, 3))\n```\n\n [nan -1. -1. -1. -1. -1. -1. -1. -1. -1.]\n [1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5]\n\n\n\n```python\n## check \na_check = c*l[1:] + u[1:]\n## output should be 2, 3, 4, ..., 10\nprint(around(a_check, 3))\n\nb_check = l[1:]*u[:-1]\n## output should be -1, -1.5, -2.5, ..., -5\nprint(around(b_check, 3))\n```\n\n [ 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n [-1. -1.5 -2. -2.5 -3. -3.5 -4. -4.5 -5. ]\n\n\n\n```python\n## check 2\nfrom scipy.linalg import lu as lu\nA = diag(b[1:], -1) + diag(a) + diag(c, 1)\n_, L, U = lu(A)\nprint(around(L, 2))\nprint(around(U, 2))\nprint(norm(L@U - A, 2))\n```\n\n [[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [-1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. -1. 1. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. -1. 1. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. -1. 1. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. -1. 1. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. -1. 1. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. -1. 1. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. -1. 1. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. -1. 1.]]\n [[ 1. -0.5 0. 0. 0. 0. 0. 0. 0. 0. ]\n [ 0. 1.5 -1. 0. 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 2. -1.5 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 2.5 -2. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 3. -2.5 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 3.5 -3. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 4. -3.5 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0. 4.5 -4. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 5. -4.5]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 5.5]]\n 0.0\n\n\n### Version 2\nIn this version, I do not pad the arrays `b` and `l` with a leading entry to align the indices. Instead, I adjust the formulas so that $u_2$ and $l_2$ correspond to `u[0]` and `l[0]`, respectively. In other words, there is a different relationship between $i$ and the index for `u` and `l`. Let `p` $=i-2$ index these vectors, but not the others (for the others we have `k` $=i-1$).\n\n\n```python\nn = 10\na = arange(n) + 1.\nb = -(arange(n-1) + 2.)/2.\nc = -(arange(n-1) + 1.)/2.\n\n\nl, u = tridiag_solve_version2(a, b, c)\n\nprint(around(l, 3))\nprint(around(u, 3))\n```\n\n [-1. -1. -1. -1. -1. -1. -1. -1. -1.]\n [1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5]\n\n\n\n```python\n## check \na_check = c*l + u[1:]\n## output should be 2, 3, 4, ..., 10\nprint(around(a_check, 3))\n\nb_check = l*u[:-1]\n## output should be -1, -1.5, -2.5, ..., -5\nprint(around(b_check, 3))\n```\n\n [ 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n [-1. -1.5 -2. -2.5 -3. -3.5 -4. -4.5 -5. ]\n\n\n\n```python\n## check 2\nfrom scipy.linalg import lu as lu\nA = diag(b, -1) + diag(a) + diag(c, 1)\n_, L, U = lu(A)\nprint(around(L, 2))\nprint(around(U, 2))\nprint(norm(L@U - A, 2))\n```\n\n [[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n [-1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. -1. 1. 0. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. -1. 1. 0. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. -1. 1. 0. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. -1. 1. 0. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. -1. 1. 0. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. -1. 1. 0. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. -1. 1. 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. -1. 1.]]\n [[ 1. -0.5 0. 0. 0. 0. 0. 0. 0. 0. ]\n [ 0. 1.5 -1. 0. 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 2. -1.5 0. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 2.5 -2. 0. 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 3. -2.5 0. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 3.5 -3. 0. 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 4. -3.5 0. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0. 4.5 -4. 0. ]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 5. -4.5]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 5.5]]\n 0.0\n\n\n\n## C\nDetermine the total number of floating point operations (i.e., the combined number of additions, subtractions, multiplications, and divisions) required for computing the LU decomposition of an $n\\times n$ matrix with your method.\n\n-------------------------------\n\nThere are $n-1$ steps in the loop (the first step is just $l_i = a_i$) and each loop has three operations. This yields $3n - 3$ total operations.\n\n\n```python\n\n```\n", "meta": {"hexsha": "b2b622852307e3772fe74deed2b3a4db92c191c4", "size": 19371, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Homework 7 Solutions.ipynb", "max_stars_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_stars_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework 7 Solutions.ipynb", "max_issues_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_issues_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework 7 Solutions.ipynb", "max_forks_repo_name": "newby-jay/MATH381-Fall2021-JupyterNotebooks", "max_forks_repo_head_hexsha": "9181fb6e154081de26fb267e0794a67f60ae11a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1887966805, "max_line_length": 924, "alphanum_fraction": 0.4661607558, "converted": true, "num_tokens": 5696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.17610088422437556}} {"text": "```python\n%matplotlib inline\n```\n\n\n\n# Background information on filtering\n\n\nHere we give some background information on filtering in general,\nand how it is done in MNE-Python in particular.\nRecommended reading for practical applications of digital\nfilter design can be found in Parks & Burrus [1]_ and\nIfeachor and Jervis [2]_, and for filtering in an\nM/EEG context we recommend reading Widmann *et al.* 2015 [7]_.\nTo see how to use the default filters in MNE-Python on actual data, see\nthe `tut_artifacts_filter` tutorial.\n\nProblem statement\n=================\n\nThe practical issues with filtering electrophysiological data are covered\nwell by Widmann *et al.* in [7]_, in a follow-up to an article where they\nconclude with this statement:\n\n Filtering can result in considerable distortions of the time course\n (and amplitude) of a signal as demonstrated by VanRullen (2011) [[3]_].\n Thus, filtering should not be used lightly. However, if effects of\n filtering are cautiously considered and filter artifacts are minimized,\n a valid interpretation of the temporal dynamics of filtered\n electrophysiological data is possible and signals missed otherwise\n can be detected with filtering.\n\nIn other words, filtering can increase SNR, but if it is not used carefully,\nit can distort data. Here we hope to cover some filtering basics so\nusers can better understand filtering tradeoffs, and why MNE-Python has\nchosen particular defaults.\n\n\nFiltering basics\n================\n\nLet's get some of the basic math down. In the frequency domain, digital\nfilters have a transfer function that is given by:\n\n\\begin{align}H(z) &= \\frac{b_0 + b_1 z^{-1} + b_2 z^{-2} + ... + b_M z^{-M}}\n {1 + a_1 z^{-1} + a_2 z^{-2} + ... + a_N z^{-M}} \\\\\n &= \\frac{\\sum_0^Mb_kz^{-k}}{\\sum_1^Na_kz^{-k}}\\end{align}\n\nIn the time domain, the numerator coefficients $b_k$ and denominator\ncoefficients $a_k$ can be used to obtain our output data\n$y(n)$ in terms of our input data $x(n)$ as:\n\n\\begin{align}:label: summations\n\n y(n) &= b_0 x(n) + b_1 x(n-1) + ... + b_M x(n-M)\n - a_1 y(n-1) - a_2 y(n - 2) - ... - a_N y(n - N)\\\\\n &= \\sum_0^M b_k x(n-k) - \\sum_1^N a_k y(n-k)\\end{align}\n\nIn other words, the output at time $n$ is determined by a sum over:\n\n 1. The numerator coefficients $b_k$, which get multiplied by\n the previous input $x(n-k)$ values, and\n 2. The denominator coefficients $a_k$, which get multiplied by\n the previous output $y(n-k)$ values.\n\nNote that these summations in :eq:`summations` correspond nicely to\n(1) a weighted `moving average`_ and (2) an autoregression_.\n\nFilters are broken into two classes: FIR_ (finite impulse response) and\nIIR_ (infinite impulse response) based on these coefficients.\nFIR filters use a finite number of numerator\ncoefficients $b_k$ ($\\forall k, a_k=0$), and thus each output\nvalue of $y(n)$ depends only on the $M$ previous input values.\nIIR filters depend on the previous input and output values, and thus can have\neffectively infinite impulse responses.\n\nAs outlined in [1]_, FIR and IIR have different tradeoffs:\n\n * A causal FIR filter can be linear-phase -- i.e., the same time delay\n across all frequencies -- whereas a causal IIR filter cannot. The phase\n and group delay characteristics are also usually better for FIR filters.\n * IIR filters can generally have a steeper cutoff than an FIR filter of\n equivalent order.\n * IIR filters are generally less numerically stable, in part due to\n accumulating error (due to its recursive calculations).\n\nIn MNE-Python we default to using FIR filtering. As noted in Widmann *et al.*\n2015 [7]_:\n\n Despite IIR filters often being considered as computationally more\n efficient, they are recommended only when high throughput and sharp\n cutoffs are required (Ifeachor and Jervis, 2002 [2]_, p. 321),\n ...FIR filters are easier to control, are always stable, have a\n well-defined passband, can be corrected to zero-phase without\n additional computations, and can be converted to minimum-phase.\n We therefore recommend FIR filters for most purposes in\n electrophysiological data analysis.\n\nWhen designing a filter (FIR or IIR), there are always tradeoffs that\nneed to be considered, including but not limited to:\n\n 1. Ripple in the pass-band\n 2. Attenuation of the stop-band\n 3. Steepness of roll-off\n 4. Filter order (i.e., length for FIR filters)\n 5. Time-domain ringing\n\nIn general, the sharper something is in frequency, the broader it is in time,\nand vice-versa. This is a fundamental time-frequency tradeoff, and it will\nshow up below.\n\nFIR Filters\n===========\n\nFirst we will focus first on FIR filters, which are the default filters used by\nMNE-Python.\n\n\n\nDesigning FIR filters\n---------------------\nHere we'll try designing a low-pass filter, and look at trade-offs in terms\nof time- and frequency-domain filter characteristics. Later, in\n`tut_effect_on_signals`, we'll look at how such filters can affect\nsignals when they are used.\n\nFirst let's import some useful tools for filtering, and set some default\nvalues for our data that are reasonable for M/EEG data.\n\n\n\n\n```python\nimport numpy as np\nfrom scipy import signal, fftpack\nimport matplotlib.pyplot as plt\n\nfrom mne.time_frequency.tfr import morlet\nfrom mne.viz import plot_filter, plot_ideal_filter\n\nimport mne\n\nsfreq = 1000.\nf_p = 40.\nflim = (1., sfreq / 2.) # limits for plotting\n```\n\nTake for example an ideal low-pass filter, which would give a value of 1 in\nthe pass-band (up to frequency $f_p$) and a value of 0 in the stop-band\n(down to frequency $f_s$) such that $f_p=f_s=40$ Hz here\n(shown to a lower limit of -60 dB for simplicity):\n\n\n\n\n```python\nnyq = sfreq / 2. # the Nyquist frequency is half our sample rate\nfreq = [0, f_p, f_p, nyq]\ngain = [1, 1, 0, 0]\n\nthird_height = np.array(plt.rcParams['figure.figsize']) * [1, 1. / 3.]\nax = plt.subplots(1, figsize=third_height)[1]\nplot_ideal_filter(freq, gain, ax, title='Ideal %s Hz lowpass' % f_p, flim=flim)\n```\n\nThis filter hypothetically achieves zero ripple in the frequency domain,\nperfect attenuation, and perfect steepness. However, due to the discontunity\nin the frequency response, the filter would require infinite ringing in the\ntime domain (i.e., infinite order) to be realized. Another way to think of\nthis is that a rectangular window in frequency is actually sinc_ function\nin time, which requires an infinite number of samples, and thus infinite\ntime, to represent. So although this filter has ideal frequency suppression,\nit has poor time-domain characteristics.\n\nLet's try to naïvely make a brick-wall filter of length 0.1 sec, and look\nat the filter itself in the time domain and the frequency domain:\n\n\n\n\n```python\nn = int(round(0.1 * sfreq)) + 1\nt = np.arange(-n // 2, n // 2) / sfreq # center our sinc\nh = np.sinc(2 * f_p * t) / (4 * np.pi)\nplot_filter(h, sfreq, freq, gain, 'Sinc (0.1 sec)', flim=flim)\n```\n\nThis is not so good! Making the filter 10 times longer (1 sec) gets us a\nbit better stop-band suppression, but still has a lot of ringing in\nthe time domain. Note the x-axis is an order of magnitude longer here,\nand the filter has a correspondingly much longer group delay (again equal\nto half the filter length, or 0.5 seconds):\n\n\n\n\n```python\nn = int(round(1. * sfreq)) + 1\nt = np.arange(-n // 2, n // 2) / sfreq\nh = np.sinc(2 * f_p * t) / (4 * np.pi)\nplot_filter(h, sfreq, freq, gain, 'Sinc (1.0 sec)', flim=flim)\n```\n\nLet's make the stop-band tighter still with a longer filter (10 sec),\nwith a resulting larger x-axis:\n\n\n\n\n```python\nn = int(round(10. * sfreq)) + 1\nt = np.arange(-n // 2, n // 2) / sfreq\nh = np.sinc(2 * f_p * t) / (4 * np.pi)\nplot_filter(h, sfreq, freq, gain, 'Sinc (10.0 sec)', flim=flim)\n```\n\nNow we have very sharp frequency suppression, but our filter rings for the\nentire second. So this naïve method is probably not a good way to build\nour low-pass filter.\n\nFortunately, there are multiple established methods to design FIR filters\nbased on desired response characteristics. These include:\n\n 1. The Remez_ algorithm (:func:`scipy.signal.remez`, `MATLAB firpm`_)\n 2. Windowed FIR design (:func:`scipy.signal.firwin2`, `MATLAB fir2`_\n and :func:`scipy.signal.firwin`)\n 3. Least squares designs (:func:`scipy.signal.firls`, `MATLAB firls`_)\n 4. Frequency-domain design (construct filter in Fourier\n domain and use an :func:`IFFT ` to invert it)\n\n

Note

Remez and least squares designs have advantages when there are\n \"do not care\" regions in our frequency response. However, we want\n well controlled responses in all frequency regions.\n Frequency-domain construction is good when an arbitrary response\n is desired, but generally less clean (due to sampling issues) than\n a windowed approach for more straightfroward filter applications.\n Since our filters (low-pass, high-pass, band-pass, band-stop)\n are fairly simple and we require precisel control of all frequency\n regions, here we will use and explore primarily windowed FIR\n design.

\n\nIf we relax our frequency-domain filter requirements a little bit, we can\nuse these functions to construct a lowpass filter that instead has a\n*transition band*, or a region between the pass frequency $f_p$\nand stop frequency $f_s$, e.g.:\n\n\n\n\n```python\ntrans_bandwidth = 10 # 10 Hz transition band\nf_s = f_p + trans_bandwidth # = 50 Hz\n\nfreq = [0., f_p, f_s, nyq]\ngain = [1., 1., 0., 0.]\nax = plt.subplots(1, figsize=third_height)[1]\ntitle = '%s Hz lowpass with a %s Hz transition' % (f_p, trans_bandwidth)\nplot_ideal_filter(freq, gain, ax, title=title, flim=flim)\n```\n\nAccepting a shallower roll-off of the filter in the frequency domain makes\nour time-domain response potentially much better. We end up with a\nsmoother slope through the transition region, but a *much* cleaner time\ndomain signal. Here again for the 1 sec filter:\n\n\n\n\n```python\nh = signal.firwin2(n, freq, gain, nyq=nyq)\nplot_filter(h, sfreq, freq, gain, 'Windowed 10-Hz transition (1.0 sec)',\n flim=flim)\n```\n\nSince our lowpass is around 40 Hz with a 10 Hz transition, we can actually\nuse a shorter filter (5 cycles at 10 Hz = 0.5 sec) and still get okay\nstop-band attenuation:\n\n\n\n\n```python\nn = int(round(sfreq * 0.5)) + 1\nh = signal.firwin2(n, freq, gain, nyq=nyq)\nplot_filter(h, sfreq, freq, gain, 'Windowed 10-Hz transition (0.5 sec)',\n flim=flim)\n```\n\nBut then if we shorten the filter too much (2 cycles of 10 Hz = 0.2 sec),\nour effective stop frequency gets pushed out past 60 Hz:\n\n\n\n\n```python\nn = int(round(sfreq * 0.2)) + 1\nh = signal.firwin2(n, freq, gain, nyq=nyq)\nplot_filter(h, sfreq, freq, gain, 'Windowed 10-Hz transition (0.2 sec)',\n flim=flim)\n```\n\nIf we want a filter that is only 0.1 seconds long, we should probably use\nsomething more like a 25 Hz transition band (0.2 sec = 5 cycles @ 25 Hz):\n\n\n\n\n```python\ntrans_bandwidth = 25\nf_s = f_p + trans_bandwidth\nfreq = [0, f_p, f_s, nyq]\nh = signal.firwin2(n, freq, gain, nyq=nyq)\nplot_filter(h, sfreq, freq, gain, 'Windowed 50-Hz transition (0.2 sec)',\n flim=flim)\n```\n\nSo far we have only discussed *acausal* filtering, which means that each\nsample at each time point $t$ is filtered using samples that come\nafter ($t + \\Delta t$) *and* before ($t - \\Delta t$) $t$.\nIn this sense, each sample is influenced by samples that come both before\nand after it. This is useful in many cases, espcially because it does not\ndelay the timing of events.\n\nHowever, sometimes it can be beneficial to use *causal* filtering,\nwhereby each sample $t$ is filtered only using time points that came\nafter it.\n\nNote that the delay is variable (whereas for linear/zero-phase filters it\nis constant) but small in the pass-band. Unlike zero-phase filters, which\nrequire time-shifting backward the output of a linear-phase filtering stage\n(and thus becoming acausal), minimum-phase filters do not require any\ncompensation to achieve small delays in the passband. Note that as an\nartifact of the minimum phase filter construction step, the filter does\nnot end up being as steep as the linear/zero-phase version.\n\nWe can construct a minimum-phase filter from our existing linear-phase\nfilter with the ``minimum_phase`` function (that will be in SciPy 0.19's\n:mod:`scipy.signal`), and note that the falloff is not as steep:\n\n\n\n\n```python\nh_min = mne.fixes.minimum_phase(h)\nplot_filter(h_min, sfreq, freq, gain, 'Minimum-phase', flim=flim)\n```\n\n\nApplying FIR filters\n--------------------\n\nNow lets look at some practical effects of these filters by applying\nthem to some data.\n\nLet's construct a Gaussian-windowed sinusoid (i.e., Morlet imaginary part)\nplus noise (random + line). Note that the original, clean signal contains\nfrequency content in both the pass band and transition bands of our\nlow-pass filter.\n\n\n\n\n```python\ndur = 10.\ncenter = 2.\nmorlet_freq = f_p\ntlim = [center - 0.2, center + 0.2]\ntticks = [tlim[0], center, tlim[1]]\nflim = [20, 70]\n\nx = np.zeros(int(sfreq * dur) + 1)\nblip = morlet(sfreq, [morlet_freq], n_cycles=7)[0].imag / 20.\nn_onset = int(center * sfreq) - len(blip) // 2\nx[n_onset:n_onset + len(blip)] += blip\nx_orig = x.copy()\n\nrng = np.random.RandomState(0)\nx += rng.randn(len(x)) / 1000.\nx += np.sin(2. * np.pi * 60. * np.arange(len(x)) / sfreq) / 2000.\n```\n\nFilter it with a shallow cutoff, linear-phase FIR (which allows us to\ncompensate for the constant filter delay):\n\n\n\n\n```python\ntransition_band = 0.25 * f_p\nf_s = f_p + transition_band\nfilter_dur = 6.6 / transition_band / 2. # sec\nn = int(sfreq * filter_dur)\nfreq = [0., f_p, f_s, sfreq / 2.]\ngain = [1., 1., 0., 0.]\n# This would be equivalent:\nh = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,\n fir_design='firwin')\nx_v16 = np.convolve(h, x)[len(h) // 2:]\n\nplot_filter(h, sfreq, freq, gain, 'MNE-Python 0.16 default', flim=flim)\n```\n\nFilter it with a different design mode ``fir_design=\"firwin2\"``, and also\ncompensate for the constant filter delay. This method does not produce\nquite as sharp a transition compared to ``fir_design=\"firwin\"``, despite\nbeing twice as long:\n\n\n\n\n```python\ntransition_band = 0.25 * f_p\nf_s = f_p + transition_band\nfilter_dur = 6.6 / transition_band # sec\nn = int(sfreq * filter_dur)\nfreq = [0., f_p, f_s, sfreq / 2.]\ngain = [1., 1., 0., 0.]\n# This would be equivalent:\n# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)\nh = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,\n fir_design='firwin2')\nx_v14 = np.convolve(h, x)[len(h) // 2:]\n\nplot_filter(h, sfreq, freq, gain, 'MNE-Python 0.14 default', flim=flim)\n```\n\nThis is actually set to become the default type of filter used in MNE-Python\nin 0.14 (see `tut_filtering_in_python`).\n\nLet's also filter with the MNE-Python 0.13 default, which is a\nlong-duration, steep cutoff FIR that gets applied twice:\n\n\n\n\n```python\ntransition_band = 0.5 # Hz\nf_s = f_p + transition_band\nfilter_dur = 10. # sec\nn = int(sfreq * filter_dur)\nfreq = [0., f_p, f_s, sfreq / 2.]\ngain = [1., 1., 0., 0.]\n# This would be equivalent\n# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)\nh = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,\n h_trans_bandwidth=transition_band,\n filter_length='%ss' % filter_dur,\n fir_design='firwin2')\nx_v13 = np.convolve(np.convolve(h, x)[::-1], h)[::-1][len(h) - 1:-len(h) - 1]\n\nplot_filter(h, sfreq, freq, gain, 'MNE-Python 0.13 default', flim=flim)\n```\n\nLet's also filter it with the MNE-C default, which is a long-duration\nsteep-slope FIR filter designed using frequency-domain techniques:\n\n\n\n\n```python\nh = mne.filter.design_mne_c_filter(sfreq, l_freq=None, h_freq=f_p + 2.5)\nx_mne_c = np.convolve(h, x)[len(h) // 2:]\n\ntransition_band = 5 # Hz (default in MNE-C)\nf_s = f_p + transition_band\nfreq = [0., f_p, f_s, sfreq / 2.]\ngain = [1., 1., 0., 0.]\nplot_filter(h, sfreq, freq, gain, 'MNE-C default', flim=flim)\n```\n\nAnd now an example of a minimum-phase filter:\n\n\n\n\n```python\nh = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,\n phase='minimum', fir_design='firwin')\nx_min = np.convolve(h, x)\ntransition_band = 0.25 * f_p\nf_s = f_p + transition_band\nfilter_dur = 6.6 / transition_band # sec\nn = int(sfreq * filter_dur)\nfreq = [0., f_p, f_s, sfreq / 2.]\ngain = [1., 1., 0., 0.]\nplot_filter(h, sfreq, freq, gain, 'Minimum-phase filter', flim=flim)\n```\n\nBoth the MNE-Python 0.13 and MNE-C filhters have excellent frequency\nattenuation, but it comes at a cost of potential\nringing (long-lasting ripples) in the time domain. Ringing can occur with\nsteep filters, especially on signals with frequency content around the\ntransition band. Our Morlet wavelet signal has power in our transition band,\nand the time-domain ringing is thus more pronounced for the steep-slope,\nlong-duration filter than the shorter, shallower-slope filter:\n\n\n\n\n```python\naxes = plt.subplots(1, 2)[1]\n\n\ndef plot_signal(x, offset):\n t = np.arange(len(x)) / sfreq\n axes[0].plot(t, x + offset)\n axes[0].set(xlabel='Time (sec)', xlim=t[[0, -1]])\n X = fftpack.fft(x)\n freqs = fftpack.fftfreq(len(x), 1. / sfreq)\n mask = freqs >= 0\n X = X[mask]\n freqs = freqs[mask]\n axes[1].plot(freqs, 20 * np.log10(np.abs(X)))\n axes[1].set(xlim=flim)\n\nyticks = np.arange(7) / -30.\nyticklabels = ['Original', 'Noisy', 'FIR-firwin (0.16)', 'FIR-firwin2 (0.14)',\n 'FIR-steep (0.13)', 'FIR-steep (MNE-C)', 'Minimum-phase']\nplot_signal(x_orig, offset=yticks[0])\nplot_signal(x, offset=yticks[1])\nplot_signal(x_v16, offset=yticks[2])\nplot_signal(x_v14, offset=yticks[3])\nplot_signal(x_v13, offset=yticks[4])\nplot_signal(x_mne_c, offset=yticks[5])\nplot_signal(x_min, offset=yticks[6])\naxes[0].set(xlim=tlim, title='FIR, Lowpass=%d Hz' % f_p, xticks=tticks,\n ylim=[-0.200, 0.025], yticks=yticks, yticklabels=yticklabels,)\nfor text in axes[0].get_yticklabels():\n text.set(rotation=45, size=8)\naxes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',\n ylabel='Magnitude (dB)')\nmne.viz.tight_layout()\nplt.show()\n```\n\nIIR filters\n===========\n\nMNE-Python also offers IIR filtering functionality that is based on the\nmethods from :mod:`scipy.signal`. Specifically, we use the general-purpose\nfunctions :func:`scipy.signal.iirfilter` and :func:`scipy.signal.iirdesign`,\nwhich provide unified interfaces to IIR filter design.\n\nDesigning IIR filters\n---------------------\n\nLet's continue with our design of a 40 Hz low-pass filter, and look at\nsome trade-offs of different IIR filters.\n\nOften the default IIR filter is a `Butterworth filter`_, which is designed\nto have a *maximally flat pass-band*. Let's look at a few orders of filter,\ni.e., a few different number of coefficients used and therefore steepness\nof the filter:\n\n

Note

Notice that the group delay (which is related to the phase) of\n the IIR filters below are not constant. In the FIR case, we can\n design so-called linear-phase filters that have a constant group\n delay, and thus compensate for the delay (making the filter\n acausal) if necessary. This cannot be done with IIR filters, as\n they have a non-linear phase (non-constant group delay). As the\n filter order increases, the phase distortion near and in the\n transition band worsens. However, if acausal (forward-backward)\n filtering can be used, e.g. with :func:`scipy.signal.filtfilt`,\n these phase issues can theoretically be mitigated.

\n\n\n\n\n```python\nsos = signal.iirfilter(2, f_p / nyq, btype='low', ftype='butter', output='sos')\nplot_filter(dict(sos=sos), sfreq, freq, gain, 'Butterworth order=2', flim=flim)\n\n# Eventually this will just be from scipy signal.sosfiltfilt, but 0.18 is\n# not widely adopted yet (as of June 2016), so we use our wrapper...\nsosfiltfilt = mne.fixes.get_sosfiltfilt()\nx_shallow = sosfiltfilt(sos, x)\n```\n\nThe falloff of this filter is not very steep.\n\n

Note

Here we have made use of second-order sections (SOS)\n by using :func:`scipy.signal.sosfilt` and, under the\n hood, :func:`scipy.signal.zpk2sos` when passing the\n ``output='sos'`` keyword argument to\n :func:`scipy.signal.iirfilter`. The filter definitions\n given in tut_filtering_basics_ use the polynomial\n numerator/denominator (sometimes called \"tf\") form ``(b, a)``,\n which are theoretically equivalent to the SOS form used here.\n In practice, however, the SOS form can give much better results\n due to issues with numerical precision (see\n :func:`scipy.signal.sosfilt` for an example), so SOS should be\n used when possible to do IIR filtering.

\n\nLet's increase the order, and note that now we have better attenuation,\nwith a longer impulse response:\n\n\n\n\n```python\nsos = signal.iirfilter(8, f_p / nyq, btype='low', ftype='butter', output='sos')\nplot_filter(dict(sos=sos), sfreq, freq, gain, 'Butterworth order=8', flim=flim)\nx_steep = sosfiltfilt(sos, x)\n```\n\nThere are other types of IIR filters that we can use. For a complete list,\ncheck out the documentation for :func:`scipy.signal.iirdesign`. Let's\ntry a Chebychev (type I) filter, which trades off ripple in the pass-band\nto get better attenuation in the stop-band:\n\n\n\n\n```python\nsos = signal.iirfilter(8, f_p / nyq, btype='low', ftype='cheby1', output='sos',\n rp=1) # dB of acceptable pass-band ripple\nplot_filter(dict(sos=sos), sfreq, freq, gain,\n 'Chebychev-1 order=8, ripple=1 dB', flim=flim)\n```\n\nAnd if we can live with even more ripple, we can get it slightly steeper,\nbut the impulse response begins to ring substantially longer (note the\ndifferent x-axis scale):\n\n\n\n\n```python\nsos = signal.iirfilter(8, f_p / nyq, btype='low', ftype='cheby1', output='sos',\n rp=6)\nplot_filter(dict(sos=sos), sfreq, freq, gain,\n 'Chebychev-1 order=8, ripple=6 dB', flim=flim)\n```\n\nApplying IIR filters\n--------------------\n\nNow let's look at how our shallow and steep Butterworth IIR filters\nperform on our Morlet signal from before:\n\n\n\n\n```python\naxes = plt.subplots(1, 2)[1]\nyticks = np.arange(4) / -30.\nyticklabels = ['Original', 'Noisy', 'Butterworth-2', 'Butterworth-8']\nplot_signal(x_orig, offset=yticks[0])\nplot_signal(x, offset=yticks[1])\nplot_signal(x_shallow, offset=yticks[2])\nplot_signal(x_steep, offset=yticks[3])\naxes[0].set(xlim=tlim, title='IIR, Lowpass=%d Hz' % f_p, xticks=tticks,\n ylim=[-0.125, 0.025], yticks=yticks, yticklabels=yticklabels,)\nfor text in axes[0].get_yticklabels():\n text.set(rotation=45, size=8)\naxes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',\n ylabel='Magnitude (dB)')\nmne.viz.adjust_axes(axes)\nmne.viz.tight_layout()\nplt.show()\n```\n\nSome pitfalls of filtering\n==========================\n\nMultiple recent papers have noted potential risks of drawing\nerrant inferences due to misapplication of filters.\n\nLow-pass problems\n-----------------\n\nFilters in general, especially those that are acausal (zero-phase), can make\nactivity appear to occur earlier or later than it truly did. As\nmentioned in VanRullen 2011 [3]_, investigations of commonly (at the time)\nused low-pass filters created artifacts when they were applied to smulated\ndata. However, such deleterious effects were minimal in many real-world\nexamples in Rousselet 2012 [5]_.\n\nPerhaps more revealing, it was noted in Widmann & Schröger 2012 [6]_ that\nthe problematic low-pass filters from VanRullen 2011 [3]_:\n\n 1. Used a least-squares design (like :func:`scipy.signal.firls`) that\n included \"do-not-care\" transition regions, which can lead to\n uncontrolled behavior.\n 2. Had a filter length that was independent of the transition bandwidth,\n which can cause excessive ringing and signal distortion.\n\n\nHigh-pass problems\n------------------\n\nWhen it comes to high-pass filtering, using corner frequencies above 0.1 Hz\nwere found in Acunzo *et al.* 2012 [4]_ to:\n\n \"...generate a systematic bias easily leading to misinterpretations of\n neural activity.”\n\nIn a related paper, Widmann *et al.* 2015 [7]_ also came to suggest a 0.1 Hz\nhighpass. And more evidence followed in Tanner *et al.* 2015 [8]_ of such\ndistortions. Using data from language ERP studies of semantic and syntactic\nprocessing (i.e., N400 and P600), using a high-pass above 0.3 Hz caused\nsignificant effects to be introduced implausibly early when compared to the\nunfiltered data. From this, the authors suggested the optimal high-pass\nvalue for language processing to be 0.1 Hz.\n\nWe can recreate a problematic simulation from Tanner *et al.* 2015 [8]_:\n\n \"The simulated component is a single-cycle cosine wave with an amplitude\n of 5µV, onset of 500 ms poststimulus, and duration of 800 ms. The\n simulated component was embedded in 20 s of zero values to avoid\n filtering edge effects... Distortions [were] caused by 2 Hz low-pass and\n high-pass filters... No visible distortion to the original waveform\n [occurred] with 30 Hz low-pass and 0.01 Hz high-pass filters...\n Filter frequencies correspond to the half-amplitude (-6 dB) cutoff\n (12 dB/octave roll-off).\"\n\n

Note

This simulated signal contains energy not just within the\n pass-band, but also within the transition and stop-bands -- perhaps\n most easily understood because the signal has a non-zero DC value,\n but also because it is a shifted cosine that has been\n *windowed* (here multiplied by a rectangular window), which\n makes the cosine and DC frequencies spread to other frequencies\n (multiplication in time is convolution in frequency, so multiplying\n by a rectangular window in the time domain means convolving a sinc\n function with the impulses at DC and the cosine frequency in the\n frequency domain).

\n\n\n\n\n\n```python\nx = np.zeros(int(2 * sfreq))\nt = np.arange(0, len(x)) / sfreq - 0.2\nonset = np.where(t >= 0.5)[0][0]\ncos_t = np.arange(0, int(sfreq * 0.8)) / sfreq\nsig = 2.5 - 2.5 * np.cos(2 * np.pi * (1. / 0.8) * cos_t)\nx[onset:onset + len(sig)] = sig\n\niir_lp_30 = signal.iirfilter(2, 30. / sfreq, btype='lowpass')\niir_hp_p1 = signal.iirfilter(2, 0.1 / sfreq, btype='highpass')\niir_lp_2 = signal.iirfilter(2, 2. / sfreq, btype='lowpass')\niir_hp_2 = signal.iirfilter(2, 2. / sfreq, btype='highpass')\nx_lp_30 = signal.filtfilt(iir_lp_30[0], iir_lp_30[1], x, padlen=0)\nx_hp_p1 = signal.filtfilt(iir_hp_p1[0], iir_hp_p1[1], x, padlen=0)\nx_lp_2 = signal.filtfilt(iir_lp_2[0], iir_lp_2[1], x, padlen=0)\nx_hp_2 = signal.filtfilt(iir_hp_2[0], iir_hp_2[1], x, padlen=0)\n\nxlim = t[[0, -1]]\nylim = [-2, 6]\nxlabel = 'Time (sec)'\nylabel = 'Amplitude ($\\mu$V)'\ntticks = [0, 0.5, 1.3, t[-1]]\naxes = plt.subplots(2, 2)[1].ravel()\nfor ax, x_f, title in zip(axes, [x_lp_2, x_lp_30, x_hp_2, x_hp_p1],\n ['LP$_2$', 'LP$_{30}$', 'HP$_2$', 'LP$_{0.1}$']):\n ax.plot(t, x, color='0.5')\n ax.plot(t, x_f, color='k', linestyle='--')\n ax.set(ylim=ylim, xlim=xlim, xticks=tticks,\n title=title, xlabel=xlabel, ylabel=ylabel)\nmne.viz.adjust_axes(axes)\nmne.viz.tight_layout()\nplt.show()\n```\n\nSimilarly, in a P300 paradigm reported by Kappenman & Luck 2010 [12]_,\nthey found that applying a 1 Hz high-pass decreased the probaility of\nfinding a significant difference in the N100 response, likely because\nthe P300 response was smeared (and inverted) in time by the high-pass\nfilter such that it tended to cancel out the increased N100. However,\nthey nonetheless note that some high-passing can still be useful to deal\nwith drifts in the data.\n\nEven though these papers generally advise a 0.1 HZ or lower frequency for\na high-pass, it is important to keep in mind (as most authors note) that\nfiltering choices should depend on the frequency content of both the\nsignal(s) of interest and the noise to be suppressed. For example, in\nsome of the MNE-Python examples involving `ch_sample_data`,\nhigh-pass values of around 1 Hz are used when looking at auditory\nor visual N100 responses, because we analyze standard (not deviant) trials\nand thus expect that contamination by later or slower components will\nbe limited.\n\nBaseline problems (or solutions?)\n---------------------------------\n\nIn an evolving discussion, Tanner *et al.* 2015 [8]_ suggest using baseline\ncorrection to remove slow drifts in data. However, Maess *et al.* 2016 [9]_\nsuggest that baseline correction, which is a form of high-passing, does\nnot offer substantial advantages over standard high-pass filtering.\nTanner *et al.* [10]_ rebutted that baseline correction can correct for\nproblems with filtering.\n\nTo see what they mean, consider again our old simulated signal ``x`` from\nbefore:\n\n\n\n\n```python\ndef baseline_plot(x):\n all_axes = plt.subplots(3, 2)[1]\n for ri, (axes, freq) in enumerate(zip(all_axes, [0.1, 0.3, 0.5])):\n for ci, ax in enumerate(axes):\n if ci == 0:\n iir_hp = signal.iirfilter(4, freq / sfreq, btype='highpass',\n output='sos')\n x_hp = sosfiltfilt(iir_hp, x, padlen=0)\n else:\n x_hp -= x_hp[t < 0].mean()\n ax.plot(t, x, color='0.5')\n ax.plot(t, x_hp, color='k', linestyle='--')\n if ri == 0:\n ax.set(title=('No ' if ci == 0 else '') +\n 'Baseline Correction')\n ax.set(xticks=tticks, ylim=ylim, xlim=xlim, xlabel=xlabel)\n ax.set_ylabel('%0.1f Hz' % freq, rotation=0,\n horizontalalignment='right')\n mne.viz.adjust_axes(axes)\n mne.viz.tight_layout()\n plt.suptitle(title)\n plt.show()\n\nbaseline_plot(x)\n```\n\nIn respose, Maess *et al.* 2016 [11]_ note that these simulations do not\naddress cases of pre-stimulus activity that is shared across conditions, as\napplying baseline correction will effectively copy the topology outside the\nbaseline period. We can see this if we give our signal ``x`` with some\nconsistent pre-stimulus activity, which makes everything look bad.\n\n

Note

An important thing to keep in mind with these plots is that they\n are for a single simulated sensor. In multielectrode recordings\n the topology (i.e., spatial pattiern) of the pre-stimulus activity\n will leak into the post-stimulus period. This will likely create a\n spatially varying distortion of the time-domain signals, as the\n averaged pre-stimulus spatial pattern gets subtracted from the\n sensor time courses.

\n\nPutting some activity in the baseline period:\n\n\n\n\n```python\nn_pre = (t < 0).sum()\nsig_pre = 1 - np.cos(2 * np.pi * np.arange(n_pre) / (0.5 * n_pre))\nx[:n_pre] += sig_pre\nbaseline_plot(x)\n```\n\nBoth groups seem to acknowledge that the choices of filtering cutoffs, and\nperhaps even the application of baseline correction, depend on the\ncharacteristics of the data being investigated, especially when it comes to:\n\n 1. The frequency content of the underlying evoked activity relative\n to the filtering parameters.\n 2. The validity of the assumption of no consistent evoked activity\n in the baseline period.\n\nWe thus recommend carefully applying baseline correction and/or high-pass\nvalues based on the characteristics of the data to be analyzed.\n\n\nFiltering defaults\n==================\n\n\nDefaults in MNE-Python\n----------------------\n\nMost often, filtering in MNE-Python is done at the :class:`mne.io.Raw` level,\nand thus :func:`mne.io.Raw.filter` is used. This function under the hood\n(among other things) calls :func:`mne.filter.filter_data` to actually\nfilter the data, which by default applies a zero-phase FIR filter designed\nusing :func:`scipy.signal.firwin`. In Widmann *et al.* 2015 [7]_, they\nsuggest a specific set of parameters to use for high-pass filtering,\nincluding:\n\n \"... providing a transition bandwidth of 25% of the lower passband\n edge but, where possible, not lower than 2 Hz and otherwise the\n distance from the passband edge to the critical frequency.”\n\nIn practice, this means that for each high-pass value ``l_freq`` or\nlow-pass value ``h_freq`` below, you would get this corresponding\n``l_trans_bandwidth`` or ``h_trans_bandwidth``, respectively,\nif the sample rate were 100 Hz (i.e., Nyquist frequency of 50 Hz):\n\n+------------------+-------------------+-------------------+\n| l_freq or h_freq | l_trans_bandwidth | h_trans_bandwidth |\n+==================+===================+===================+\n| 0.01 | 0.01 | 2.0 |\n+------------------+-------------------+-------------------+\n| 0.1 | 0.1 | 2.0 |\n+------------------+-------------------+-------------------+\n| 1.0 | 1.0 | 2.0 |\n+------------------+-------------------+-------------------+\n| 2.0 | 2.0 | 2.0 |\n+------------------+-------------------+-------------------+\n| 4.0 | 2.0 | 2.0 |\n+------------------+-------------------+-------------------+\n| 8.0 | 2.0 | 2.0 |\n+------------------+-------------------+-------------------+\n| 10.0 | 2.5 | 2.5 |\n+------------------+-------------------+-------------------+\n| 20.0 | 5.0 | 5.0 |\n+------------------+-------------------+-------------------+\n| 40.0 | 10.0 | 10.0 |\n+------------------+-------------------+-------------------+\n| 45.0 | 11.25 | 5.0 |\n+------------------+-------------------+-------------------+\n| 48.0 | 12.0 | 2.0 |\n+------------------+-------------------+-------------------+\n\nMNE-Python has adopted this definition for its high-pass (and low-pass)\ntransition bandwidth choices when using ``l_trans_bandwidth='auto'`` and\n``h_trans_bandwidth='auto'``.\n\nTo choose the filter length automatically with ``filter_length='auto'``,\nthe reciprocal of the shortest transition bandwidth is used to ensure\ndecent attenuation at the stop frequency. Specifically, the reciprocal\n(in samples) is multiplied by 3.1, 3.3, or 5.0 for the Hann, Hamming,\nor Blackman windows, respectively as selected by the ``fir_window``\nargument for ``fir_design='firwin'``, and double these for\n``fir_design='firwin2'`` mode.\n\n

Note

For ``fir_design='firwin2'``, the multiplicative factors are\n doubled compared to what is given in Ifeachor and Jervis [2]_\n (p. 357), as :func:`scipy.signal.firwin2` has a smearing effect\n on the frequency response, which we compensate for by\n increasing the filter length. This is why\n ``fir_desgin='firwin'`` is preferred to ``fir_design='firwin2'``.

\n\nIn 0.14, we default to using a Hamming window in filter design, as it\nprovides up to 53 dB of stop-band attenuation with small pass-band ripple.\n\n

Note

In band-pass applications, often a low-pass filter can operate\n effectively with fewer samples than the high-pass filter, so\n it is advisable to apply the high-pass and low-pass separately\n when using ``fir_design='firwin2'``. For design mode\n ``fir_design='firwin'``, there is no need to separate the\n operations, as the lowpass and highpass elements are constructed\n separately to meet the transition band requirements.

\n\nFor more information on how to use the\nMNE-Python filtering functions with real data, consult the preprocessing\ntutorial on `tut_artifacts_filter`.\n\nDefaults in MNE-C\n-----------------\nMNE-C by default uses:\n\n 1. 5 Hz transition band for low-pass filters.\n 2. 3-sample transition band for high-pass filters.\n 3. Filter length of 8197 samples.\n\nThe filter is designed in the frequency domain, creating a linear-phase\nfilter such that the delay is compensated for as is done with the MNE-Python\n``phase='zero'`` filtering option.\n\nSquared-cosine ramps are used in the transition regions. Because these\nare used in place of more gradual (e.g., linear) transitions,\na given transition width will result in more temporal ringing but also more\nrapid attenuation than the same transition width in windowed FIR designs.\n\nThe default filter length will generally have excellent attenuation\nbut long ringing for the sample rates typically encountered in M-EEG data\n(e.g. 500-2000 Hz).\n\nDefaults in other software\n--------------------------\nA good but possibly outdated comparison of filtering in various software\npackages is available in [7]_. Briefly:\n\n* EEGLAB\n MNE-Python in 0.14 defaults to behavior very similar to that of EEGLAB,\n see the `EEGLAB filtering FAQ`_ for more information.\n* Fieldrip\n By default FieldTrip applies a forward-backward Butterworth IIR filter\n of order 4 (band-pass and band-stop filters) or 2 (for low-pass and\n high-pass filters). Similar filters can be achieved in MNE-Python when\n filtering with :meth:`raw.filter(..., method='iir') `\n (see also :func:`mne.filter.construct_iir_filter` for options).\n For more inforamtion, see e.g. `FieldTrip band-pass documentation`_.\n\nSummary\n=======\n\nWhen filtering, there are always tradeoffs that should be considered.\nOne important tradeoff is between time-domain characteristics (like ringing)\nand frequency-domain attenuation characteristics (like effective transition\nbandwidth). Filters with sharp frequency cutoffs can produce outputs that\nring for a long time when they operate on signals with frequency content\nin the transition band. In general, therefore, the wider a transition band\nthat can be tolerated, the better behaved the filter will be in the time\ndomain.\n\nReferences\n==========\n\n.. [1] Parks TW, Burrus CS (1987). Digital Filter Design.\n New York: Wiley-Interscience.\n.. [2] Ifeachor, E. C., & Jervis, B. W. (2002). Digital Signal Processing:\n A Practical Approach. Prentice Hall.\n.. [3] Vanrullen, R. (2011). Four common conceptual fallacies in mapping\n the time course of recognition. Perception Science, 2, 365.\n.. [4] Acunzo, D. J., MacKenzie, G., & van Rossum, M. C. W. (2012).\n Systematic biases in early ERP and ERF components as a result\n of high-pass filtering. Journal of Neuroscience Methods,\n 209(1), 212–218. http://doi.org/10.1016/j.jneumeth.2012.06.011\n.. [5] Rousselet, G. A. (2012). Does filtering preclude us from studying\n ERP time-courses? Frontiers in Psychology, 3(131)\n.. [6] Widmann, A., & Schröger, E. (2012). Filter effects and filter\n artifacts in the analysis of electrophysiological data.\n Perception Science, 233.\n.. [7] Widmann, A., Schröger, E., & Maess, B. (2015). Digital filter\n design for electrophysiological data – a practical approach.\n Journal of Neuroscience Methods, 250, 34–46.\n.. [8] Tanner, D., Morgan-Short, K., & Luck, S. J. (2015).\n How inappropriate high-pass filters can produce artifactual effects\n and incorrect conclusions in ERP studies of language and cognition.\n Psychophysiology, 52(8), 997–1009. http://doi.org/10.1111/psyp.12437\n.. [9] Maess, B., Schröger, E., & Widmann, A. (2016).\n High-pass filters and baseline correction in M/EEG analysis.\n Commentary on: “How inappropriate high-pass filters can produce\n artefacts and incorrect conclusions in ERP studies of language\n and cognition.” Journal of Neuroscience Methods, 266, 164–165.\n.. [10] Tanner, D., Norton, J. J. S., Morgan-Short, K., & Luck, S. J. (2016).\n On high-pass filter artifacts (they’re real) and baseline correction\n (it’s a good idea) in ERP/ERMF analysis.\n.. [11] Maess, B., Schröger, E., & Widmann, A. (2016).\n High-pass filters and baseline correction in M/EEG analysis-continued\n discussion. Journal of Neuroscience Methods, 266, 171–172.\n Journal of Neuroscience Methods, 266, 166–170.\n.. [12] Kappenman E. & Luck, S. (2010). The effects of impedance on data\n quality and statistical significance in ERP recordings.\n Psychophysiology, 47, 888-904.\n\n\n\n", "meta": {"hexsha": "0f9ea30c173d3c34f97efd6399667df4f3ea8616", "size": 49780, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "0.15/_downloads/plot_background_filtering.ipynb", "max_stars_repo_name": "drammock/mne-tools.github.io", "max_stars_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0.15/_downloads/plot_background_filtering.ipynb", "max_issues_repo_name": "drammock/mne-tools.github.io", "max_issues_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0.15/_downloads/plot_background_filtering.ipynb", "max_forks_repo_name": "drammock/mne-tools.github.io", "max_forks_repo_head_hexsha": "5d3a104d174255644d8d5335f58036e32695e85d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.1003861004, "max_line_length": 9801, "alphanum_fraction": 0.6294094014, "converted": true, "num_tokens": 11113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.17510818493671107}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\nplt.style.use('ggplot')\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\n\n```python\nlambda_\n```\n\n\n\n\n Elemwise{switch,no_inplace}.0\n\n\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n 100.00% [60000/60000 00:09<00:00 Sampling 4 chains, 0 divergences]\n
\n\n\n\n Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 19 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\")\nplt.tight_layout()\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint(lambda_1_samples.mean())\nprint(lambda_2_samples.mean())\n```\n\n 17.759335513669996\n 22.690660793052064\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\nprint( (lambda_1_samples / lambda_2_samples).mean() )\nprint(lambda_1_samples.mean() / lambda_2_samples.mean() )\n```\n\n 0.7838908068925983\n 0.7826715879119724\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\nlambda_1_samples[tau_samples < 45].mean()\n```\n\n\n\n\n 17.750733104781183\n\n\n\n\n```python\nlambda_1_samples.mean()\n```\n\n\n\n\n 17.759335513669996\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "cb82f53deed0467a015d6609b77ff2818b7325f7", "size": 359770, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "jeremymiller00/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "2024638d5936e85c4b40975abc2412d46bb9ac44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "jeremymiller00/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "2024638d5936e85c4b40975abc2412d46bb9ac44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "jeremymiller00/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "2024638d5936e85c4b40975abc2412d46bb9ac44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 305.9268707483, "max_line_length": 91228, "alphanum_fraction": 0.9084081497, "converted": true, "num_tokens": 11769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.17510818157473826}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n```\n\n# Lecture 4 - Darcy's Law and Conductivity #\n\n_(The contents presented in this section were re-developed principally by [Prof. B. R. Chahar](http://web.iitd.ac.in/~chahar/) and Dr. P. K. Yadav. The original contents are from Prof. Rudolf Liedl)_\n\n## Energy and hydraulic head ##\n\nIn the last section we learned that _hydrostatic pressure difference_ $p(z)$ will not allow the fully quantify water flow. In fact in addition to $p(z)$ other form of energy must also be considered. \n\nThe energy available for groundwater flow is given the name _hydraulic head_ $(h)$ or also called _piezometric head_:. It consists of three components, related to \n\n> **elevation, \npressure and \nvelocity**. \n\nThe total energy head is expressed by the equation\n\n$$\nh = z + \\frac{p}{\\rho g} + \\frac{v^2}{2g}\n$$\n\nwhere,
\n$z$ is the _elevation_ or _datum head_ [L],
\n$p$ is the _pressure_\nexerted by water column [M L$^{-1}$ T$^{-2}$],
\n$\\rho$ is the density of fluid [M L$^{-3}$],
\n$g$ is the acceleration due to gravity [LT$^{-2}$], and
\n$v$ is velocity of flow [LT$^{-1}$].\n\nNote that the $h$ has the dimension of length [L]. In groundwater flow, the velocity is so low\nthat the energy contained in velocity can be neglected when computing the total energy.\nThus, the hydraulic head (see figure below) is written as\n\n$$\nh = z + \\frac{p}{\\rho g} \n$$\n\nThe above equation says that Water flow is governed by differences in hydraulic head and not by differences in pressure head alone.\n\nIt is to be noted that $z$ depends on the orientation. In the above equation $+z$ is considered oriented upward (based on conventional sign convention). If $z-$axis is oriented downwards, we have\n\n$$\nh = \\frac{p}{\\rho g}-z \n$$\n\n\n### Hydraulic head and discharge - when there is no discharge ###\n\nConsider the figure below:\n\n\n\n\nThe pressure head: $p(z) = p_L + \\rho \\cdot g \\cdot (L-z)$
\nThe hydraulic head (piezometric head): $h(z) = \\frac{p(z)}{\\rho \\cdot g } + z = \\frac{p_L + \\rho \\cdot g \\cdot (L-z) }{\\rho \\cdot g } + z = \\frac{p_L}{\\rho \\cdot g}+ L = \\text{Const}$
\n\nIn the figure above the hydraulic head difference between two points ($z=0$ and $z=L$) are exactly equal, i.e., $\\Delta h = 0$. This refers to the system with no energy gradient and hence a _no flow_ system. \n\n### Hydraulic head and discharge - when there will be a discharge ###\n\nNow consider the figure below\n\n\n\n\nHere there is clear difference between the elevation head ($z_1$ and $z_2$), which is taken from a reference level ($z=0$ in this case. Average Sea Level (ASL), is often use for this reference). Also differing are pressure heads ($p_1$ and $p_2$). Therefore, the $h(z)$ in this case are:\n\n$$\n\\begin{align}\nh_1 &= \\frac{p_1}{\\rho \\cdot g} + z_1 \\\\\nh_2 &= \\frac{p_2}{\\rho \\cdot g} + z_2\n\\end{align}\n$$\n\nAs can be observed from the figure, in this case $h_1 1. if there\n is no hydraulic gradient (difference in hydraulic head over a distance), no flow occurs\n (this is hydrostatic conditions), \n\n> 2. if there is a hydraulic gradient, flow will occur from\n a high head towards a low head (opposite the direction of increasing gradient, hence the\nnegative sign in Darcy's law), \n\n> 3. the greater the hydraulic gradient (through the same\naquifer material), the greater the discharge, and \n\n> 4. the discharge may be different\nthrough different aquifer materials (or even through the same material, in a different\ndirection) even if the same hydraulic gradient exists.\n\nFrom the experiments Darcy observed that the _volume of water per unit time_ passing through a porous medium\n\n- is _directly proportional_ to the $A$ [L$^2$] and the head difference between inlet and outlet $(h_1 – h_2)$ [L], and \n- is inversely proportional to the _length of the medium_ $L$ [L] \n\ni.e.,\n\n$$\n\\frac{\\text{Vol}}{t}= Q \\propto A (h_1 - h_2)\\frac{1}{L}\n$$\n\nwhich in terms of specific discharge $q$, or discharge velocity or Darcy velocity $v$ [LT$^{-1}$] is\n\n$$\nq = v = \\frac{Q}{A}= - K\\frac{\\partial h}{\\partial L} = - K\\,i\n$$\n\nwhere constant of proportionality $K =$ _hydraulic conductivity_ [LT$^{-1}$]; and $i = \\partial h/ \\partial L =$\n_hydraulic gradient_ = rate of head loss per unit length of medium [ ]. The _negative sign_\nindicates that the total head is decreasing in the direction of flow because of friction or\nresistance\n\n### Example problem ###\n\n```{admonition} Darcy's Law\nCalculate the specific discharge and the flow rate passing through the surface with the given parameters.\n```\n\n\n```python\nprint(\"\\nProvided are:\\n\")\n\nK = 5e-4 # m/s, conductivity\nA = 10 # m², surface\nh_in = 10 # m, hydraulic head at the inlet\nh_out = 2 # m, hydraulic head at the outlet\nL = 5 #m, lenght of the column\n\n#intermediate calculation\nI = (h_in-h_out)/L\n\n#solution\nq = K*I\nQ = K*I*A\n\nprint(\"Conductivity = {} m/s\\nSurface = {} m²\\nHydraulic head at the inlet = {} m\\nHydraulic head at the outlet = {} m\\nLenght of the column = {} m\".format(K, A, h_in, h_out, L), \"\\n\")\nprint(\"Solution:\\nThe resulting specific discharge is {0:0.0e} m/s\".format(q), \"\\nand the flow rate is {0:0.0e} m³/s\".format(Q))\n```\n\n \n Provided are:\n \n Conductivity = 0.0005 m/s\n Surface = 10 m²\n Hydraulic head at the inlet = 10 m\n Hydraulic head at the outlet = 2 m\n Lenght of the column = 5 m \n \n Solution:\n The resulting specific discharge is 8e-04 m/s \n and the flow rate is 8e-03 m³/s\n\n\n### Darcy's law and analogous physical systems ###\n\nDarcy's law is analogous to pipe flow in which energy is dissipated over the distance to overcome frictional loss resulting\nfrom fluid viscosity. \n\nIt also forms the scientific basis of permeability used in the earth\nsciences. \n\nIt may be noted Darcy's law is analogous to Fourier's law in the field of heat conduction, Ohm's law in the field of electrical networks, or Fick's law in diffusion theory.\n\n## Hydraulic Conductivity and Intrinsic Permeability ##\n\n_Hydraulic Conductivity ($K$)_ appeared in the Darcy's law as a constant of proportionality, i.e., it is the fundamental quantity that is required to describe groundwater flow. Therefore we illustrate this further,\n\nA medium has a _unit hydraulic conductivity_ if it will transmit in _unit time_ a _unit volume of groundwater_ at the prevailing kinematic viscosity through a cross section of _unit area_ measured at _right angles_ to the direction of flow, under a _unit hydraulic gradient_. \n\nThe hydraulic conductivity of a soil or rock depends on a variety of\nphysical factors, important ones are:\n- porosity, \n- particle size and distribution, \n- shape of particles,\n- arrangement of particles.\n\nAlso, hydraulic conductivity is depends on the property of the fluid e.g., density, viscosity \n\nIn general for unconsolidated porous media,$K$ varies with _square_ of particle size; clayey materials exhibit low values of $K$, whereas\nsands and gravels display high values\n\nTypical values for hydraulic conductivity (see figure XX for more comprehensive listing):\n\n| Media Type | hydraulic conductivity (m/s) |\n| ----------- | ---: |\n| Gravel | $10^{-2} – 10^{-1}$ |\n| coarse sand | $\\approx 10^{-3}$ |\n| medium sand | $10 ^{-4} – 10^{-3}$ |\n| fine sand | $10^{-5} – 10^{-4}$ |\n| Silt | $10^{-9} – 10^{-6} $ |\n| Clay | $< 10^{-9} $ |\n\n### Obtaining Hydraulic Conductivities ###\n\nThe hydraulic conductivity depends on properties of the fluid (density, viscosity,\ntemperature) and on properties of the porous medium (effective porosity, grain size\ndistribution). It can be obtained by calculation from formulas, laboratory methods, or\nfield tests\n\nThe laboratory method can be indirect method or direct method. For example,\ndetermination of the hydraulic conductivity based on the evaluation of sieve analysis\ndata is the indirect laboratory method. On the other hand, the direct method of\ndetermination of the hydraulic conductivity (e.g. permeameter) is based on some version of Darcy‘s experiment. Advantages of laboratory methods include controlled\nconditions, small sample size (easy handling), lower costs, larger number of\nexperiments, etc. While, the disadvantages of laboratory methods are disturbed\nsamples, additional pathways at column walls, small sample size (randomly high or low\nK), flushing of fine material, etc.\n\n#### Hydraulic Conductivities estimations from Sieve analysis ####\n\nSieve analysis data can be evaluated to estimate hydraulic conductivity of\nunconsolidated media. There are several _empirical methods_. The simplest one dates back to Hazen (1892):\n\n$$\nK = 0.0116 \\cdot d_{10}^2\n$$\n\n\nwhere, $d_{10}$ = grain diameter (mm) corresponding to $10\n\\%$ of cumulative mass fraction. It can be generalized by including temperature ($\\theta$ in $^\\circ$C). Thus the Hazen formula becomes\n\n\n$$\nK = 0.0116 \\cdot d_{10}^2 \\cdot (0.7 + 0.03\\cdot\\theta)\n$$\n\nHazen's formula is only valid for the indicated units, i.e., conversion of the _unit_ may be required before using the formula.\n\n### Example problem ###\n\n```{admonition} Hydraulic Conductivity from sieve data\nAn Aquifer with fine to medium sand was investigated with an sieve analysis. At a temperature of $20°C$ a $d_{10}$ of $0.13$ mm was measured. Determine the hydraulic conductivity (using Hazen's formula) and how it changes when the temperature rises by $5°C$.\n```\n\n\n\n```python\nprint(\"Let us find the hydraulic conductivities.\\n\\nProvided are:\")\n\nd10 = 0.13 # mm, grain diameter corresponding to 10% of cumulative mass fraction\nT1 = 10 # °C, Temperature\ndeltaT = 5 # °C, temperature change\n\n#intermediate calculation\nT2 = T1 + deltaT\n\n#solution based on Hazen's formula\nK1 = 0.0116 * d10**2 * (0.7 + 0.03*T1)\nK2 = 0.0116 * d10**2 * (0.7 + 0.03*T2)\n\nprint(\"grain diameter corresponding to 10% of cumulative mass fraction = {} mm\\nTemperature = {} °C\\ntemperature change = {} K\".format(d10, T1, deltaT),\"\\n\")\nprint(\"The resulting hydraulic Conductivity at 20°C is {0:0.2e} m/s\".format(K1),\n \"\\nand the resulting hydraulic conductivity at 25°C is {0:0.2e} m/s\".format(K2))\n```\n\n Let us find the hydraulic conductivities.\n \n Provided are:\n grain diameter corresponding to 10% of cumulative mass fraction = 0.13 mm\n Temperature = 10 °C\n temperature change = 5 K \n \n The resulting hydraulic Conductivity at 20°C is 1.96e-04 m/s \n and the resulting hydraulic conductivity at 25°C is 2.25e-04 m/s\n\n\n#### Hydraulic Conductivities estimations from Darcy's Law ####\n\n**Permeameter** is an instrument used to determine hydraulic conductivity of soil samples\nin the laboratory as _direct method_. The design of permeameters is based on Darcy‘s\nexperiment. \n\n\n\n\nThere are mainly two types of permeameters\n1. Constant-head permeameter, and \n2. Falling-head permeameter. \n\n\nIn **constant-head permeameters** as\nshown in Figure the hydraulic heads at inflow and outflow of the Darcy column are\nconstant in time. As a consequence, the discharge is not changing with time. \n\n\n\nThe\nhydraulic conductivity can be obtained by observing discharge and heads and then\nsubstituting in the below formula that is rearranged form of Darcy’s law from:\n\n$$\nK = \\frac{QL}{A(h_{in}- h_{out}}\n$$\n\nwhere $Q$ =discharge[L$^3$T$^{-1}$];
\n$L$ = length of sample [L];
$A$ = cross-sectional area of sample [L$^2$];
\n$h_{in}$ = hydraulic head at column inlet [L];
\n$h_{out}$ = hydraulic head at column outlet [L];
\n$\\Delta h$ = $h_{in} - h_{out}$\n\n$h_{out}$ can be set equal to zero as only head differences are important.\n\n### Example problem ###\n\n```{admonition} Hydraulic Conductivity from Constant head-permeameter\nA constant-head permeameter has a length of 15 cm and a cross-sectional area of $25$ cm$^2$. With a head of 5 cm, a total Volume of 100 mL of water is collected in 12 min. Determine the hydraulic conductivity.\n```\n\n\n```python\nprint(\"Let us find the hydraulic conductivity with a constant-head permeameter.\\n\\nProvided are:\")\n\nL = 15 # Length of the permeameter [cm]\nA = 25 # cross-sectional area [cm^2]\nh = 5 # hydraulic head [cm]\nV = 100 # Volume of collected water [mL = cm^3]\nt = 12 # time [min]\n\n#solution\nK1 = (V * L)/(A * t * h)\nK2 = K1/(60*100)\n\nprint(\"Length of the permeameter = {} cm \\ncross-sectional area = {} cm\\u00b2\\nhydraulic head = {} cm \\nVolume = {} mL \\ntime = {} min\".format(L,A,h,V,t),\"\\n\")\nprint(\"The resulting hydraulic Conductivity is {0:2.0e} cm/min\".format(K1),\n \"\\nand which is {:02.0e} m/s\".format(K2))\n```\n\n Let us find the hydraulic conductivity with a constant-head permeameter.\n \n Provided are:\n Length of the permeameter = 15 cm \n cross-sectional area = 25 cm²\n hydraulic head = 5 cm \n Volume = 100 mL \n time = 12 min \n \n The resulting hydraulic Conductivity is 1e+00 cm/min \n and which is 2e-04 m/s\n\n\nIn falling-head permeameter as shown in Figure the hydraulic head at the outflow of\nthe Darcy column is not changing, but the hydraulic head at the inflow is decreasing\nwith time. \n\n\n\nAs a result, the discharge also decreases with time. Rewriting Darcy's law for a small time interval\n\n$$\nK \\frac{\\pi d_c^2}{4}\\big(h_{in} - h_{out}\\big)\\frac{1}{L}\\text{d}t = \\frac{\\pi d_t^2}{4}\\text{d}h \n$$\n\n$K$ can be obtained from the above equation by separating the variables and then integrating. The resulting expression for $K$ will be\n\n$$\nK = \\frac{d_t^2 L}{d_c^2}\\ln \\Bigg(\\frac{h_{in}(0) - h_{out}}{h_{in}(t)-h_{out}}\\Bigg)\n$$\n\nwhere,
\n$L$ = length of sample [L];
\n$d_c$ = diameter of sample cylinder [L];
\n$d_t$ = diameter of piezometer tube [L];
\n$h_{in}(0)$ = initial hydraulic head at column inlet [L];
\n$h_{in}(t)$ = final hydraulic head at column inlet [L];
\n$h_{out}$ = hydraulic head at column outlet [L];
\n$h_0 = h_{in}(0) - h_{out}$;
\n$h = h_{in}(t) - h_{out}$\n\nand $h_{out}$ can be set equal to zero as only head differences are\nimportant. The hydraulic conductivity can be obtained from the above equation using observed time and corresponding heads. Larger experimental time periods are needed for the falling-head permeameter, in particular if hydraulic conductivity is low. On the other hand, no measurement of discharge or water volume is required.\n\n**Field methods** of determination of the hydraulic conductivity include tracer tests, auger hole tests, pumping tests of wells, etc. Field experiments are much more complicated and expensive than laboratory tests. Resulting hydraulic conductivities represent averages over an aquifer volume, which is covered by the experiment. The size of this\nvolume depends on subsurface properties and on the experimental method used.\n\n### Intrinsic Permeability ###\n\nA convenient alternative is to write Darcy's equation in a form of **intrinsic permeability**\nwhere the properties of the medium and the fluid are represented explicitly\n\n$$\nv = \\frac{-k \\cdot \\rho\\cdot g}{\\mu}\\frac{\\partial h}{\\partial L}\n$$\n\nwhere, $k$ is the intrinsic permeability [L$^2$], and $\\eta$ is the dynamic viscosity of fluid [ML$^{-1}$T$^{-1}$] e.g., (Pa-S). The relation between _hydraulic conductivity_ _intrinsic permeability_, therefore, is\n\n$$\nK = k\\cdot \\frac{ \\rho \\cdot g}{\\eta}\n$$\n\nIn terms of Kinematic viscosity [L$^2$T$^{-1}$}], $\\eta = \\rho \\cdot \\nu$, the above relation becomes\n\n$$\nK = k\\cdot \\frac{ g}{\\nu}\n$$\n\nBoth density and viscosity are temperature dependent quantites. Their values in field conditions $\\approx 10 ^\\circ$C and in the laboratory conditions $\\approx 20 ^\\circ$C are:\n\n\n| | 10°C | 20°C |\n|----------------------------|-------------|--------------|\n| density (kg/m$^3$) | 999.7 | 999.7 |\n| kinematic viscosity (m$^2$/s) | 1.3101·10$^{-6}$ | 1.0105·100$^{-6}$ |\n| ynamic viscosity (Pa$\\cdot$s) | 1.3097·10$^{-3}$ | 1.3097·100$^{-3}$ |\n|||\n\n\nThe _intrinsic permeability_ can be written in terms of specific weight or weight density [ML$^{-2}$T$^{-2}$] (or in metric unit- N/m$^3$), $\\gamma = \\rho\\cdot g$ as\n\n$$\nk = \\frac{\\eta}{\\gamma}K\n$$\n\n### Example problem ###\n\n```{admonition} Instrinsic Permeability\nThe intrinsic permeability of a consolidated rock is $2,7 \\cdot 10^{-11} cm^2$. What is the hydraulic conductivity for water at 20°C\n```\n\n\n```python\nprint(\"Let us find the hydraulic conductivity.\")\n\nk = 2.7e-15 # intrinsic permeability [m^2]\nrho = 999.7 # density at 20°C [kg/m^3]\neta = 0.013097 # dynamic viscosity at 20°C [Pa*s]\ng = 9.81 # [m/s^2]\n\n# solution\nK = k * ((rho * g)/eta)\n\nprint(\"intrinsic permeability = {} m\\u00b2\\ndensity = {} kg/m\\u00b3\\ndynamic viscosity = {} Pa*s\".format(k, rho, eta),\"\\n\")\nprint(\"The resulting hydraulic conductivity at 20°C is {0:0.1e} m/s\".format(K))\n```\n\n Let us find the hydraulic conductivity.\n intrinsic permeability = 2.7e-15 m²\n density = 999.7 kg/m³\n dynamic viscosity = 0.013097 Pa*s \n \n The resulting hydraulic conductivity at 20°C is 2.0e-09 m/s\n\n\n### Properties of Intrinsic Permeability ###\n\n- The value of intrinsic permeability of a porous medium\nequals 1 m$^2$ if a fluid with dynamic viscosity of 1 Pa$\\cdot$s can pass through the porous\nmedium at a Darcy velocity of 1 m/s under a hydrostatic pressure gradient of 1 Pa/m\n(horizontal flow).\n\n- The intrinsic permeability is _independent_ of the fluid moving through the medium and depends only upon the medium properties. Intrinsic\npermeability of unconsolidated porous media is roughly proportional to the square of\nthe pore diameter.\n\n- The intrinsic permeability is used primarily when the density or the viscosity of the\nfluid varies with position.\n\n- The dimension of $k$ is [L$^2$], but when expressed in m$^2$ is so small that square\nmicrometers ($\\mu$ m)$^2 = 10^{-12}$ m$^2$ is used. In the petroleum industry it is expressed in **Darcy**\n(symbol: D) with conversion factor to SI units is: 1 D $= 0.987\\cdot 10^{-12}$ m$^2$. \n\n- Intrinsic permeability for a weakly , well and\nhighly permeable aquifers vary in the range 10$^{-4}$ to 10$^{-1}$ D, 10$^{-1}$ to 10$^2$ D, and $> 10^2$ D\nrespectively\n\n- Typical value of conductivity and intrinsic permeability is provided in the fig (from Todd and Mays, 2004) below.\n\n\n\n\n## Darcy velocity and Interstitial velocity ##\n\nDarcy velocity $v$ is the _apparent velocity_ or _fictitious velocity_ or _Darcy flux_ (discharge per\nunit area). This value of velocity, often referred to as the _apparent velocity_, is not the\nvelocity which the water traveling through the pores is experiencing. The velocity $v$ is\nreferred to as the Darcy velocity because it assumes that flow occurs through the entire cross section of the material without regard to solids and pores. Actually water can flow\nthough pores only and the pore spaces vary continuously with location within the\nmedium. Therefore the actual velocity is nonuniform, involving endless accelerations,\ndeceleration, and changes in direction. To define the _actual flow velocity_ or **interstitial\nvelocity**, one must consider the microstructure of the rock material. \n\nFor naturally occurring geologic materials, the microstructure cannot be specified three-\ndimensionally; hence, actual velocities can only be quantified statistically.\n\n\n\nActually, the flow is limited to the pores (white spaces in Figure) only so that the\n_average interstitial velocity_ or _actual velocity_ or _seepage velocity_ $(v_s)$ through pore space\ncan be determined by applying continuity equation\n\n$$\nQ = A_s\\cdot v_s = Av\n$$ \n\nLeading to \n\n$$\nv_s = v\\frac{A}{A_s} = \\frac{v}{\\nu_e}\n$$\n\nwhere $A$ = total area of soil specimen, and $A_s$ = area of pores only (see Figure). The velocity\nis divided by effective porosity ($\\nu_e$) to account for the fact that only a fraction of the total aquifer\nvolume is available for flow. This indicates that for a sand with a porosity of 33% the $v_s\n= 3 v$. Thus the average interstitial velocity or seepage velocity or linear velocity through\npore space is never smaller than Darcy velocity. Sometimes, the average flow velocity of\nwater in the pore space is termed _linear velocity_. \n\n### Example problem ###\n\n```{admonition} Interstitial velocity\nFrom the data below obtain the average interstitial velocity in the Darcy's column. \n```\n\n\n```python\nprint(\"Provided data are:\\n\")\n\nQ = 0.005 # Flow rate [m^3/s]\nA = 1000 # total area of soil specimen [m^2]\nne = 0.4 # effective porosity [-] = \n\n\n#solution\nvs = Q / (ne * A)*3600*24 \n\nprint(\"Flow rate = {} m\\u00b3/s\\ntotal area = {} m\\u00b2\\neffective porosity = {} \".format(Q, A, ne),\"\\n\")\nprint(\"The resulting average interstitial velocity is {} m/d\".format(vs))\n```\n\n Provided data are:\n \n Flow rate = 0.005 m³/s\n total area = 1000 m²\n effective porosity = 0.4 \n \n The resulting average interstitial velocity is 1.08 m/d\n\n\n### Typical values of linear velocities ### \n\nTypical values for average interstitial velocities or linear velocities in unconsolidated aquifers are 0.5 m/d to 1 m/d and 30\nm/d to 300 m/d in sand and gravel respectively. \n\nLinear velocities in fractured or\nkarstified aquifers can be rather high along fractures or conduits e.g. 200 m/d to 1.2\nkm/d along fractures and 3 km/d to 14 km/d in karst conduits. \n\nOn the contrary, the\nlinear velocities are very low in the rock matrix of consolidated aquifers (1 cm/d or\neven less).\n\n### Travel time and Pore volume ### \n\nThe average linear/pore velocity is the velocity a conservative tracer/dye experiences if\ncarried by water through the aquifer. \n\nThe travel time of water through a column of\nlength $L$ is given by \n\n$$\nt = L/v_s\n$$\n\nIt is to be noted that the linear/seepage velocity $v_s$ has to be used in travel time computation, not the Darcy velocity. The term _residence time_ is can also be found to be used for referring to _travel time_ .\n\nYet another important term that is often found in standard texts is _pore volume_. The _pore volume is the travel time through a column. It can be understood as the _time_ needed to replace the water in the column. In this sense, the pore volume is not a _volume_ but a _time_ (i.e., 1 PV corresponds to the ratio $L/v_s$ ). The pore volume (PV) is frequently used for _normalisation_ purposes in order to better compare column\nexperiments conducted under different flow velocities. This is mostly done for studying the transport behaviour of chemicals dissolved in water and their arrivals at the column outlets\n\n### Example problem ###\n\n```{admonition} Travel time and pore volume\nIn a tracer test, the breaktrought was measured after 100 h at a distance of 200 m. Determine the linear velocity and the pore volume. what is the darcy velocity, if there is an effective porosity of 0.25.\n```\n\n\n```python\nprint(\"Provided are:\\n\")\n\nt = 100 # travel time of water [h]\nL = 200 # Distance from injection to measurement [m]\nne = 0.25 # effective porosity [-] \n\n\n#solution\nvs = L / t\nPV = L / vs\nv = vs * ne\n\nprint(\"travel time of water = {} s\\nLength = {} m\\u00b2\\neffective porosity = {} \".format(t, L, ne),\"\\n\")\nprint(\"The linear velocity is {} m/h \\nthe pore volume is {} s, and \\nthe darcy velocity is {} m/h\".format(vs, PV, v))\n```\n\n Provided are:\n \n travel time of water = 100 s\n Length = 200 m²\n effective porosity = 0.25 \n \n The linear velocity is 2.0 m/h \n the pore volume is 100.0 s, and \n the darcy velocity is 0.5 m/h\n\n", "meta": {"hexsha": "596ae3b625a457ec28c494afdb8120c8949f4e2c", "size": 35918, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "_build/html/_sources/contents/flow/lecture_04/14_darcy_law_K.ipynb", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/html/_sources/contents/flow/lecture_04/14_darcy_law_K.ipynb", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/html/_sources/contents/flow/lecture_04/14_darcy_law_K.ipynb", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9977728285, "max_line_length": 436, "alphanum_fraction": 0.5911242274, "converted": true, "num_tokens": 7148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.17432256766697285}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (2 chains in 2 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n Sampling 2 chains, 0 divergences: 100%|██████████| 30000/30000 [00:15<00:00, 1890.08draws/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\n## My addition\npm.traceplot(trace);\n```\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nprint(lambda_1_samples.mean(),\nlambda_2_samples.mean())\n```\n\n 17.764572308895286 22.724895224113308\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nix = tau_samples < 45\nprint(lambda_1_samples[ix].mean())\n```\n\n 17.765949108965923\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "1e92ba3eab19bc88c806ed4657d65e2db773d94e", "size": 393622, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "Amirgav/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers-AG", "max_stars_repo_head_hexsha": "2ff80f127a0f361a111b9dd65a003f937d1cb67c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "Amirgav/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers-AG", "max_issues_repo_head_hexsha": "2ff80f127a0f361a111b9dd65a003f937d1cb67c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "Amirgav/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers-AG", "max_forks_repo_head_hexsha": "2ff80f127a0f361a111b9dd65a003f937d1cb67c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 355.896925859, "max_line_length": 98244, "alphanum_fraction": 0.9166586217, "converted": true, "num_tokens": 11277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.37022538564692037, "lm_q1q2_score": 0.17355819053036256}} {"text": "```python\n__author__ = 'Guillermo Damke , Francisco Förster , Alice Jacques '\n__version__ = '20210119' # yyyymmdd;\n__datasets__ = ['Iris flower dataset']\n__keywords__ = ['Introduction to Machine Learning', 'Supervised Machine Learning', 'La Serena School for Data Science']\n```\n\n# Introduction to Supervised Machine Learning - Basic Concepts\n\n*In original form by Francisco Forster, Centro de Modelamiento Matemático (CMM), Universidad de Chile / Instituto Milenio de Astrofísica (MAS). Adaptated for NOIRLab Astro Data Lab by Guillermo Damke and Alice Jacques.*\n\n#### This notebook is part of the curriculum of the 2019 La Serena School for Data Science.\n\n## Table of Contents\n\nThis notebook presents an introduction to topics in Machine Learning, in the following sections:\n\n* [General concepts in Machine Learning](#1---General-concepts-in-Machine-Learning)\n\n* [Supervised (and Unsupervised) Machine Learning methods](#2---Supervised-and-Unsupervised-Machine-Learning)\n\n* [Metrics to evaluate model performance](#3---Metrics-to-evaluate-model-performance)\n\n* [Diagnostics](#4---Diagnostics)\n\n* [Visual representations of results](#5---Visual-representations-of-results)\n\n# Summary\nThis notebook introduces several concepts and definitions that are common in Machine Learning. Practical examples of these concepts are presented in a separate notebook.\n\n# 1 - General concepts in Machine Learning\n\n## 1.1 - Overfitting, underfitting, and the bias-variance tradeoff\n\n\n### Overfitting and Underfitting\n\nTwo important concepts in machine learning are **overfitting** and **underfitting**.\n\nIf a model represents our data too accurately (**overfitting**), it may not effectively generalize unobserved data.\n\nIf a model represents our data too generally (**underfitting**), it may underrepresent the features of the data.\n\nA popular solution to reduce overfitting consists of adding structure to the model through **regularization**. This favors simpler models through training inspired by **[Occam's razor](https://en.wikipedia.org/wiki/Occam%27s_razor)**.\n\n### Bias\n\n* Quantifies the precision of the model across the training sets.\n\n### Variance \n\n* Quantifies how sensitive the model is to small changes in the training set.\n\n### Bias-variance tradeoff\n\nThe plot below shows the **bias-variance tradeoff**, which is a common problem in Supervised Machine Learning algorithms. It is related to model selection. A model with high complexity describes the training data well (low training error), but may not effectively generalize when applied to new data (high validation error, i.e., high error in predicting when presented to new data). A simpler model is not prone to overfitting the noise in the data, but it may underrepresent the features of the data (**underfitting**).\n\n\n\n## 1.2 - Complexity, accuracy, robustness\n\nIn general, we want precise and robust models. \n\n**Simpler models tend to be less accurate, but more robust.**\n\n**More complex models tend to be more accurate, but less robust.**\n\nThis tension is usually expressed as the **bias-variance tradeoff** which is central to machine learning.\n\n## 1.3 - Model selection\n\nNo one model performs uniformly better than another. One model may perform well in one data set and poorly in another.\n\n## 1.4 - Classification vs. regression\n\nThe figure below represents two usual tasks performed with Machine Learning.\n\n* **Classification**: refers to predicting to what class or category an object belongs to, given some input data about that object. In this case, the output is a category, class, or label (i.e., a discrete variable).\n\n* **Regression**: refers to predicting an output real value, given some input data. In this case, the output is a continuous variable.\n\n\n\n# 2 - Supervised and Unsupervised Machine Learning\n\nIn this section, we will introduce two different learning algorithms, which are considered either as Supervised or Unsupervised Machine Learning.\n\n## 2.1 - Predictive or *Supervised Learning*:\n\nLearn a mapping from inputs ${\\bf x}$ to outputs $y$, given a **labeled** set of input-output pairs $D=\\lbrace{({\\bf x_i}, y_i)\\rbrace}_{i=1}^N$.\n\n$D$ is called the **training set**.\n \nEach training input ${\\bf x_i}$ is a vector of dimension $M$, with numbers called **features**, **attributes** or **covariates**. They are usually stored in a $N \\times M$ **design matrix** ${\\bf X}$.\n\n\nAn important consideration, as mentioned above:\n \n* When $y$ is **categorical** the problem is known as **[classification](#1.4---Classification-vs.-regression)**.\n \n* When $y$ is **real-valued** the problem is known as **[regression](#1.4---Classification-vs.-regression)**.\n\n### Example of a labeled training set: the \"Iris flower dataset\".\n\nThe **Iris flower dataset** is commonly utilized in Machine Learning tests and examples for problems in categorical classification. Because of this, the dataset is included in several Python libraries, including the Seaborn library which we will use below.\n\nThe **Iris flower dataset** includes four real-valued variables (length and width of petals and sepals) for 50 samples of each three species of Iris (versicolor, virginica, and setosa):\n\n\n\n\n\n#### What does this dataset look like?\n\nLet's read the dataset and explore it with the Seaborn library:\n\n\n```python\nimport seaborn as sns\n%matplotlib inline\nsns.set(style=\"ticks\")\n\ndfIris = sns.load_dataset(\"iris\")\nprint(\"Design matrix shape (entries, attributes):\", dfIris.shape)\nprint(\"Design matrix columns:\", dfIris.columns)\n```\n\n Design matrix shape (entries, attributes): (150, 5)\n Design matrix columns: Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width',\n 'species'],\n dtype='object')\n\n\nIt can be seen that the dataset contains 150 entries with 5 atributes (columns).\n\nWe can view the first five entries with the `head` function:\n\n\n```python\ndfIris.head()\n# Notice that the real-valued variables are in centimeters.\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2setosa
14.93.01.40.2setosa
24.73.21.30.2setosa
34.63.11.50.2setosa
45.03.61.40.2setosa
\n
\n\n\n\nThe function `info` prints \"a concise summary\" of a DataFrame:\n\n\n```python\ndfIris.info()\n```\n\n \n RangeIndex: 150 entries, 0 to 149\n Data columns (total 5 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 sepal_length 150 non-null float64\n 1 sepal_width 150 non-null float64\n 2 petal_length 150 non-null float64\n 3 petal_width 150 non-null float64\n 4 species 150 non-null object \n dtypes: float64(4), object(1)\n memory usage: 6.0+ KB\n\n\nWhile the function `describe` is used to \"generate descriptive statistics\" of a DataFrame:\n\n\n```python\ndfIris.describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
sepal_lengthsepal_widthpetal_lengthpetal_width
count150.000000150.000000150.000000150.000000
mean5.8433333.0573333.7580001.199333
std0.8280660.4358661.7652980.762238
min4.3000002.0000001.0000000.100000
25%5.1000002.8000001.6000000.300000
50%5.8000003.0000004.3500001.300000
75%6.4000003.3000005.1000001.800000
max7.9000004.4000006.9000002.500000
\n
\n\n\n\nFor a quick visual exploration of the dataset, we can use the `pairplot` function of the Seaborn library.\nWe will pass the `hue=\"species\"` argument, so that the three species (labels) in the dataset are represented by different colors.\n\n\n```python\nsns.pairplot(dfIris, hue=\"species\");\n```\n\nWe will train a model to predict the Iris classes in Section 4 of this notebook.\n\nIn addition, some applications of Supervised Machine Learning algorithms is presented in the [\"04_Intro_Machine_Learning_practical\"](https://github.com/astro-datalab/notebooks-latest/blob/master/06_EPO/LaSerenaSchoolForDataScience/2019/04_Intro_Machine_Learning_practical/Intro_Machine_Learning_practical.ipynb) entry of this series.\n\n## 2.2 - Descriptive or *Unsupervised Learning*\n\nOnly inputs are given: $D=\\lbrace{{\\bf x_i}\\rbrace}_{i=1}^N$\n \nThe goal here is to find interesting patterns, which is sometimes called **knowledge discovery**.\n \nThe problem is not always well defined. It may not be clear what kind of pattern to look for, and there may not be an obvious metric to use (unlike supervised learning).\n\nSome applications of Unsupervised Machine Learning algorithms are presented in the [\"04_Intro_Machine_Learning_practical\"](https://github.com/astro-datalab/notebooks-latest/blob/master/06_EPO/LaSerenaSchoolForDataScience/2019/04_Intro_Machine_Learning_practical/Intro_Machine_Learning_practical.ipynb) entry of this series.\n\n## 2.3 - Reinforcement Learning\n\nMixed between Supervised and Unsupervised. Only occasional reward or punishement signals are given (e.g. baby learning to walk).\n\n# 3 - Metrics to evaluate model performance\n\n## 3.1 - Classification loss\n\nLearning algorithms, and optimization algorithms, need to quantify if the predicted value from a model agrees with the true value. The learning process involves a minimization process in which a **loss function** penalizes the wrong outcomes.\n\n### Loss function and classification risk:\n\nThe most common loss function used for supervised classification is the **zero-one** loss function:\n\n$L(y, \\hat y) = \\delta(y \\ne \\hat y)$\n\nwhere $\\hat y$ is the best guess value of $y$. The function is 1 if the guess is different than the true value; and 0 if the guess is the same as the true value.\n\nThe **classification risk** of a model is the expectation value of the loss function:\n\n$E[L(y, \\hat y)] = p(y \\ne \\hat y)$\n\nFor the zero-one loss function the risk is equal to the **misclassification rate** or **error rate**.\n\n## 3.2 - Types of errors\n\nAccuracy and classification risk are not necessarily good diagnostics of the quality of a model. \n\nIt is better to distinguish between two types of errors (assuming 1 is the label we are evaluating):\n\n1. Assigning the label 1 to an object whose true class is 0 (a **false positive**)\n\n2. Assigning the label 0 to an object whose true class is 1 (a **false negative**)\n\n\n(Image from http://opendatastat.org/mnemonics/)\n\nAdditionally, correct cases can be separated as:\n\n- Assigning the label 1 to an object whose true class is 1 is a **true positive**.\n- Assigning the label 0 to an object whose true class is 0 is a **true negative**.\n\n# 4 - Diagnostics\n\nApplying the concepts introduced above, it is possible to define several diagnostics or metrics in Machine Learning to evaluate the goodness of a given algorithm applied to a dataset.\n\n\n\n## 4.1 - Accuracy, contamination, recall, and precision\n\nThese four metrics are defined as:\n\n$$\\rm accuracy = \\frac{\\#\\ correct\\ labels}{total}$$\n\nNote that this is one minus the classification risk (defined in [Section 3.1](#3.1---Classification-loss)).\n\n$$\\rm contamination\\ =\\ \\frac{false~ positives}{true~ positives~ +~ false~ positives}$$\n\n$$\\rm recall\\ =\\ \\frac{true~ positives}{true~ positives~ +~ false~ negatives}$$\n\n\n$$\\rm precision\\ = 1 - contamination = \\ \\frac{true~ positives}{true~ positives~ +~ false~ positives}$$\n\n\nNote: Sometimes, **recall** is also called **completeness**.\n\n## 4.2 - Macro vs. micro averages\n\nThe definitions given above can be applied directly in a two-class problem. However, when evaluating the different diagnostics in a **multiclass problem** (i.e., non-binary classification) one has to choose to do macro or micro averages.\n\n**Macro averaging**\n\nCompute diagnostics for every class by taking the average of the class diagnostics.\n \n\n**Micro averaging**\n\nCompute diagnostics for the total errors without making a distinction between classes (True Positive, False Positive, False Negative).\n \n\nFor example, consider the following 3-class problem:\n\n| Label | TP | FP | FN | Precision | Recall |\n| - | - | - | - | - | - |\n| c1 | 3 | 2 | 7 | 0.6 | 0.3 |\n| c2 | 1 | 7 | 9 | 0.12 | 0.1 |\n| c3 | 2 | 5 | 6 | 0.29 | 0.25 |\n| Total | 6 | 14 | 22 | | | \n| Macro averaged | | | | 0.34 | 0.22 |\n| Micro averaged | | | | 0.3 | 0.21 |\n\n\nIn this case, the value for macro precision is:\n\n\\begin{align}\n\\rm Macro_{precision} &= \\rm average \\big(precision(c1), precision(c2), precision(c3)\\big) \\\\\n& = \\frac{1}{3} \\times \\biggl( \\frac{3}{3 + 2} + \\frac{1}{1 + 7} + \\frac{2}{2 + 5} \\biggr) = 0.34\n\\end{align}\n\nAnd the value for micro precision is:\n\n\\begin{align}\n\\rm Micro_{precision} &= \\rm precision(total) \\\\\n& = \\frac{6}{6 + 14} = 0.3\n\\end{align}\n\n## 4.3 True positive rate (TPR) and false positive rate (FPR)\n\nThese scores are defined as:\n\n$$\\rm TPR\\ =\\ recall\\ =\\ \\frac{true~ positives}{true~ positives~ +~ false~ negatives}$$\n\n\n$$\\rm FPR\\ = \\ \\frac{false~ positives}{false~ positives~ +~ true~ negatives}$$\n\n\n\n\n\n(image by user Walber in Wikipedia. CC BY-SA 4.0)\n\n## 4.4 - Problems with accuracy \n\nAs introduced above, accuracy is defined as:\n\n$$\\rm accuracy\\ =\\ \\frac{\\#~ Total~ of~ correct~ predictions}{\\#~ Total~ number~ of~ predictions}$$\n\n\nTo show why accuracy is not a very useful statistic let's consider the following example.\n\n**Example:** A model to predict whether a person is from a given country (with a population of 37 million people):\n\n*Simple (and wrong) model*: assuming that the world population is 7.5 billion people, predict that a person is from that country with a probability 37/7500.\n\n$$ \\rm{correct\\ predictions} = (7,500,000,000 - 37,000,000) \\times \\bigg(1 - \\frac{37}{7500}\\bigg) + 37,000,000 \\times \\frac{37}{7500} = 7,426,365,067$$\n\nThen, accuracy becomes:\n\n$$\\rm accuracy = \\frac{7,426,365,067}{7,500,000,000} = 0.99$$\n\n\nOur classifier is 99% accurate, but it is clearly too simplistic!\n\n### Precision and recall are better statistics\n\nLet's try precision and recall instead. First, calculate the TP, FP and FN:\n\nTrue positives (TP): $37,000,000 \\times \\frac{37}{7500} = 182,533$\n\nFalse positives (FP): $(7,500,000,000 - 37,000,000) \\times \\frac{37}{7500} = 36,817,467$\n\nFalse negatives (FN): $37,000,000 \\times \\big(1 - \\frac{37}{7500}\\big) = 36,817,467$\n\nThen, we evaluate **recall** and **precision**:\n\n$$\\rm recall = \\frac{TP}{TP + FN} = \\frac{182,533}{182,533 + 36,817,467} = 0.005$$\n\n$$\\rm precision = \\frac{TP}{TP + FP} = \\frac{182,533}{182,533 + 36,817,467} = 0.005$$\n\nOur classifier has only 0.5% recall and precision!\n\n## 4.5 - F1 score\n\nA simple statistic which takes into account both recall and precision is the **$\\rm \\bf F_1$ score**, which is twice their harmonic mean. It is defined as:\n\n\n$$\\rm F_1 = 2 \\times \\ \\frac{1}{\\frac{1}{precision}\\ +\\ \\frac{1}{recall}} = 2 \\times \\ \\frac{precision\\ \\times\\ recall}{precision\\ +\\ recall}$$\n\n## 4.6 - F$_\\beta$ score\n\nTo give more or less weight to recall vs precision, the $F_\\beta$ score is used:\n\n$$\\rm F_\\beta = (1 + \\beta^2) \\times \\frac{precision\\ \\times\\ recall}{\\beta^2\\ precision\\ +\\ recall}$$\n\n$F_\\beta$ was derived so that it measures the effectiveness of retrieval with respect to a user who attaches **$\\beta$ times as much importance to recall as precision**.\n\n# 5 - Visual representations of results\n\n## 5.1 - Confusion matrix\n\nAlso known as **error matrix**, it is a way to summarize results in classification problems.\n\nThe elements of the matrix correspond to the number (or fraction) of instances of an actual class which were classified as another class.\n\nA perfect classifier has the *identity* as its normalized confusion matrix.\n\nFor example, a classifier for the Iris flower dataset could yield the following results:\n\n\n\n

\n

\n\n\n\n## 5.2 - ROC curve\n\nThe **Receiver Operating Characteristic (ROC)** curve is a visualization of the tradeoff between the recall and precision of a classifier as the discrimination threshold is varied.\n\nIt plots the **True Positive Rate (TPR)** vs the **False Positive Rate (FPR)** at various thresholds.\n\n\n\n\nThe demo below shows the ROC curve for a classifier as the discrimination between TP and FP varies.\n\n\n```python\nfrom IPython.display import Image\nImage(url=\"Images/roc_curve.gif\")\n```\n\n\n\n\n\n\n\n\nThis demonstration is described [here](https://arogozhnikov.github.io/2015/10/05/roc-curve.html).\n\n## 5.3 - Area under the curve (AUC) and Gini coefficient (G1)\n\nThe AUC is equal to the probability that the classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one.\n\n * A larger AUC indicates a better classification model\n * A perfect classifier has AUC = 1\n * A random classifier has AUC = 0.5 (note that the **no-discrimination line** is the identity) \n * AUC is related to the G1, which is twice the area between the ROC and the no-discrimination line: \n \n $\\Large \\rm G_1 = 2 \\times AUC - 1$ \n \n\nThe ROC AUC statistic is normally used to do model comparison.\n\n## 5.4 - DET curve\n\nAn alternative to the ROC curve is the **Detection Error Tradeoff (DET)** curve.\n\nThe DET curve plots the **FNR (missed detections) vs. the FPR (false alarms)** on a non-linearly transformed axis in order to emphasize regions of low FPR and low FNR.\n\n\n\n# In Conclusion\n\nThis has been a brief introduction of concepts in Machine Learning with focus on classification (Supervised Learning). Special emphasis has been put into introducing a variety of concepts and metrics that should be especially useful for the evaluation of Machine Learning algorithms in classification problems. Finally, we introduced some common visual representations of results, which are useful to summarize model performance.\n", "meta": {"hexsha": "0e527fb0d272c63cab1dddb9bfd2404d6ea25f03", "size": 263437, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "06_EPO/LaSerenaSchoolForDataScience/2019/05_Supervised_ML_I/05_Supervised_ML_1_intro.ipynb", "max_stars_repo_name": "noaodatalab/notebooks_default", "max_stars_repo_head_hexsha": "3001f40c0de05445e65e205fdb3806f85e91dbfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-19T17:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T17:38:59.000Z", "max_issues_repo_path": "06_EPO/LaSerenaSchoolForDataScience/2019/05_Supervised_ML_I/05_Supervised_ML_1_intro.ipynb", "max_issues_repo_name": "noaodatalab/notebooks_default", "max_issues_repo_head_hexsha": "3001f40c0de05445e65e205fdb3806f85e91dbfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2022-02-21T20:09:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T15:41:15.000Z", "max_forks_repo_path": "06_EPO/LaSerenaSchoolForDataScience/2019/05_Supervised_ML_I/05_Supervised_ML_1_intro.ipynb", "max_forks_repo_name": "noaodatalab/notebooks_default", "max_forks_repo_head_hexsha": "3001f40c0de05445e65e205fdb3806f85e91dbfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-21T18:13:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T18:13:37.000Z", "avg_line_length": 266.9067882472, "max_line_length": 230820, "alphanum_fraction": 0.9123471646, "converted": true, "num_tokens": 5425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.1705995354580129}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n\n```python\n\n```\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1, 2]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n\n
\n\n\n\n Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 38 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint(lambda_1_samples.mean())\nprint(lambda_2_samples.mean())\n```\n\n 17.743607156764146\n 22.7093739712513\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n(lambda_1_samples/lambda_2_samples).mean()\n```\n\n\n\n\n 0.7825252356102967\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\nlambda_1_samples[tau_samples<45].mean()\n```\n\n\n\n\n 17.74444306523926\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d35f8ee8b670467fb5ac305cfd9231dac737f20e", "size": 904244, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "squiroga6/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "032b545f79e43c725a22b335737e5816924e0a10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "squiroga6/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "032b545f79e43c725a22b335737e5816924e0a10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "squiroga6/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "032b545f79e43c725a22b335737e5816924e0a10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 863.6523400191, "max_line_length": 200441, "alphanum_fraction": 0.7228679427, "converted": true, "num_tokens": 11655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.17015656453199288}} {"text": "# U of U IS Deep Learning Study Group - Notes #1\n#### Author: Brian Sheng\n#### Art Credit: Stephen Vickers\n\n\n```python\nfrom IPython.display import YouTubeVideo\nimport tensorflow as tf\nimport sympy as sp\nfrom sympy import Matrix\nsp.init_printing(\"latex\")\n```\n\nDeep Learning has been getting a lot of attention lately. The question is why... and does it live up to the hype? Well, you may know that our ability to train and run bigger neural networks due to our increase in compute power since days past is a big part of it. \n\n**Note**: This notebook explains things from the ground up, and you may be familiar with some of these concepts already. The intention of the simplistic explanations is not to insult or condescend, but to couch things in as simple terms as possible, but no simpler. As a result, plain English is often used to introduce heady concepts in layman's terms. Feel free to skim through concepts you're already solidly familiar with, but please be open to alternative perspectives that may be enlightening.\n\nIf you want the abridged version of everything, I'd suggest reading the headings, reading around the *bolded statements*, looking at the visuals, reading the formulas, and reading things that are indented in HTML quotes style like this:\n> This is HTML quote style\n\nAt the same time it's important to know that I do not hold a Ph.D in Computer Science, nor am I currently an industy leader in AI, so what is written here is not dogma. I am simply a determined amateur who is doing his best to fill his knowledge gaps and do some good science. Many of the makers of these resources *are* experts in their field however, and I would advise that you go through them:\n\n## Additional Learning Resources\n**The de facto Deep Learning textbook from Goodfellow et al (free!)**:\nhttp://deeplearningbook.org/\n\n**An easier online Deep Learning textbook (free!)**:\nhttp://neuralnetworksanddeeplearning.com/\n\n**Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems (~$32)**:\nhttps://www.amazon.com/gp/product/1491962291\n\n**Hands-On Machine Learning Github (free code and Jupyter Notebooks!)**:\nhttps://github.com/ageron/handson-ml\n\n**How Deep Neural Networks Work**: \nhttps://www.youtube.com/watch?v=ILsA4nyG7I0\n\n**How Convolutional Neural Networks work**:\nhttps://www.youtube.com/watch?v=FmpDIaiMIeA\n\n**CS231N Winter 2016 Lectures from Andrej Karpathy at Stanford**: https://www.youtube.com/playlist?list=PLkt2uSq6rBVctENoVBg1TpCC7OQi31AlC\n\n**CS231N Winter 2016 Lecture Notes**:\nhttp://cs231n.github.io/\n\n**ConvNetJS (neural nets in your browser with JavaScript!)**:\nhttp://cs.stanford.edu/people/karpathy/convnetjs/\n\n**Hvass Labs TensorFlow Jupyter Notebook Tutorials with YouTube Videos**:\nhttps://github.com/Hvass-Labs/TensorFlow-Tutorials\n\n**Stanford's Deep Natural Language Processing Video Lectures**:\nhttps://www.youtube.com/playlist?list=PL3FW7Lu3i5Jsnh1rnUwq_TcylNr7EkRe6\n\n**Berkeley's Deep Reinforcement Learning Course (even more learning resources recommended there!)**:\nhttp://rll.berkeley.edu/deeprlcourse/\n\n**YouTube playlist for developing visual intution for linear algebra**:\nhttps://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab\n\n**YouTube playlist for developing visual intution for calculus**:\nhttps://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr\n\n**Backpropagation Example Python Code:**\nhttps://iamtrask.github.io/2017/03/21/synthetic-gradients/\nhttps://iamtrask.github.io/2015/07/12/basic-python-network/\n\nWith that out of the way, let's proceed.\n\n## Introduction and Learning Goals\n\n### Introduction\n#### Why can we go deeper? Why are neural nets suddenly working better?\n\nIn a nutshell:\n- Backpropagation has been around for a while\n- Neural nets are nothing new\n\n#### Why are neural nets hot right now?\n- More compute power\n- More data\n- Use of different neural net types\n\t- Convolutional Neural Net architectures exist that have ~10^2 layers (not all “layers” have neurons)\n\t- Vanilla Fully-Connected Nets usually don’t see much benefit from >3 layers depending on the application\n\t- Recurrent Net depth is <10^1 layers, usually more like 4 or 5. (due to nature of computation and exacerbated vanishing/exploding gradient problems)\n- Use of different units\n\t- ReLU for ConvNets, some RNNs, Fully Connected Nets\n\t- LSTMs and GRUs for RNNs\n\t- These units train better and/or address vanishing/exploding gradients\n- Better initialization\n\t- RBMs initially pre-trained and then stacked to create Deep Belief Networks\n\t- Turns out better initialization is all you really need (don’t need RBMs)\n\t*Citation: Andrej Karpathy’s CS231N lectures 4, 5, 6.\n\t- Small random values, normally or uniformly distributed depending on the network type, with std dev depending on number of inputs and outputs for a given neuron.\n*RBM = Restricted Boltzmann Machine\n- Better regularization (L2, Dropout, DropConnect, Early Stopping, Ensemble, Bagging)\n\nAn *in-a-nutshell* statement on the current state of AI from DARPA can be found here:\n\n\n```python\nYouTubeVideo('-O01G3tSYpU')\n```\n\n\n\n\n\n\n\n\n\n\nAn *in-a-nutshell* explanation of deep neural nets can be found here:\n\n\n```python\nYouTubeVideo('ILsA4nyG7I0')\n```\n\n\n\n\n\n\n\n\n\n\n### Learning Goals for this Group\n- Develop a better intuition of how neural nets function from the ground up.\n- Develop an intuition for tuning deep neural net models in practice.\n- Develop skills for use in practice, research, etc.\n\n#### How to accomplish this?\n- Presentations from week to week.\n- Hopefully lecture notes and code to play with on Git service of our choosing.\n\n## Effect of Depth & General Intuitions\n\n### Networks Have Layers\nYou likely know that the *Deep* in *Deep Learning* is due to the large number of layers in some networks that have performed quite well on modern AI tasks in recent years. For the sake of review and reference, in a nutshell, each layer is either an input, an output, or the result of an element-wise activation function that has been applied to the result of a matrix multiply followed by an addition operation with a *bias vector*. These output vectors are the *layers*, and the weights in the matrices are the connections between them. Layers that aren't the output or input layer are called *hidden* layers.\n\nImage credit: https://en.wikipedia.org/wiki/Artificial_neural_network\n\n### Learning of Meaningful Features\nThe meaningful *features* that a learning system is meant to grab onto are traditionally designed by human domain experts, resulting in very complicated operations on the input data, and complex functions being fed into each *layer* of the network. The general idea with neural nets is to instead allow a learning system to define its own features as it is trained on the data. Each layer can be seen as a **layer of abstraction**, with the network creating more complicated features from simpler features. This can be seen as building up more complicated concepts from simpler ones. This can be seen in convolutional neural nets, with the learned *filters* getting more complicated as we go from input layer to output layer. \n\n\nImage credit: (Goodfellow et al, 2016)\n\n### Repeated Kernel Trick (Warp & Slice)\nIn the example of a 2d data space, and classifying inputs as one of two things, you can think of a neural network as repeatedly stretching, warping, and squashing the space of data to allow for the drawing of a flat plane to separate the data. It's like taking a sheet of rubber and warping it into some weird shape before freezing it and slicing through it with a knife. Each layer results in another warping of the sheet, and the final layer corresponds to the last warping, followed by a slice with a knife. The number of *neurons* type of *activation function* for a given layer will determine the warping type. You can see that warpings generally **get more complex with number of neurons**, and that **adding layers nests these warpings together**, feeding them into one another like Russian nesting dolls.\n\n\nImage credit: (Karpathy et al, 2016)\n\nThis can be seen in this interactive demo from Andrej Karpathy of such a neural net that runs in your browser: http://cs.stanford.edu/people/karpathy/convnetjs/demo/classify2d.html\n\nExplanation of demo:\n\n\n```python\nYouTubeVideo('i94OvYb6noo?t=1h10m45s')\n```\n\n\n\n\n\n\n\n\n\n\n### Neural Nets as Universal Function Approximators\nNeural Nets can be shown to approximate just about any arbitrary function given non-linear activation functions and enough units. Essentially, if you give neural nets enough capacity to learn and represent complex outputs, then you'll tend towards being able to output whatever arbitrary thing as long as it's a function on the input. See these chapters for much more detailed and rigorous explanations:\nhttp://neuralnetworksanddeeplearning.com/chap4.html\nhttp://www.deeplearningbook.org/contents/mlp.html\n\n\n### Problems with Depth\nThe problem is that when you increase depth on a network you also make it considerably harder to train. This is due to the way that the network learns for the network being tied to depth in a way that parts of the network further removed from the output will be less affected by the learning mechanism, which operates on a function of the output error of the network. Modern methods find ways around this with the aforementioned tweaks in our Introduction section to give *Deep Learning*, where we can effectively train very deep neural nets given some caveats (mainly convolutional neural nets it seems).\n\n**I strongly recommend now playing with the aforementioned ConvNetJS two-class neural net classifier with visualization. It will give you intuition about the concepts and ideas discussed in this section**\n\n## Neural Nets as Composed Functions & Computational Graphs\nNeural nets can be viewed as nested, or \"composed\", functions. They are functions of functions of functions of inputs. Looking at the top level of abstraction, they can be unhelpfully viewed as literal boxes of *magic*. This view of (unwitting) data being pulled in to a box of magic to produce (suave) output is a bit to simplistic and doesn't really help us, so let's break it down a bit deeper. \n\n\n\n### Computational Graphs\nTaking the example of a neural net with one hidden layer, if we break down the magic box into the machines that it's made out of, we have a representation that looks like this:\n\n\n\nIf it looks like bedlam and chaos, that's because those little workers are computing something important in an inefficient way. We'll come back to that later.\n\nYou can see that there's a matrix multiply with bias and activation function to go from input to hidden layer, then another set of matrix multiply with bias and activation function machines to go from hidden layer to output. (On a related note, this YouTube playlist gives an excellent series of intuitive explanations of linear algebra concepts, enjoyable even for the seasoned pro: https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab)\n\nIf you examine the first machine in the line, you'll see that matrix multiply and bias machines look like this:\n\n\nLet's clean things up a bit and go back to a more helpful version of *magic* boxes. In the process, we'll also break the operations down into their useful components, or smaller magic boxes. Here's the same matrix multiply and bias operation in terms of magic boxes:\n\n\n\nYou can see that it's pretty much exactly what it says on the tin. It's the multiplication of some input **x** with some matrix **W1** using *****, followed by the addition of a bias **b1** using **+** to the result. If we keep the activation function interchangeable and leave it as a magic box labelled **f**, we can then represent our neural network as a series of magic boxes chained together like this. When you expand it all out, it looks something like this:\n\n\n\nThis series of chained boxes that takes an input and spits out some outputs is a **computational graph**. In the case of neural nets, it has the property where you can always find a beginning input that depends only on itself, and also the property where you can't get caught in an infinite loop. This is called **acyclic dependency**, and will be a helpful property later. \n\n### Optimal Substructure & Gradients of Composed Functions with the Chain Rule\nYou may notice that each box in this graph may depend on other boxes feeding into their input. They are therefore *functions* of these other input boxes. These input boxes are also functions, so we have functions of functions. The end result of the graph is a nested or composed function. If you were to find the change of the output of this graph with respect to the change in some part further back in the graph, this would be the **derivative** of the output with respect to that part. Since these are vector or matrix shape parts, we get vector or matrix-shaped derivatives. These vector or matrix-shaped derivatives would be called our **gradients**.\n\n\n\nIt is important to note another property of this computational graph. The gradients of the output with respect to each box happen to depend on each other. You can make gradients from other gradients. Solutions from smaller solution pieces. This is called **optimal substructure**, and it is also a helpful property for us. The fact that the whole computational graph is a bunch of functions composed together means that we compute these gradients using the **chain rule**. Borrowing from Wikipedia's chain rule explanation, in short, the derivative of an outer function\n\n$$F(x)=f(g(x))$$\n\nwith respect to an inner function's input (the single quote indicates a derivative of F(x)) **F'(x)** is computed by:\n\n$$F'(x) = f'(g(x))g'(x)$$\n\nThis means that the derivative of the outside function with respect to the inside function's input is equal to the derivative of the outside function with respect to the inside function multiplied by the derivative of inside function with respect to the inside function's input.\n\nAlternatively, if you set $z=F(x)=f(g(x))=f(y)$ and $y=g(x)$, then you can rewrite this as:\n\n$$\\frac{dz}{dx}=\\frac{dz}{dy}\\frac{dy}{dx}=F'(x) = f'(g(x))g'(x)$$\n\nWhere $\\frac{dz}{dx}$ is the derivative of z with respect to x, $\\frac{dz}{dy}$ is the derivative of z with respect to y, and $\\frac{dy}{dx}$ is the derivative of y with respect to x. You can see that the $dy$ numerator and denominator appear to cancel, leaving $\\frac{dz}{dx}$ as the result.\n\nThe notation of $\\frac{dz}{dx}$ for the derivative reflects the fact that it's *like* the ratio between a tiny change in $z$ due to a tiny change in its input $x$ by $dx$ \n\n$$dz\\approx z(x+dx)-z(x)$$\n\nand that tiny change dx. When $dx$ is *infinitely small* (take the \"limit\" as is goes to zero) then the derivative is *literally* that ratio and we get:\n\n$$\\frac{dz}{dx}=\\lim_{dx \\to 0}\\frac{z(x+dx)-z(x)}{dx}$$\n\nIf the function has multiple inputs, then you're taking a *partial derivative* when you take the derivative w.r.t that input while holding everything else constant. The notation for that looks like:\n\n\n\n$$\\frac{\\partial z}{\\partial u}=\\frac{\\partial z}{\\partial x}\\frac{\\partial x}{\\partial u},z=f(x,y),x=g(u,v)$$\n\nYou can see that we multiply gradients together with other gradients to get our final gradients of the output with respect to each box output or input(e.g. **W1** is a box input, $\\boldsymbol{f}(\\boldsymbol{W_1 x}+\\boldsymbol{b_1})$ is the output of the first **f** box) . Chain rule is described here: https://en.wikipedia.org/wiki/Chain_rule.\n\nIf this is your first exposure to calculus and you've never heard of the chain rule before, then this YouTube playlist may also prove useful (The Essence of Calculus): https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr\n\nThe video from that playlist related to the Chain Rule is here:\n\n\n```python\nYouTubeVideo('YG15m2VwSjA')\n```\n\n\n\n\n\n\n\n\n\n\nHow the gradients pass through split inputs on addition and multiplication is covered here (related to the Backpropagation section):\nhttp://cs231n.github.io/optimization-2/\n\nNow, why do we want the gradient? Well, since that output *J* indicates how bad our neural net is doing on the training data, we want to make that as small as possible. Some parts that go into *J* can't be helped. Some of these bits can be helped, and would be called the **parameters** of our model that are free to change. These would be **W1** **b1** **W2** **b2**, and free to vary during the training process. We use the gradient of that *J* with respect to these parameters to change these parameters during training. This will move them in a direction to minimize that loss, *J* on the training data. This process is Gradient Descent, and is covered in the next section.\n\n## Gradient Descent & Backpropagation\n\n### Gradient Descent\nSo, you have a neural net that has an associated loss function. To get it to learn, we minimize this loss function with respect to the training data, fitting it to the data. The general way to do this is with any number of modified versions of *Gradient Descent*.\n\nLooking in the motivation section of Wikipedia page for gradient:\nhttps://en.wikipedia.org/wiki/Gradient\n> *Consider a surface whose height above sea level at point (x, y) is H(x, y). The gradient of H at a point is a vector pointing in the direction of the **steepest slope or grade at that point.** The steepness of the slope at that point is given by the magnitude of the gradient vector.*\n\n\nImage credit: https://en.wikipedia.org/wiki/Gradient_descent\n\nSubtracting the gradient from its associated vector or function is like heading away from the direction of *steepest ascent*. You are heading in the direction of *steepest descent*, hence **Gradient Descent**. Intuitively, if you're heading towards a direction of steepest descent, eventually you will reach a flat spot or region locally. You will arrive at a *local minimum* of the matrix function. See the Wikipedia page for more info:\n\nhttps://en.wikipedia.org/wiki/Gradient_descent\n\nThe general formula of interest is:\n$$u_{t+1}=u_{t}-\\alpha \\nabla f(u_t)$$\n\nWhere $u$ is a parameter of the function $f(u)$, $u_{t+1}$ is the new value of $u$, $u_t$ is the old value of $u$, $\\alpha$ is a scalar real number value, and $\\nabla f(u_t)$ is the gradient of $f(u_t)$. The important thing to keep in mind here is that $u$ can be any arbitrary shaped matrix, vector, or tensor, but the shapes of $u_{t+1}$, $u_{t}$, and $\\nabla f(u_t)$ must be the same for gradient descent to work. That seems a bit obvious, but this will be important later.\n\n### Computing Gradients\n\nThe naive way to compute the gradients we need for our parameters is to repeatedly apply the chain rule over and over again. This however, results in use repeating ourselves much more than necessary. Let's look at the example where we need to compute the gradient of *J* w.r.t. (with respect to) **W1** **b1** **W2** **b2** as in our computational graph for a one hidden layer neural net with activation functions on the hidden and output layers.\n\n\n\nAs for taking the derivative (differentiation) w.r.t a vector, the following video should outline the idea behind it:\n\n\n```python\nYouTubeVideo('iWxY7VdcSH8')\n```\n\n\n\n\n\n\n\n\n\n\nDifferentiation of a vector $\\boldsymbol{f}$ w.r.t to another vector $\\boldsymbol{x}$ gives the Jacobian matrix of $\\boldsymbol{f}$ w.r.t $\\boldsymbol{x}$, $\\frac{\\partial \\boldsymbol{f}}{\\partial \\boldsymbol{x}}$, which is of the form:\n\n$$\n\\begin{bmatrix}\n\\frac{\\partial f_1}{\\partial x_1} & \\dots & \\frac{\\partial f_1}{\\partial x_m} \\\\\n\\vdots & \\ddots & \\vdots \\\\\n\\frac{\\partial f_n}{\\partial x_1} & \\dots & \\frac{\\partial f_n}{\\partial x_m}\n\\end{bmatrix}\n$$\n\nThis gives us this horrid mess of formulas from the Chain Rule, which we'll stick here for the sake of reference:\n\n$\\boldsymbol{x}=$ Inputs\n\n$\\boldsymbol{z_1}=\\boldsymbol{W_1 x}+\\boldsymbol{b_1}=$ Input values to \"hidden\" activation function\n\n$\\boldsymbol{a}=\\boldsymbol{f}(\\boldsymbol{z_1})=$ Hidden Activations\n\n$\\boldsymbol{z_2}=\\boldsymbol{W_2 a}+\\boldsymbol{b_2}=$ Inputs to \"output\" activation function\n\n$\\boldsymbol{y ̂}=\\boldsymbol{f}(\\boldsymbol{z_2})=$Output Activations\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_2}}\n=\n\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{b_2} }\n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\odot\n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n\\boldsymbol{\\delta_2}\n$$\n\nWhere $\\odot$ is **element-wise multiplication**, a.k.a the Hadamard Product: https://en.wikipedia.org/wiki/Hadamard_product_(matrices), and $\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} }$ is the derivative of the output activation function w.r.t its inputs.\n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{b_2}}=\\frac{\\partial}{\\partial \\boldsymbol{b_2}}\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)=\\boldsymbol{1}\n$$\n\nWhere \n$\\boldsymbol{1}$ is the ones vector. (i.e. $\\boldsymbol{1}=\\begin{bmatrix}\n 1 \\\\\n ... \\\\\n 1\n \\end{bmatrix}$\n for some arbitrary length) \n In the case of \n $\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{b_2}}$\n , the length of the vector is the same as the length of \n $\\boldsymbol{b_2}$.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_2}}\n=\n\\boldsymbol{\\delta_2}\n\\odot\n\\boldsymbol{1}=\\boldsymbol{\\delta_2}\n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}\n=\n\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2} }\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{w_2}}\n\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)\n=\n\\boldsymbol{a}^T$$\n\n$$\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}\n=\n\\boldsymbol{\\delta_2}\n\\otimes\n\\boldsymbol{a}\n=\n\\boldsymbol{\\delta_2}\\boldsymbol{a}^T\n$$\n\nWhere $\\otimes$ is the **outer (or tensor) product**: https://en.wikipedia.org/wiki/Outer_product\n\n$$\\frac{\\partial J}{\\partial \\boldsymbol{b_1}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}} \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1} }\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n$$\n\nWhere $\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} }$ is the derivative of the hidden activation function w.r.t. its inputs. \n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{a}}\n\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)\n=\n\\boldsymbol{w_2}^T\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{b_1}}\n\\left( \\boldsymbol{w_1 x}+\\boldsymbol{b_1}\\right)\n=\n\\boldsymbol{1}\n$$\n\n$$\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} }\n=\n\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle\n=\n\\boldsymbol{w_2} \\cdot \\boldsymbol{\\delta_2} \n=\n\\boldsymbol{w_2}^T\\boldsymbol{\\delta_2}\n$$\n\nWhere $\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle$ is the **inner product** (in this case, called the **dot product**) of the matrices $\\boldsymbol{w_2}$ and $\\boldsymbol{\\delta_2}$ :\nhttps://en.wikipedia.org/wiki/Inner_product_space\nhttps://en.wikipedia.org/wiki/Dot_product\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_1}}\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n=\n\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle\n\\odot \\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} }\n\\odot \\boldsymbol{1}\n=\n\\boldsymbol{\\delta_1} \\odot \\boldsymbol{1}\n=\n\\boldsymbol{\\delta_1} \n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{ w_1 }}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}} \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{w_1}}\n=\n\\boldsymbol{\\delta_1}\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{ w_1 }}\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{ w_1 }}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{ w_1 }}\n\\left( \\boldsymbol{w_1 x}+\\boldsymbol{b_1}\\right)\n=\n\\boldsymbol{x}^T\n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{w_1}}\n=\n\\boldsymbol{\\delta_1}\n\\otimes\n\\boldsymbol{x}\n=\n\\boldsymbol{\\delta_1}\n\\boldsymbol{x}^T\n$$\n\nSo, that was most likely a bit overwhelming. We'll go through that in a more intuitive manner in a bit, but now you have the formulas for reference later. \n\nYou can see there's a lot of repeated work in these formulas. Terms like \n$\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}} \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} }$\ncontain other terms, such as \n$\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } $.\n\nIf you were to simply calculate everything straight-ahead without reusing work, you'd be repeating a lot of derivative calculcations unnecessarily. If we go back to the factory analogy with the workers computing the gradients, you can see it goes right back to bedlam and chaos very quickly if we use the straight-ahead method.\n\nThis is where backpropagation comes in.\n\n### The Essence of Backpropagation\nBackpropagation takes advantage of two properties of the computational graphs of neural nets to do these calculations without having to recalculate anything. The properties of **acyclic dependency** and **optimal substructure** allow for fancy thing called **Dynamic Programming** to be applied to the problem of calculating gradients. In this case, Dynamic Programming just means that we make sure to start with a calculation that is self contained and doesn't depend on stuff we don't have (the beginnning/end of the graph), then move on to using that result to calculate things that depend on it, then continue onto things that depend on that next result and so on.\n\nWe start from the *beginning* to calculate that *initial thing* and work our way through building *things* that depend on that *initial thing*, then building *new things* that depend on those *things* and so on, all the while making sure to compute everything without repeating work unnecessarily.\nWith this in mind, we can see that:\n* The *things* we're building up are the gradients of the loss function output $J$ w.r.t each part.\n* Our beginning is at the loss function output $J$.\n* We can determine an order to do the calculations in by performing a **topological sort** on the compuational graph, or just keep track of what we've computed and check if we've computed something already before doing it, which is called **memoization**.\n* Once we've computed everything that we need to, we're done.\n\nYou can see the **acyclic dependency** and **optimal substructure** of the problem in our diagram of the interdependencies of the gradient from earlier:\n\n\n\n### Backpropagation from the Top-Down: Keeping Track of Shape\nLet's walk through the example with one hidden layer we had before, and go through the formulas in more depth. One thing that tends to trip people up is keeping track of the shapes of all the vectors and matrices.\n\nThe shape of the matrices/tensors during feedforward and backprop is important to keep in mind. Things get confusing when you mix it up. It's easy to get lost in the abstract world of formulas, resulting in getting all the parts that you need for computation without knowing how to put them together to make actual gradients. So, let's go through the process *backwards* and figure out how things are suppose to fit together, and what shape everything is before slowly revealing more detail about the parts we're assembling.\n\nRemember that formula for gradient descent?\n$$u_{t+1}=u_{t}-\\alpha \\nabla f(u_t)$$\n\nWell, we need to make sure that $u_{t}$ and $\\nabla f(u_t)$ are the same shape. If we look at some operations available for us to play with, we can see some preserve shape while others do not. Let's set up some weight matrices and bias vectors to look at while we go through this example. We'll use the SymPy Python library for its array data structures and operations, and print things out as we go along. We'll use a neural network that looks like the following figure:\n\n\n\nThis network has 3 input units, 4 hidden units, and 2 output units. If we use column vectors in our matrix multiplications, we'll have two weight matrices and two bias vectors for our input-to-hidden and hidden-to-output mappings. The input-to-hidden weight matrix and bias vector will be $\\boldsymbol{w_1}$ and $\\boldsymbol{b_1}$, and the hidden-to-output weight matrix and bias vector will be $\\boldsymbol{w_2}$ and $\\boldsymbol{b_2}$, as before.\n\n#### Non-Square Matrices as Transformations Between Dimensions (Shape Changing)\nA matrix can be viewed as encoding a linear function, and non-square matrices can be views as encoding linear functions between dimensions. If you're operating on column vectors, then the number of rows encodes the output dimensionality, and the number of columns is input dimensionality. So a matrix like the following one encodes a transformation from 4 dimensional vectors to 2 dimensional vectors.\n\n$$\\begin{bmatrix}\n 1 & 1 & 1 & 1\\\\\n 1 & 1 & 1 & 1\n \\end{bmatrix}$$\n\nA matrix multiply between a 4D vector and such a matrix will produce a 2D vector.\n\n$$\\begin{bmatrix}\n 1 & 1 & 1 & 1\\\\\n 2 & 2 & 2 & 2\n \\end{bmatrix}\\begin{bmatrix}\n 2 \\\\\n 2 \\\\\n 2 \\\\\n 2\n \\end{bmatrix}=\\begin{bmatrix}\n 8 \\\\\n 16\n \\end{bmatrix}$$\n\nYou can see that a non-square matrix multiplication of this kind can be seen as a magic box that takes in an input of one shape, and makes an input of another shape.\n\n\n\nThe video below gives a more in-depth understanding of how this is the case:\n\n\n```python\nYouTubeVideo('v8VSDg_WQlA')\n```\n\n\n\n\n\n\n\n\n\n\nSo, looking at that neural net figure again, we'll have a 3D input vector, which must map to a 4D hidden vector, which must in turn map to a 2D output vector. This means we'll need a (4,3) (or $4x3$ depending on your notation) shaped matrix for the input-to-hidden map and a (2,4) shaped matrix for the hidden-to-output map. Our $b_1$ and $b_2$ bias vectors get added in at the hidden an output layers, so they must be 4D and 2D themselves.\n\nLet's make the variables for these in SymPy and go through a bunch of symbolic computations with matrices so we can get an idea of how things interact.\n\n\n```python\ndef names_2_sympy_str_list(shape, array_name):\n \"\"\"Takes a shape tuple or list, and a string for the array name\n and makes a string formatted for making a sympy string of the same\n shape that is filled with symbols of the form:\n \n {array_name}_{indices of element in matrix}\n \n Returns:\n A list of strings of the form:\n [{array_name}({rows+1}\\,(1:{array.shape[1]})),\n {array_name}({rows+1}\\,(1:{array.shape[1]})), ... ]\n \n To be fed to the sympy.symbols(...) function to create symbols\n to be fed into a symbolic matrix.\n \"\"\"\n return ['{{{0}}}_{{({1}\\,(1:{2}))}}'\n .format(array_name, rows+1, shape[1]+1) \n for rows in range(shape[0])]\n\n\ndef string_list_to_sympy_matrix(sympy_string_list): \n \"\"\"Takes a list of lists of strings for feeding into sympy.symbols(...)\n and feeds the list to sympy.symbols(...) and sympy.Matrix(...) via\n string_list_to_matrix(...) to create a list of sympy matrices or a\n single sympy matrix depending on the arguments.\n \"\"\"\n return Matrix(sp.symbols(sympy_string_list))\n\n\ndef sympy_matrices_from_names(shapes, names):\n \"\"\"Takes a list of matrix shape tuples, and a list of names\n for the arrays (strings) and creates symbolic matrices\n of the form:\n |name_11 name_12|\n |name_21 name_22|\n |name_31 name_32|\n \n Returns:\n A list of matrices to be unpacked, or a single matrix\n if only one array is given.\n \"\"\"\n assert(isinstance(shapes,(tuple,list))\n and isinstance(names,(str,tuple,list)))\n \n if isinstance(names,str):\n string_list_input = names_2_sympy_str_list(arrays, names)\n return string_list_to_sympy_matrix(string_list_input)\n else:\n assert(len(shapes)==len(names))\n string_lists = [names_2_sympy_str_list(arr, nam)\n for arr, nam in zip(shapes, names)]\n matrices = [string_list_to_sympy_matrix(string_list)\n for string_list in string_lists]\n return matrices if len(matrices)>1 else matrices[0]\n\n\nparameter_and_variable_shapes = ((2,1), (2,1), (2,4), (4,1), (4,1), (4,3), (3,1), (4,1),)\nparameter_and_variable_names = ('b_2', '\\delta_2', 'w_2','b_1', '\\delta_1', 'w_1','x','a')\n\n(b_2, delta_2, w_2, b_1, delta_1, w_1,\n input_x, hidden_activations) = sympy_matrices_from_names(parameter_and_variable_shapes,\n parameter_and_variable_names)\ndisplay(b_2, w_2, b_1, w_1, input_x, hidden_activations)\n```\n\nWe'll have activation functions applied to the results of the matrix multiply and biasing on the hidden and output layers, but let's focus on the shape first.\n\nIn order to increment the $\\boldsymbol{b_2}$ vector, we'll need one of the same size to subtract from it. Same goes for $\\boldsymbol{w_2}$, $\\boldsymbol{b_1}$, and $\\boldsymbol{w_1}$. We want something that looks like this:\n\n$$\\boldsymbol{b_2}-\\Delta \\boldsymbol{b_2}\n=\n\\begin{bmatrix}\n b_{2(1,1)} \\\\ \n b_{2(2,1)}\n \\end{bmatrix}\n -\n \\begin{bmatrix}\n \\Delta b_{2(1,1)} \\\\\n \\Delta b_{2(2,1)}\n \\end{bmatrix}\n $$\n\nIf we refer to some of the formulas from applying chain rule earlier, we see this needs to depend on the derivative of the loss $J$ w.r.t $\\boldsymbol{y ̂}$, $\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }}$, which will be a vector in the shape of $\\boldsymbol{y ̂}$ due to the way that derivatives w.r.t a vector work. Activation functions are element-wise, and thus shape-preserving, so their derivatives also preserve shape. The output activation function derivative w.r.t its input, $\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} }$, will therefore be the same shape as $\\boldsymbol{b_2}$ too.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_2}}\n=\n\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{b_2} }\n$$\n\nThe activation function and its derivative are like magic boxes that operate element-wise on inputs, leaving shapes unchanged.\n\n\n\nAs for that last piece, from differentiation rules, we can clearly see:\n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{b_2}}=\\frac{\\partial}{\\partial \\boldsymbol{b_2}}\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)=\\boldsymbol{1}\n$$\n\nWhere $\\boldsymbol{1}$ is the same shape of $\\boldsymbol{b_2}$. So, we see that we essentially use just the first two pieces.\n\nSo, it's quite easy to put a vector together shaped like $\\boldsymbol{b_2}$ from these pieces. Everything is already the same shape as $\\boldsymbol{b_2}$, so we just multiply $\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }}$ and $ \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} }$ together element-wise. The magic box analogy for that would be something like this:\n\n\n\nIf we multiply everything together, we get this thing, which we can multiply by some $\\alpha$ and subtract from $\\boldsymbol{b_2}$. It pops up again and ends up backpropagating through the gradients, so we'll call it $\\boldsymbol{\\delta_2}$.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_2}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\odot\n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n\\boldsymbol{\\delta_2}\n$$\n\n$$\n\\boldsymbol{b_2}\n-\n\\Delta \\boldsymbol{b_2}\n=\n\\boldsymbol{b_2}\n-\n\\alpha \\boldsymbol{\\delta_2}\n$$\n\nWhere $\\odot$ is element-wise multiplication, aka the Hadamard Product: https://en.wikipedia.org/wiki/Hadamard_product_(matrices). \n\nSo, everything's been a convenient shape so far, and we've only use shape-preserving operations to assemble the pieces we need and combine them together. What about for the next parameter set in line, $\\boldsymbol{w_2}$? If we take a look at the Chain Rule equations again, we see that we need to use this $\\boldsymbol{\\delta_2}$ to make the gradient $\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}$ to increment $\\boldsymbol{w_2}$.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}\n=\n\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2} }\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}\n$$\n\nNow, $\\boldsymbol{b_2}$ looks like this:\n\n\n```python\ndisplay(b_2)\n```\n\nKeeping in mind that $\\boldsymbol{\\delta_2}$ is the same shape as $\\boldsymbol{b_2}$,\n\n$\\boldsymbol{w_2}$ looks like this:\n\n\n```python\ndisplay(w_2)\n```\n\nHow is this supposed to work out? They're not the same shape! We can't hope to get there with shape-preserving operations!\n\nWell, we don't have to preserve shape, we just need to put things together from other things that they depend on. You can have more than one thing in $\\boldsymbol{w_2}$ depend on a single item in $\\boldsymbol{b_2}$. Specifically, differentiation rules show that we'll be using the *Sum Rule* in addition to the Chain Rule and company. This means we'll need to multiply things together, sum them, and stick them in matrices. \n\nThat sounds a lot like matrix multiplication... because it *is* matrix multiplication. We'll specifically be doing a special kind of matrix multiply that's called the *outer product* or *tensor product* (https://en.wikipedia.org/wiki/Outer_product). It will take two vectors and make a matrix out of them. It's like making a transformation between dimensions using two vectors. Like making a function from two vectors. In magic box terms, that looks a bit like this:\n\n\n\n**Note: Transpose and Outer Product functions make functions from their inputs. Since having an arrow to another magic box would be confusing, we show the functions being operated on as being enclosed in bubbles. A magic box enters another one as a bubble, and exits as a modified version of itself. A pair of pegs gets combined to make a peg mapping magic box, and exits the magic box in a bubble. \n**\n\nIf we look at the Chain Rule formulas again, we see that we need to multiply our $\\boldsymbol{\\delta_2}$ by the derivative $\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}$: \n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}\n=\n\\frac{\\partial J}{ \\partial \\boldsymbol{y ̂ }} \n\\frac{\\partial \\boldsymbol{y ̂ }}{\\partial \\boldsymbol{z_2} } \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2} }\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}\n$$\n\nApplying differentiation rules, we see that it's equal to the **activations of the hidden layer** $\\boldsymbol{a}$.\n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{w_2}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{w_2}}\n\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)\n=\n\\boldsymbol{a}$$\n\nNow, $\\boldsymbol{a}$ is the same shape, (4,1), as $\\boldsymbol{b_1}$ which looks like this:\n\n\n```python\ndisplay(b_1)\n```\n\n$\\boldsymbol{b_2}$ is shaped like (2,1) and looks like this:\n\n\n```python\ndisplay(b_2)\n```\n\nCan we make a (2,4) shape matrix from a (2,1) and a (4,1)? Intuitively, if you have something of the shape output by a matrix multiply, and something of the shape going into a matrix multiply, you should be able to reconstruct a matrix of the same shape used in the multiply. With the outer product, we can do exactly that and make a matrix from two vectors:\n\n\n```python\ndisplay(delta_2, hidden_activations)\ndisplay(delta_2*hidden_activations.T)\n```\n\nThis is the right shape, and actually gives us our gradient for incrementing $\\boldsymbol{w_2}$, but let's zoom in a bit, and take a look at why.\n\n Looking at the forward pass, we can examine what $\\boldsymbol{z_2}=\\boldsymbol{w_2 a}+\\boldsymbol{b_2}$:\n\n\n```python\nw_2*hidden_activations+b_2\n```\n\nHmm, those expressions look very similar. If you *remove the addition symbols*, and *got rid of the biases and $w_2$ factors*, it looks like you could multiply $\\boldsymbol{\\delta_2}$ by each column to get the same result as the outer product between $\\boldsymbol{\\delta_2}$ and $\\boldsymbol{a}$. You can see that as seen mentioned in the lecture notes for CS231N, the pieces of $\\boldsymbol{\\delta_2}$ are distributed amongst its dependants in $\\boldsymbol{a}$, **splitting along sum gates**.\n\nNow we need to backpropagate our gradients through the hidden layer to the biases and weights on the other side. If we look at a matrix transpose operation as taking a transformation between dimensions and flipping it, then we can use $\\boldsymbol{w_2}$ to at least get our gradients in the shape we want. Essentially, with the matrix transpose, we have another magic box that takes in magic boxes, and spits out new magic boxes. \n\n\n\nOur equations of interest (again from the Chain Rule formulas):\n\n$$\\frac{\\partial J}{\\partial \\boldsymbol{b_1}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}} \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1} }\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{a}}\n\\left( \\boldsymbol{w_2 a}+\\boldsymbol{b_2}\\right)\n=\n\\boldsymbol{w_2}^T\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{b_1}}\n\\left( \\boldsymbol{w_1 x}+\\boldsymbol{b_1}\\right)\n=\n\\boldsymbol{1}\n$$\n\n$$\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} }\n=\n\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle\n=\n\\boldsymbol{w_2} \\cdot \\boldsymbol{\\delta_2} \n=\n\\boldsymbol{w_2}^T\\boldsymbol{\\delta_2}\n$$\n\nWhere $\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle$ is the **inner product** (in this case, called the **dot product**) of the matrices $\\boldsymbol{w_2}$ and $\\boldsymbol{\\delta_2}$ :\nhttps://en.wikipedia.org/wiki/Inner_product_space\nhttps://en.wikipedia.org/wiki/Dot_product\n\nWe can see that we have $\\boldsymbol{w_2}^T$ as a factor, which is (4,2) shaped, and looks like this:\n\n\n```python\ndisplay(w_2.T)\n```\n\n$\\boldsymbol{\\delta_2}$ is (2,1) shaped, and looks like this:\n\n\n```python\ndisplay(delta_2)\n```\n\nIf we multiply them together as $\\boldsymbol{w_2}^T\\boldsymbol{\\delta_2}$, we get:\n\n\n```python\nw_2.T*delta_2\n```\n\nWhich is (4,1) shaped, just what we need for incrementing the bias vector $\\boldsymbol{b_1}$. Except for one element-wise factor, that is. We need the derivative of the hidden layer's activation w.r.t its input. Once we multiply that through, we'll have our $\\boldsymbol{\\delta_1}$ which is the gradient that we can use to move our $\\boldsymbol{b_1}$ in the direction of *goodness*.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_1}}\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n=\n\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle\n\\odot \\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} }\n\\odot \\boldsymbol{1}\n=\n\\boldsymbol{\\delta_1} \\odot \\boldsymbol{1}\n=\n\\boldsymbol{\\delta_1} \n$$\n\nNow we need to compute our $\\frac{\\partial J}{\\partial \\boldsymbol{ w_1 }}$ gradient for incrementing our weight matrix $\\boldsymbol{ w_1 }$. Another peek at our formulas shows that we have one more shape-changing outer product to go.\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{ w_1 }}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}} \n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{w_1}}\n=\n\\boldsymbol{\\delta_1}\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{ w_1 }}\n$$\n\n$$\n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{ w_1 }}\n=\n\\frac{\\partial}{\\partial \\boldsymbol{ w_1 }}\n\\left( \\boldsymbol{w_1 x}+\\boldsymbol{b_1}\\right)\n=\n\\boldsymbol{x}^T\n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{w_1}}\n=\n\\boldsymbol{\\delta_1}\n\\otimes\n\\boldsymbol{x}\n=\n\\boldsymbol{\\delta_1}\n\\boldsymbol{x}^T\n$$\n\nWe'll multiply that out, and you can again see that distribution of gradients through summing operations at work here:\n\n\n```python\ndisplay(delta_1, input_x)\ndisplay(delta_1*input_x.T)\n```\n\nThat last matrix is our gradient $\\frac{\\partial J}{\\partial \\boldsymbol{w_1}}$, and we're now done!\n\nJust for reference, here's the corresponding feedforward portion $\\boldsymbol{z_1}$ so you can see the distribution of the gradient through sum gates again:\n\n\n```python\ndisplay(w_1*input_x+b_1)\n```\n\nThat concludes this example, but keep in mind that to backpropagate through more layers simply requires repeating the last few steps until you have all the gradients you need. You're after those $\\boldsymbol{\\delta}$ vectors, and the rest is rather simple.\n\nNow, we’re missing a few element-wise factors when we look at the shape this way, but let’s fill those in. Chain rule says we need these things for all the derivatives for a one-hidden-layer network. We’re missing these activation function derivatives and this cost function derivative w.r.t to y_approx. We pretty much know those if we know what activation and cost functions we’re using. We'll use sigmoid with MSE for the sake of finishing this example, but keep in mind that you can use ReLU or Softmax activations, and Cross-Entropy loss too:\n* https://en.wikipedia.org/wiki/Rectifier_(neural_networks)\n* https://en.wikipedia.org/wiki/Softmax_function\n* https://en.wikipedia.org/wiki/Cross_entropy\n\nMSE gives the loss function:\n\n$$\n\\frac{1}{m}\n\\sum^{m}_{i=1}\n(\\boldsymbol{y}-\\hat{\\boldsymbol{y}})^2\n$$\n\nDifferentiation rules tell us to sum all $m$ derivatives, bring down the power of 2 to cancel the $\\frac{1}{2}$ factor, and bring out the negative sign due to the Chain Rule. This results in a derivative that looks like:\n\n$$\\frac{\\partial J}{\\partial \\boldsymbol{\\hat{\\boldsymbol{y}}}}\n=\n-(\\boldsymbol{y}-\\hat{\\boldsymbol{y}})\n=\n(\\hat{\\boldsymbol{y}}-\\boldsymbol{y})$$\n\nSigmoid units have the form:\n\n$$\\boldsymbol{\\sigma}(\\boldsymbol{z})=\\frac{1}{1+e^{-\\boldsymbol{z}}}$$\n\nWhich has the derivative (see http://mathworld.wolfram.com/SigmoidFunction.html):\n\n$$\n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z}}\n=\n\\frac{\\partial \\boldsymbol{\\sigma(\\boldsymbol{z})}}{\\partial \\boldsymbol{z}}\n=\n\\boldsymbol{\\sigma}(\\boldsymbol{z})(1-\\boldsymbol{\\sigma}(\\boldsymbol{z}))\n$$\n\nPlug those into your equations and you get:\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_2}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n\\frac{\\partial J}{\\partial \\boldsymbol{y ̂}} \n\\odot\n\\frac{\\partial \\boldsymbol{y ̂}}{\\partial\\boldsymbol{z_2}}\n=\n(\\hat{\\boldsymbol{y}}-\\boldsymbol{y})\n\\odot\n\\left[\\boldsymbol{\\sigma}(\\boldsymbol{z})(1-\\boldsymbol{\\sigma}(\\boldsymbol{z}))\\right]\n=\n\\boldsymbol{\\delta_2}\n$$\n\n$$\\frac{\\partial J}{\\partial \\boldsymbol{ w_2 }}\n=\n\\boldsymbol{\\delta_2}\n\\otimes\n\\boldsymbol{a}\n=\n\\boldsymbol{\\delta_2}\\boldsymbol{a}^T\n=\n(\\hat{\\boldsymbol{y}}-\\boldsymbol{y})\n\\odot \n\\left[\\boldsymbol{\\sigma}(\\boldsymbol{z})(1-\\boldsymbol{\\sigma}(\\boldsymbol{z}))\\right]\n\\otimes\n\\boldsymbol{a}\n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{b_1}}\n=\n\\boldsymbol{\\delta_2}\n\\frac{\\partial \\boldsymbol{z_2}}{\\partial \\boldsymbol{a} } \n\\frac{\\partial \\boldsymbol{a}}{\\partial \\boldsymbol{z_1} } \n\\frac{\\partial \\boldsymbol{z_1}}{\\partial \\boldsymbol{b_1}}\n=\n\\langle \\boldsymbol{w_2},\\boldsymbol{\\delta_2}\\rangle\n\\odot \n\\left[\\boldsymbol{\\sigma}(\\boldsymbol{z})(1-\\boldsymbol{\\sigma}(\\boldsymbol{z}))\\right]\n=\n\\boldsymbol{\\delta_1} \n$$\n\n$$\n\\frac{\\partial J}{\\partial \\boldsymbol{w_1}}\n=\n\\boldsymbol{\\delta_1}\n\\otimes\n\\boldsymbol{x}\n=\n\\boldsymbol{\\delta_1}\n\\boldsymbol{x}^T\n$$\n\nThat wraps up this example and this notebook! I would highly recommend checking out the code from Andrew Trask, which takes backpropagation and packages it up in an object-oriented fashion, tying into the computational graph structure we discussed, and connecting to the computational graph structure that's actually used by TensorFlow under the hood!\n\nhttps://iamtrask.github.io/2017/03/21/synthetic-gradients/\n\nWe'll be moving onto Optimization and Regularization next!\n", "meta": {"hexsha": "ca0c4d96fd50242366666440877c23937ce2a694", "size": 240177, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1_Intro_Comp_Graphs_Backprop/1_Intro_Comp_Graphs_Backprop.ipynb", "max_stars_repo_name": "BugBiteSquared/uofuDL-IS", "max_stars_repo_head_hexsha": "be128d4fd5cf3cc801478942fa00a266d2c3e015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1_Intro_Comp_Graphs_Backprop/1_Intro_Comp_Graphs_Backprop.ipynb", "max_issues_repo_name": "BugBiteSquared/uofuDL-IS", "max_issues_repo_head_hexsha": "be128d4fd5cf3cc801478942fa00a266d2c3e015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1_Intro_Comp_Graphs_Backprop/1_Intro_Comp_Graphs_Backprop.ipynb", "max_forks_repo_name": "BugBiteSquared/uofuDL-IS", "max_forks_repo_head_hexsha": "be128d4fd5cf3cc801478942fa00a266d2c3e015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 100.7031446541, "max_line_length": 41451, "alphanum_fraction": 0.8078042444, "converted": true, "num_tokens": 13714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.16984457610209006}} {"text": "# O Jupyter Notebook\n\nEste documento é um *Jupyter Notebook*, esta é uma forma exploratória de editar e executar códigos em Python. Uma das grandes vantagens do *Notebook* é ser capaz de apresentar textos formatados lado a lado com códigos em Python.\n\n## As células do *notebook*\n\nA estrutura básica de um *notebook* é a célula. Cada célula tem um objetivo único, que pode ser conter, por exemplo um **texto**, **código**, **metadados** ou muitos outros tipos de dados que não trataremos aqui.\n\nPor exemplo, a próxima célula apresenta um código. Que efetua a seguinte operação\n\n\\begin{equation}\n5+2 = 7\n\\end{equation}\n\nPara executar selecione \n\n\n```python\n5+2\n```\n\n\n\n\n 7\n\n\n\nO código é escrito na lingagem Python e efetua uma operação aritmética básica. Poderíamos também executar um comando Python diretamente.\n\n\n```python\nprint(\"Olá Mundo\")\n```\n\n Olá Mundo\n\n\nDigitar alguma coisa sem sentido em uma célula de código nos da um erro Python\n\n\n```python\nimprime(\"Olá Mundo\")\n```\n\n## Modo texto\n\nUma célula em modo texto (Markdown), não é interpretada pelo Python. Você pode considerar que ela funciona como um comentário. Você pode inserir utilizando a sintaxe do [Markdown](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html). Pode inclusive incluir a notação matemática do LaTex.\n\n\\begin{equation}\n\\sum_{i=0}^n \\frac{ (-1)^n f(x)^{(n)}(x-a)}{n!}\n\\end{equation}\n\n\n## Estados do notebook\n\nO notebook pode ficar em dois estados\n\n* Edição (caixa verde) Tecla: ENTER\n* Comando (caixa azul) Tecla: ESC\n\nNo modo de edição as setas e teclas manipulam o conteúdo da célula. No modo de comando as setas movem entre células e as outras teclas representam comandos.\n\nNo dia de hoje, iremos aprender Python em conjunto com a manipulação dos **notebooks**.\n\n### Praticando\n\nPratique adicionando células novas, tanto do tipo **texto**, como **código**, fazendo operações aritméticas simples e texto formatado utilizando a linguagem Markdown.\n\n| Atalho | Função |\n|--------|--------|\n| ENTER | Edita a célula |\n| SHIFT-ENTER | Executa a célula |\n| Setas | Move o cursor |\n| a | Adiciona uma célula acima |\n| b | Adiciona uma célula abaixo\n| y | Muda o tipo de célula para CÓDIGO |\n| m | Muda o tipo de célula para TEXTO |\n| x | Corta célula |\n| c | Copia célula |\n| v | Cola célula abaixo |\n\n", "meta": {"hexsha": "e0710f4fd0403f19a5de1aa5c0932a097abc1fbc", "size": 5857, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "aulas/01-JupyterNotebook.ipynb", "max_stars_repo_name": "igormorgado/introducaopython", "max_stars_repo_head_hexsha": "26d9eb0a57c22774e43bd3a79de849ca2e9c0f59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-03-18T19:38:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T20:36:43.000Z", "max_issues_repo_path": "aulas/01-JupyterNotebook.ipynb", "max_issues_repo_name": "igormorgado/introducaopython", "max_issues_repo_head_hexsha": "26d9eb0a57c22774e43bd3a79de849ca2e9c0f59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aulas/01-JupyterNotebook.ipynb", "max_forks_repo_name": "igormorgado/introducaopython", "max_forks_repo_head_hexsha": "26d9eb0a57c22774e43bd3a79de849ca2e9c0f59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-08T14:23:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T14:36:18.000Z", "avg_line_length": 25.1373390558, "max_line_length": 351, "alphanum_fraction": 0.547891412, "converted": true, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.16946365188027615}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (2 chains in 2 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n\n
\n\n\n\n Sampling 2 chains for 5_000 tune and 10_000 draw iterations (10_000 + 20_000 draws total) took 18 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint(\"lambda_1 mean: {0:.3f}\".format(lambda_1_samples.mean()))\nprint(\"lambda_2 mean: {0:.3f}\".format(lambda_2_samples.mean()))\n```\n\n lambda_1 mean: 17.768\n lambda_2 mean: 22.704\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n(lambda_2_samples / lambda_1_samples).mean()\n```\n\n\n\n\n 1.2794553996488207\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "b3b4d2229e7a6c34644e75dff9182d3253a0e58b", "size": 811107, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "StanleyTuz/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "cce98755dcffac4b04b05b13c921a42921bcfb93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "StanleyTuz/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "cce98755dcffac4b04b05b13c921a42921bcfb93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "StanleyTuz/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "cce98755dcffac4b04b05b13c921a42921bcfb93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 739.38650866, "max_line_length": 192534, "alphanum_fraction": 0.7435319878, "converted": true, "num_tokens": 11423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1681689071028012}} {"text": "```python\nfrom IPython.core.display import HTML\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n# Lecture 2: What is an optimization problem and how to solve them?\n\n# What is an optimization problem?\n\nA general mathematical formulation for **the optimization problems studied on this course** is\n$$\n\\begin{align} \\\n\\min \\quad &f(x)\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_k(x) = 0\\text{ for all }k=1,\\ldots,K\\\\\n&x\\in \\mathbb R^n.\n\\end{align}\n$$\n\nThe above problem can be expressed as \n>Find an $x\\in \\mathbb R^n$ such that $g_j(x)\\geq 0$ for all $j=1,\\ldots,J$ and $h_k(x)=0$ for all $k=1,\\ldots,K$, and there does not exist $x'\\in \\mathbb R^n$ such that $f(x')0$ such that there does not exist a feasible solution $x'\\in \\operatorname{B}(x^*,r)$ such that $f(x')Examples of mathematical programming
\n\n# How to solve optimization problems?\n\n## Iterative vs. non-iterative methods\n\nOptimal solutions to some optimization problems can be found by defining an explicit formula for it. For example, if the objective function is twice continuously differentiable and there are no constraints, the optimal solution (if exists) can be found by calculating all the zero-points of the gradient and finding the best one of those. In this kinds of cases, the optimization problem **can be solved using non-iterative methods.**\n\n\n```python\nImage(filename = \"Images\\LocalVsGlobal2D.jpg\", width = 400, height = 300)\n```\n\n\n\n\n \n\n \n\n\n\n\n**In this course we concentrate on the iterative methods.** Iterative methods are needed, if the problem has constraints, or the problem is in some other way not-well behaved (to be defined later, depending on the context). In iterative methods, solving the optimization problem starts from a so-called starting solution and then tries to improve the solution iteratively. The optimization algorithm chooses how the solution is changed at each iteration.\n\n## What kind of methods will you learn in this course?\nDifferent optimization problems require different methods. In this course, we study optimization problems, which are\n* nonlinear\n* not hugely multimodal\n\nOften the methods cannot guarantee a (global) optimum, but instead **we need to satisfy ourselves with a local optimum**. In addition, it is usually not possible to find the actual optimal solution since numerical methods are used, but instead **an approximation of the optimal solution**. A feasible solution $x^*$ is called an approximation of a local optimum $x^{**}$ with quality $L>0$, when $\\|x^*-x^{**}\\|\\leq L$.\n\n\n# Line search\n\nLet us study optimization problem $\\min_{x\\in[a,b]} f(x)$, where $a,b\\in\\mathbb R$. Let us try to find an approximation of a local optimum to this problem. \n\nNote: We have to assume that $f$ is *unimodal* in $[a,b]$, i.e. there exists a point $c\\in (a,b)$ such that $f$ is strictly decreasing in $[a,c)$ and strictly increasing in $(c,b]$ \n\n\n```python\n#Example objective function\ndef f(x):\n return 2+(1-x)**2\n```\n\n\n```python\nprint(\"The value of the objective function at 3 is \" + str(f(3)))\n```\n\n The value of the objective function at 3 is 6\n\n\n## Line search with fixed steps\n**input:** the quality $L>0$ of the approximation of the local optimum. \n**output:** an approximation of the local optimum with quality $L$.\n```\nstart with x as the start point of the interval\nloop until stops:\n if the value of the objective is increasing for x+L from x\n stop, because the approximation of the locally optimal solution is x \n increase x by L\n```\n\n\n```python\ndef fixed_steps_line_search(a,b,f,L):\n x = a\n while f(x)>f(x+L) and x+L0$ of the approximation of the local optimum. \n**output:** an approximation of the local optimum with quality $L$.\n```\nSet x as the start point of interval and y as the end point\nwhile y-x>2*L:\n if the function is increasing at the mid point between x and y:\n set y as the midpoint between y and x, because a local optimum is before the midpoint\n otherwise:\n set x as the midpoint, because a local optimum is after the midpoint\nreturn midpoint between x and y\n```\n\nThe following function is completed live in class as an exercise. **Try to do it yourself before checking an answer below!** Follow the pseudo code given in the above cell.\n\nThis is what we should end up. The following function is not shown on the slides.\n\n\n```python\ndef bisection_line_search(a,b,f,L,epsilon): \n x = a\n y = b\n while y-x>2*L:\n c = (x+y)/2\n if f(c+epsilon) > f(c-epsilon):\n y = c+epsilon\n else:\n x = c-epsilon\n return (x+y)/2\n \n```\n\n\n```python\nx = bisection_line_search(0.0,3.0,f,0.001,1e-5); print(\"optimum is \"+str(x)+\", function value is \" +str(f(x)))\n```\n\n optimum is 0.9997591943359379, function value is 2.000000057987368\n\n\n\n```python\n%timeit bisection_line_search(0.0,3.0,f,1e-3,1e-4)\n```\n\n 9.98 µs ± 849 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n\nWhat is the role of $\\epsilon$ in the bisection_line_search above?\n\n## Golden section search (known also as Fibonacci search)\n\n### Golden section \n\nLet $a0$ of the approximation of the local optimum. \n**output:** an approximation of the local optimum with quality $L$.\n```\nSet x as the start point of interval and y as the end point\nwhile y-x>2*L:\n Divide the interval [x,y] in the golden section from the left and right and attain two division points\n If the greater of the division points has a greater function value \n set y as the rightmost division point, because a local optimum is before that\n otherwise:\n set x as the leftmost division point, because a local optimum is after that\nreturn midpoint between x and y\n```\n\nThe following function is completed in class as an exercise. **Try to do it yourself before checking an answer below!** Follow the pseudo code given in the above cell.\n\n\n```python\nimport math\ndef golden_section_line_search(a,b,f,L):\n x = a\n y = b\n while y-x>2*L:\n gr = (math.sqrt(5)-1)/2\n d = x + gr*(y-x)\n c = y - gr*(y-x)\n if f(d)>f(c):\n y = d\n else:\n x = c\n return (x+y)/2\n\n```\n\n\n```python\nx = golden_section_line_search(0.0,3.0,f,0.0001); print(\"optimum is \"+str(x)+\", function value is \" +str(f(x)))\n```\n\n optimum is 0.999966946519324, function value is 2.0000000010925327\n\n\n\n```python\n%timeit golden_section_line_search(0.0,3.0,f,1e-3)\n```\n\n 17.9 µs ± 2.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n\n**What can you conclude from the execution times for the three different methods?**\n", "meta": {"hexsha": "7ccd723b92747131165e7e2add443698826f6753", "size": 364322, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture 2, What is an optimization problem and how to solve them and line search.ipynb", "max_stars_repo_name": "bshavazipour/TIES483-2022", "max_stars_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture 2, What is an optimization problem and how to solve them and line search.ipynb", "max_issues_repo_name": "bshavazipour/TIES483-2022", "max_issues_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 2, What is an optimization problem and how to solve them and line search.ipynb", "max_forks_repo_name": "bshavazipour/TIES483-2022", "max_forks_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T09:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:02.000Z", "avg_line_length": 268.080941869, "max_line_length": 110949, "alphanum_fraction": 0.8992402325, "converted": true, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.1681465322806429}} {"text": "\n# Oscillations\n\n \n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA and Department of Physics, University of Oslo, Norway \n\n **[Scott Pratt](https://pa.msu.edu/profile/pratts/)**, Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University, USA \n\n **[Carl Schmidt](https://pa.msu.edu/profile/schmidt/)**, Department of Physics and Astronomy, Michigan State University, USA\n\nDate: **Feb 22, 2020**\n\nCopyright 1999-2020, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n\n\n\n\n\n## Harmonic Oscillator\n\nThe harmonic oscillator is omnipresent in physics. Although you may think \nof this as being related to springs, it, or an equivalent\nmathematical representation, appears in just about any problem where a\nmode is sitting near its potential energy minimum. At that point,\n$\\partial_x V(x)=0$, and the first non-zero term (aside from a\nconstant) in the potential energy is that of a harmonic oscillator. In\na solid, sound modes (phonons) are built on a picture of coupled\nharmonic oscillators, and in relativistic field theory the fundamental\ninteractions are also built on coupled oscillators positioned\ninfinitesimally close to one another in space. The phenomena of a\nresonance of an oscillator driven at a fixed frequency plays out\nrepeatedly in atomic, nuclear and high-energy physics, when quantum\nmechanically the evolution of a state oscillates according to\n$e^{-iEt}$ and exciting discrete quantum states has very similar\nmathematics as exciting discrete states of an oscillator.\n\nThe potential energy for a single particle as a function of its position $x$ can be written as a Taylor expansion about some point $x_0$\n\n\n
\n\n$$\n\\begin{equation}\nV(x)=V(x_0)+(x-x_0)\\left.\\partial_xV(x)\\right|_{x_0}+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0}\n+\\frac{1}{3!}\\left.\\partial_x^3V(x)\\right|_{x_0}+\\cdots\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nIf the position $x_0$ is at the minimum of the resonance, the first two non-zero terms of the potential are\n\n$$\n\\begin{eqnarray}\nV(x)&\\approx& V(x_0)+\\frac{1}{2}(x-x_0)^2\\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\n&=&V(x_0)+\\frac{1}{2}k(x-x_0)^2,~~~~k\\equiv \\left.\\partial_x^2V(x)\\right|_{x_0},\\\\\n\\nonumber\nF&=&-\\partial_xV(x)=-k(x-x_0).\n\\end{eqnarray}\n$$\n\nPut into Newton's 2nd law (assuming $x_0=0$),\n\n$$\n\\begin{eqnarray}\nm\\ddot{x}&=&-kx,\\\\\nx&=&A\\cos(\\omega_0 t-\\phi),~~~\\omega_0=\\sqrt{k/m}.\n\\end{eqnarray}\n$$\n\nHere $A$ and $\\phi$ are arbitrary. Equivalently, one could have\nwritten this as $A\\cos(\\omega_0 t)+B\\sin(\\omega_0 t)$, or as the real\npart of $Ae^{i\\omega_0 t}$. In this last case $A$ could be an\narbitrary complex constant. Thus, there are 2 arbitrary constants\n(either $A$ and $B$ or $A$ and $\\phi$, or the real and imaginary part\nof one complex constant. This is the expectation for a second order\ndifferential equation, and also agrees with the physical expectation\nthat if you know a particle's initial velocity and position you should\nbe able to define its future motion, and that those two arbitrary\nconditions should translate to two arbitrary constants.\n\nA key feature of harmonic motion is that the system repeats itself\nafter a time $T=1/f$, where $f$ is the frequency, and $\\omega=2\\pi f$\nis the angular frequency. The period of the motion is independent of\nthe amplitude. However, this independence is only exact when one can\nneglect higher terms of the potential, $x^3, x^4\\cdots$. Once can\nneglect these terms for sufficiently small amplitudes, and for larger\namplitudes the motion is no longer purely sinusoidal, and even though\nthe motion repeats itself, the time for repeating the motion is no\nlonger independent of the amplitude.\n\nOne can also calculate the velocity and the kinetic energy as a function of time,\n\n$$\n\\begin{eqnarray}\n\\dot{x}&=&-\\omega_0A\\sin(\\omega_0 t-\\phi),\\\\\n\\nonumber\nK&=&\\frac{1}{2}m\\dot{x}^2=\\frac{m\\omega_0^2A^2}{2}\\sin^2(\\omega_0t-\\phi),\\\\\n\\nonumber\n&=&\\frac{k}{2}A^2\\sin^2(\\omega_0t-\\phi).\n\\end{eqnarray}\n$$\n\nThe total energy is then\n\n\n
\n\n$$\n\\begin{equation}\nE=K+V=\\frac{1}{2}m\\dot{x}^2+\\frac{1}{2}kx^2=\\frac{1}{2}kA^2.\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\nThe total energy then goes as the square of the amplitude.\n\n\nA pendulum is an example of a harmonic oscillator. By expanding the\nkinetic and potential energies for small angles find the frequency for\na pendulum of length $L$ with all the mass $m$ centered at the end by\nwriting the eq.s of motion in the form of a harmonic oscillator.\n\nThe potential energy and kinetic energies are (for $x$ being the displacement)\n\n$$\n\\begin{eqnarray*}\nV&=&mgL(1-\\cos\\theta)\\approx mgL\\frac{x^2}{2L^2},\\\\\nK&=&\\frac{1}{2}mL^2\\dot{\\theta}^2\\approx \\frac{m}{2}\\dot{x}^2.\n\\end{eqnarray*}\n$$\n\nFor small $x$ Newton's 2nd law becomes\n\n$$\nm\\ddot{x}=-\\frac{mg}{L}x,\n$$\n\nand the spring constant would appear to be $k=mg/L$, which makes the\nfrequency equal to $\\omega_0=\\sqrt{g/L}$. Note that the frequency is\nindependent of the mass.\n\n\n## Damped Oscillators\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{4}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([4](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto6} \\tag{7}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto7} \\tag{8}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $e{rt}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{9}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{10}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\n## Our Sliding Block Code\nHere we study first the case without additional friction term and scale our equation\nin terms of a dimensionless time $\\tau$.\n\nLet us remind ourselves about the differential equation we want to solve (the general case with damping due to friction)\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0.\n$$\n\nWe divide by $m$ and introduce $\\omega_0^2=\\sqrt{k/m}$ and obtain\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =0.\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$ (check\nthat the dimensionality is correct) and rewrite our equation as\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0,\n$$\n\nwhich gives us\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nWe then define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =0.\n$$\n\nThis is the equation we will code below. The first version employs the Euler-Cromer method.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nfrom pylab import plt, mpl\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'serif'\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as simple one-dimensional arrays of time\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.0\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"BlockEulerCromer\")\nplt.show()\n```\n\nWhen setting up the value of $\\gamma$ we see that for $\\gamma=0$ we get the simple oscillatory motion with no damping.\nChoosing $\\gamma < 1$ leads to the classical underdamped case with oscillatory motion, but where the motion comes to an end.\n\nChoosing $\\gamma =1$ leads to what normally is called critical damping and $\\gamma> 1$ leads to critical overdamping.\nTry it out and try also to change the initial position and velocity. Setting $\\gamma=1$\nyields a situation, as discussed above, where the solution approaches quickly zero and does not oscillate. With zero initial velocity it will never cross zero. \n\n## Sinusoidally Driven Oscillators\n\nHere, we consider the force\n\n\n
\n\n$$\n\\begin{equation}\nF=-kx-b\\dot{x}+F_0\\cos\\omega t,\n\\label{_auto8} \\tag{11}\n\\end{equation}\n$$\n\nwhich leads to the differential equation\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:drivenosc} \\tag{12}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=(F_0/m)\\cos\\omega t.\n\\end{equation}\n$$\n\nConsider a single solution with no arbitrary constants, which we will\ncall a {\\it particular solution}, $x_p(t)$. It should be emphasized\nthat this is {\\bf A} particular solution, because there exists an\ninfinite number of such solutions because the general solution should\nhave two arbitrary constants. Now consider solutions to the same\nequation without the driving term, which include two arbitrary\nconstants. These are called either {\\it homogenous solutions} or {\\it\ncomplementary solutions}, and were given in the previous section,\ne.g. Eq. ([9](#eq:homogsolution)) for the underdamped case. The\nhomogenous solution already incorporates the two arbitrary constants,\nso any sum of a homogenous solution and a particular solution will\nrepresent the {\\it general solution} of the equation. The general\nsolution incorporates the two arbitrary constants $A$ and $B$ to\naccommodate the two initial conditions. One could have picked a\ndifferent particular solution, i.e. the original particular solution\nplus any homogenous solution with the arbitrary constants $A_p$ and\n$B_p$ chosen at will. When one adds in the homogenous solution, which\nhas adjustable constants with arbitrary constants $A'$ and $B'$, to\nthe new particular solution, one can get the same general solution by\nsimply adjusting the new constants such that $A'+A_p=A$ and\n$B'+B_p=B$. Thus, the choice of $A_p$ and $B_p$ are irrelevant, and\nwhen choosing the particular solution it is best to make the simplest\nchoice possible.\n\nTo find a particular solution, one first guesses at the form,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{13}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$\n\nand rewrite the differential equation as\n\n\n
\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto9} \\tag{14}\n\\end{equation}\n$$\n\nOne can now use angle addition formulas to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$\n\nBoth the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$\n\nAfter dividing by $\\cos\\delta$, the lower expression leads to\n\n\n
\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto10} \\tag{15}\n\\end{equation}\n$$\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,\n\n$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$\n\nInserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{16}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$\n\nFor a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n## Alternative Derivation for Driven Oscillators\n\nHere, we derive the same expressions as in Equations ([13](#eq:partform)) and ([16](#eq:Ddrive)) but express the driving forces as\n\n$$\n\\begin{eqnarray}\nF(t)&=&F_0e^{i\\omega t},\n\\end{eqnarray}\n$$\n\nrather than as $F_0\\cos\\omega t$. The real part of $F$ is the same as before. For the differential equation,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:compdrive} \\tag{17}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x&=&\\frac{F_0}{m}e^{i\\omega t},\n\\end{eqnarray}\n$$\n\none can treat $x(t)$ as an imaginary function. Because the operations\n$d^2/dt^2$ and $d/dt$ are real and thus do not mix the real and\nimaginary parts of $x(t)$, Eq. ([17](#eq:compdrive)) is effectively 2\nequations. Because $e^{\\omega t}=\\cos\\omega t+i\\sin\\omega t$, the real\npart of the solution for $x(t)$ gives the solution for a driving force\n$F_0\\cos\\omega t$, and the imaginary part of $x$ corresponds to the\ncase where the driving force is $F_0\\sin\\omega t$. It is rather easy\nto solve for the complex $x$ in this case, and by taking the real part\nof the solution, one finds the answer for the $\\cos\\omega t$ driving\nforce.\n\nWe assume a simple form for the particular solution\n\n\n
\n\n$$\n\\begin{equation}\nx_p=De^{i\\omega t},\n\\label{_auto11} \\tag{18}\n\\end{equation}\n$$\n\nwhere $D$ is a complex constant.\n\nFrom Eq. ([17](#eq:compdrive)) one inserts the form for $x_p$ above to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2+2i\\beta\\omega+\\omega_0^2\\right\\}e^{i\\omega t}=(F_0/m)e^{i\\omega t},\\\\\n\\nonumber\nD=\\frac{F_0/m}{(\\omega_0^2-\\omega^2)+2i\\beta\\omega}.\n\\end{eqnarray}\n$$\n\nThe norm and phase for $D=|D|e^{-i\\delta}$ can be read by inspection,\n\n\n
\n\n$$\n\\begin{equation}\n|D|=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}},~~~~\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto12} \\tag{19}\n\\end{equation}\n$$\n\nThis is the same expression for $\\delta$ as before. One then finds $x_p(t)$,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven1} \\tag{20}\nx_p(t)&=&\\Re\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\cos(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nThis is the same answer as before.\nIf one wished to solve for the case where $F(t)= F_0\\sin\\omega t$, the imaginary part of the solution would work\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fastdriven2} \\tag{21}\nx_p(t)&=&\\Im\\frac{(F_0/m)e^{i\\omega t-i\\delta}}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\\\\\n\\nonumber\n&=&\\frac{(F_0/m)\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray}\n$$\n\nConsider the damped and driven harmonic oscillator worked out above. Given $F_0, m,\\beta$ and $\\omega_0$, solve for the complete solution $x(t)$ for the case where $F=F_0\\sin\\omega t$ with initial conditions $x(t=0)=0$ and $v(t=0)=0$. Assume the underdamped case.\n\nThe general solution including the arbitrary constants includes both the homogenous and particular solutions,\n\n$$\n\\begin{eqnarray*}\nx(t)&=&\\frac{F_0}{m}\\frac{\\sin(\\omega t-\\delta)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}\n+A\\cos\\omega't e^{-\\beta t}+B\\sin\\omega't e^{-\\beta t}.\n\\end{eqnarray*}\n$$\n\nThe quantities $\\delta$ and $\\omega'$ are given earlier in the\nsection, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2},\n\\delta=\\tan^{-1}(2\\beta\\omega/(\\omega_0^2-\\omega^2)$. Here, solving\nthe problem means finding the arbitrary constants $A$ and\n$B$. Satisfying the initial conditions for the initial position and\nvelocity:\n\n$$\n\\begin{eqnarray*}\nx(t=0)=0&=&-\\eta\\sin\\delta+A,\\\\\nv(t=0)=0&=&\\omega\\eta\\cos\\delta-\\beta A+\\omega'B,\\\\\n\\eta&\\equiv&\\frac{F_0}{m}\\frac{1}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\beta^2\\omega^2}}.\n\\end{eqnarray*}\n$$\n\nThe problem is now reduced to 2 equations and 2 unknowns, $A$ and $B$. The solution is\n\n$$\n\\begin{eqnarray}\nA&=& \\eta\\sin\\delta ,~~~B=\\frac{-\\omega\\eta\\cos\\delta+\\beta\\eta\\sin\\delta}{\\omega'}.\n\\end{eqnarray}\n$$\n\n## Resonance Widths; the $Q$ factor\n\nFrom the previous two sections, the particular solution for a driving force, $F=F_0\\cos\\omega t$, is\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\\cos(\\omega_t-\\delta),\\\\\n\\nonumber\n\\delta&=&\\tan^{-1}\\left(\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nIf one fixes the driving frequency $\\omega$ and adjusts the\nfundamental frequency $\\omega_0=\\sqrt{k/m}$, the maximum amplitude\noccurs when $\\omega_0=\\omega$ because that is when the term from the\ndenominator $(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2$ is at a\nminimum. This is akin to dialing into a radio station. However, if one\nfixes $\\omega_0$ and adjusts the driving frequency one minimize with\nrespect to $\\omega$, e.g. set\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{d\\omega}\\left[(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2\\right]=0,\n\\label{_auto13} \\tag{22}\n\\end{equation}\n$$\n\nand one finds that the maximum amplitude occurs when\n$\\omega=\\sqrt{\\omega_0^2-2\\beta^2}$. If $\\beta$ is small relative to\n$\\omega_0$, one can simply state that the maximum amplitude is\n\n\n
\n\n$$\n\\begin{equation}\nx_{\\rm max}\\approx\\frac{F_0}{2m\\beta \\omega_0}.\n\\label{_auto14} \\tag{23}\n\\end{equation}\n$$\n\n$$\n\\begin{eqnarray}\n\\frac{4\\omega^2\\beta^2}{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}=\\frac{1}{2}.\n\\end{eqnarray}\n$$\n\nFor small damping this occurs when $\\omega=\\omega_0\\pm \\beta$, so the $FWHM\\approx 2\\beta$. For the purposes of tuning to a specific frequency, one wants the width to be as small as possible. The ratio of $\\omega_0$ to $FWHM$ is known as the {\\it quality} factor, or $Q$ factor,\n\n\n
\n\n$$\n\\begin{equation}\nQ\\equiv \\frac{\\omega_0}{2\\beta}.\n\\label{_auto15} \\tag{24}\n\\end{equation}\n$$\n\n## Numerical Studies of Driven Oscillations\n\nSolving the problem of driven oscillations numerically gives us much\nmore flexibility to study different types of driving forces. We can\nreuse our earlier code by simply adding a driving force. If we stay in\nthe $x$-direction only this can be easily done by adding a term\n$F_{\\mathrm{ext}}(x,t)$. Note that we have kept it rather general\nhere, allowing for both a spatial and a temporal dependence.\n\nBefore we dive into the code, we need to briefly remind ourselves\nabout the equations we started with for the case with damping, namely\n\n$$\nm\\frac{d^2x}{dt^2} + b\\frac{dx}{dt}+kx(t) =0,\n$$\n\nwith no external force applied to the system.\n\nLet us now for simplicty assume that our external force is given by\n\n$$\nF_{\\mathrm{ext}}(t) = F_0\\cos{(\\omega t)},\n$$\n\nwhere $F_0$ is a constant (what is its dimension?) and $\\omega$ is the frequency of the applied external driving force.\n**Small question:** would you expect energy to be conserved now?\n\n\nIntroducing the external force into our lovely differential equation\nand dividing by $m$ and introducing $\\omega_0^2=\\sqrt{k/m}$ we have\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =\\frac{F_0}{m}\\cos{(\\omega t)},\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$\nand a dimensionless frequency $\\tilde{\\omega}=\\omega/\\omega_0$. We have then\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\frac{F_0}{m\\omega_0^2}\\cos{(\\tilde{\\omega}\\tau)},\n$$\n\nIntroducing a new amplitude $\\tilde{F} =F_0/(m\\omega_0^2)$ (check dimensionality again) we have\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nOur final step, as we did in the case of various types of damping, is\nto define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nThis is the equation we will code below using the Euler-Cromer method.\n\n\n```python\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions as one-dimensional arrays of time\nx0 = sqrt(1./3.)\nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.0\nOmegatilde = 8./sqrt(2.)\nFtilde = 1.75\n# Start integrating using Euler-Cromer's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n a = -2*gamma*v[i]-x[i]+Ftilde*cos(t[i]*Omegatilde)\n # update velocity, time and position\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockEulerCromer\")\nplt.show()\n```\n\nIn the above example we have focused on the Euler-Cromer method. This\nmethod has a local truncation error which is proportional to $\\Delta t^2$\nand thereby a global error which is proportional to $\\Delta t$.\nWe can improve this by using the Runge-Kutta family of\nmethods. The widely popular Runge-Kutta to fourth order or just **RK4**\nhas indeed a much better truncation error. The RK4 method has a global\nerror which is proportional to $\\Delta t$.\n\nLet us revisit this method and see how we can implement it for the above example.\n\n\n## Differential Equations, Runge-Kutta methods\n\nRunge-Kutta (RK) methods are based on Taylor expansion formulae, but yield\nin general better algorithms for solutions of an ordinary differential equation.\nThe basic philosophy is that it provides an intermediate step in the computation of $y_{i+1}$.\n\nTo see this, consider first the following definitions\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{dy}{dt}=f(t,y), \n\\label{_auto16} \\tag{25}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\ny(t)=\\int f(t,y) dt, \n\\label{_auto17} \\tag{26}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y_i+ \\int_{t_i}^{t_{i+1}} f(t,y) dt.\n\\label{_auto18} \\tag{27}\n\\end{equation}\n$$\n\nTo demonstrate the philosophy behind RK methods, let us consider\nthe second-order RK method, RK2.\nThe first approximation consists in Taylor expanding $f(t,y)$\naround the center of the integration interval $t_i$ to $t_{i+1}$,\nthat is, at $t_i+h/2$, $h$ being the step.\nUsing the midpoint formula for an integral, \ndefining $y(t_i+h/2) = y_{i+1/2}$ and \n$t_i+h/2 = t_{i+1/2}$, we obtain\n\n\n
\n\n$$\n\\begin{equation}\n\\int_{t_i}^{t_{i+1}} f(t,y) dt \\approx hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto19} \\tag{28}\n\\end{equation}\n$$\n\nThis means in turn that we have\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y_i + hf(t_{i+1/2},y_{i+1/2}) +O(h^3).\n\\label{_auto20} \\tag{29}\n\\end{equation}\n$$\n\nHowever, we do not know the value of $y_{i+1/2}$. Here comes thus the next approximation, namely, we use Euler's\nmethod to approximate $y_{i+1/2}$. We have then\n\n\n
\n\n$$\n\\begin{equation}\ny_{(i+1/2)}=y_i + \\frac{h}{2}\\frac{dy}{dt}=y(t_i) + \\frac{h}{2}f(t_i,y_i).\n\\label{_auto21} \\tag{30}\n\\end{equation}\n$$\n\nThis means that we can define the following algorithm for \nthe second-order Runge-Kutta method, RK2.\n\n6\n0\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n\n
\n\n$$\n\\begin{equation}\nk_2=hf(t_{i+1/2},y_i+k_1/2),\n\\label{_auto23} \\tag{32}\n\\end{equation}\n$$\n\nwith the final value\n\n\n
\n\n$$\n\\begin{equation} \ny_{i+i}\\approx y_i + k_2 +O(h^3). \n\\label{_auto24} \\tag{33}\n\\end{equation}\n$$\n\nThe difference between the previous one-step methods \nis that we now need an intermediate step in our evaluation,\nnamely $t_i+h/2 = t_{(i+1/2)}$ where we evaluate the derivative $f$. \nThis involves more operations, but the gain is a better stability\nin the solution.\n\nThe fourth-order Runge-Kutta, RK4, has the following algorithm\n\n6\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\nk_3=hf(t_i+h/2,y_i+k_2/2)\\hspace{0.5cm} k_4=hf(t_i+h,y_i+k_3)\n$$\n\nwith the final result\n\n$$\ny_{i+1}=y_i +\\frac{1}{6}\\left( k_1 +2k_2+2k_3+k_4\\right).\n$$\n\nThus, the algorithm consists in first calculating $k_1$ \nwith $t_i$, $y_1$ and $f$ as inputs. Thereafter, we increase the step\nsize by $h/2$ and calculate $k_2$, then $k_3$ and finally $k_4$. The global error goes as $O(h^4)$.\n\n\nHowever, at this stage, if we keep adding different methods in our\nmain program, the code will quickly become messy and ugly. Before we\nproceed thus, we will now introduce functions that enbody the various\nmethods for solving differential equations. This means that we can\nseparate out these methods in own functions and files (and later as classes and more\ngeneric functions) and simply call them when needed. Similarly, we\ncould easily encapsulate various forces or other quantities of\ninterest in terms of functions. To see this, let us bring up the code\nwe developed above for the simple sliding block, but now only with the simple forward Euler method. We introduce\ntwo functions, one for the simple Euler method and one for the\nforce.\n\nNote that here the forward Euler method does not know the specific force function to be called.\nIt receives just an input the name. We can easily change the force by adding another function.\n\n\n```python\ndef ForwardEuler(v,x,t,n,Force):\n for i in range(n-1):\n v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n```\n\n\n```python\ndef SpringForce(v,x,t):\n# note here that we have divided by mass and we return the acceleration\n return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)\n```\n\nIt is easy to add a new method like the Euler-Cromer\n\n\n```python\ndef ForwardEulerCromer(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n```\n\nand the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces))\n\n\n```python\ndef VelocityVerlet(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]+0.5*a\n anew = Force(v[i],x[i+1],t[i+1])\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK2(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Final result\n x[i+1] = x[i]+k2x\n v[i+1] = v[i]+k2v\n\tt[i+1] = t[i]+DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK4(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k3\n vv = v[i]+k2v*0.5\n xx = x[i]+k2x*0.5\n k3x = DeltaT*vv\n k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k4\n vv = v[i]+k3v\n xx = x[i]+k3x\n k4x = DeltaT*vv\n k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)\n# Final result\n x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.\n v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.\n t[i+1] = t[i] + DeltaT\n```\n\nThe Runge-Kutta family of methods are particularly useful when we have a time-dependent acceleration.\nIf we have forces which depend only the spatial degrees of freedom (no velocity and/or time-dependence), then energy conserving methods like the Velocity Verlet or the Euler-Cromer method are preferred. As soon as we introduce an explicit time-dependence and/or add dissipitave forces like friction or air resistance, then methods like the family of Runge-Kutta methods are well suited for this. \nThe code below uses the Runge-Kutta4 methods.\n\n\n```python\nDeltaT = 0.001\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions (can change to more than one dim)\nx0 = 1.0\nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 0.0\nOmegatilde = 0.2\nFtilde = 1.0\n\n# Start integrating using Euler's method\n# Note that we define the force function as a SpringForce\nRK4(v,x,t,n,SpringForce)\n\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, x)\nfig.tight_layout()\nsave_fig(\"ForcedBlockRK4\")\nplt.show()\n```\n\n\n## Principle of Superposition and Periodic Forces (Fourier Transforms)\n\nIf one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\nthe particular solution to each $F_n$, $x_{pn}(t)$, and the particular\nsolution for the entire driving force is\n\n\n
\n\n$$\n\\begin{equation}\nx_p(t)=\\sum_nx_{pn}(t).\n\\label{_auto25} \\tag{34}\n\\end{equation}\n$$\n\nThis is known as the principal of superposition. It only applies when\nthe homogenous equation is linear. If there were an anharmonic term\nsuch as $x^3$ in the homogenous equation, then when one summed various\nsolutions, $x=(\\sum_n x_n)^2$, one would get cross\nterms. Superposition is especially useful when $F(t)$ can be written\nas a sum of sinusoidal terms, because the solutions for each\nsinusoidal (sine or cosine) term is analytic, as we saw above.\n\nDriving forces are often periodic, even when they are not\nsinusoidal. Periodicity implies that for some time $\\tau$\n\n$$\n\\begin{eqnarray}\nF(t+\\tau)=F(t). \n\\end{eqnarray}\n$$\n\nOne example of a non-sinusoidal periodic force is a square wave. Many\ncomponents in electric circuits are non-linear, e.g. diodes, which\nmakes many wave forms non-sinusoidal even when the circuits are being\ndriven by purely sinusoidal sources.\n\nThe code here shows a typical example of such a square wave generated using the functionality included in the **scipy** Python package. We have used a period of $\\tau=0.2$.\n\n\n```python\nimport numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t)\nplt.plot(t, SqrSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()\n```\n\nFor the sinusoidal example studied in the previous subsections the\nperiod is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\nsatisfy the periodicity requirement. In general, any force that\nsatisfies the periodicity requirement can be expressed as a sum over\nharmonics,\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n\\label{_auto26} \\tag{35}\n\\end{equation}\n$$\n\nFrom the previous subsection, one can write down the answer for\n$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$ into Eq.s\n([20](#eq:fastdriven1)) or ([21](#eq:fastdriven2)) respectively. By\nwriting each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n2\\pi/\\tau$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:fourierdef1} \\tag{36}\nF(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n\\end{equation}\n$$\n\nThe solutions for $x(t)$ then come from replacing $\\omega$ with\n$n\\omega$ for each term in the particular solution in Equations\n([13](#eq:partform)) and ([16](#eq:Ddrive)),\n\n$$\n\\begin{eqnarray}\nx_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n\\nonumber\n\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n\\nonumber\n\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n\\end{eqnarray}\n$$\n\nBecause the forces have been applied for a long time, any non-zero\ndamping eliminates the homogenous parts of the solution, so one need\nonly consider the particular solution for each $n$.\n\nThe problem will considered solved if one can find expressions for the\ncoefficients $f_n$ and $g_n$, even though the solutions are expressed\nas an infinite sum. The coefficients can be extracted from the\nfunction $F(t)$ by\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fourierdef2} \\tag{37}\nf_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n\\nonumber\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n\\end{eqnarray}\n$$\n\nTo check the consistency of these expressions and to verify\nEq. ([37](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\nEq. ([36](#eq:fourierdef1)) into the expression for the coefficients in\nEq. ([37](#eq:fourierdef2)) and see whether\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\n\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\n\\right\\}\\cos(n\\omega t).\n\\end{eqnarray}\n$$\n\nImmediately, one can throw away all the terms with $g_m$ because they\nconvolute an even and an odd function. The term with $f_0/2$\ndisappears because $\\cos(n\\omega t)$ is equally positive and negative\nover the interval and will integrate to zero. For all the terms\n$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\nformulas to see that $\\cos(m\\omega t)\\cos(n\\omega\nt)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\nto zero unless $m=n$. In that case the $m=n$ term gives\n\n\n
\n\n$$\n\\begin{equation}\n\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n\\label{_auto27} \\tag{38}\n\\end{equation}\n$$\n\nand\n\n$$\n\\begin{eqnarray}\nf_n&=?&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2\\\\\n\\nonumber\n&=&f_n~\\checkmark.\n\\end{eqnarray}\n$$\n\nThe same method can be used to check for the consistency of $g_n$.\n\n\nConsider the driving force:\n\n\n
\n\n$$\n\\begin{equation}\nF(t)=At/\\tau,~~-\\tau/2\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:fouriersolution} \\tag{40}\ng_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2}dt~\\sin(n\\omega t) \\frac{At}{\\tau}\\\\\n\\nonumber\nu&=&t,~dv=\\sin(n\\omega t)dt,~v=-\\cos(n\\omega t)/(n\\omega),\\\\\n\\nonumber\ng_n&=&\\frac{-2A}{n\\omega \\tau^2}\\int_{-\\tau/2}^{\\tau/2}dt~\\cos(n\\omega t)\n+\\left.2A\\frac{-t\\cos(n\\omega t)}{n\\omega\\tau^2}\\right|_{-\\tau/2}^{\\tau/2}.\n\\end{eqnarray}\n$$\n\nThe first term is zero because $\\cos(n\\omega t)$ will be equally\npositive and negative over the interval. Using the fact that\n$\\omega\\tau=2\\pi$,\n\n$$\n\\begin{eqnarray}\ng_n&=&-\\frac{2A}{2n\\pi}\\cos(n\\omega\\tau/2)\\\\\n\\nonumber\n&=&-\\frac{A}{n\\pi}\\cos(n\\pi)\\\\\n\\nonumber\n&=&\\frac{A}{n\\pi}(-1)^{n+1}.\n\\end{eqnarray}\n$$\n\n## Fourier Series\n\nMore text will come here, chpater 5.7-5.8 of Taylor are discussed\nduring the lectures. The code here uses the Fourier series discussed\nin chapter 5.7 for a square wave signal. The equations for the\ncoefficients are are discussed in Taylor section 5.7, see Example\n5.4. The code here visualizes the various approximations given by\nFourier series compared with a square wave with period $T=0.2$, witth\n$0.1$ and max value $F=2$. We see that when we increase the number of\ncomponents in the Fourier series, the Fourier series approximation gets closes and closes to the square wave signal.\n\n\n```python\nimport numpy as np\nimport math\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n# number of points \nn = 500\n# start and final times \nt0 = 0.0\ntn = 1.0\n# Period \nT =0.2\n# Max value of square signal \nFmax= 2.0\n# Width of signal \nWidth = 0.1\nt = np.linspace(t0, tn, n, endpoint=False)\nSqrSignal = np.zeros(n)\nFourierSeriesSignal = np.zeros(n)\nSqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)\na0 = Fmax*Width/T\nFourierSeriesSignal = a0\nFactor = 2.0*Fmax/np.pi\nfor i in range(1,500):\n FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)\nplt.plot(t, SqrSignal)\nplt.plot(t, FourierSeriesSignal)\nplt.ylim(-0.5, 2.5)\nplt.show()\n```\n\n## Solving differential equations with Fouries series\n\nThe material here was discussed during the lecture of February 19 and 21.\nIt is also covered by Taylor in section 5.8.\n\n\n## Response to Transient Force\n\nConsider a particle at rest in the bottom of an underdamped harmonic\noscillator, that then feels a sudden impulse, or change in momentum,\n$I=F\\Delta t$ at $t=0$. This increases the velocity immediately by an\namount $v_0=I/m$ while not changing the position. One can then solve\nthe trajectory by solving Eq. ([9](#eq:homogsolution)) with initial\nconditions $v_0=I/m$ and $x_0=0$. This gives\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I}{m\\omega'}e^{-\\beta t}\\sin\\omega't, ~~t>0.\n\\label{_auto29} \\tag{41}\n\\end{equation}\n$$\n\nHere, $\\omega'=\\sqrt{\\omega_0^2-\\beta^2}$. For an impulse $I_i$ that\noccurs at time $t_i$ the trajectory would be\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\frac{I_i}{m\\omega'}e^{-\\beta (t-t_i)}\\sin[\\omega'(t-t_i)] \\Theta(t-t_i),\n\\label{_auto30} \\tag{42}\n\\end{equation}\n$$\n\nwhere $\\Theta(t-t_i)$ is a step function, i.e. $\\Theta(x)$ is zero for\n$x<0$ and unity for $x>0$. If there were several impulses linear\nsuperposition tells us that we can sum over each contribution,\n\n\n
\n\n$$\n\\begin{equation}\nx(t)=\\sum_i\\frac{I_i}{m\\omega'}e^{-\\beta(t-t_i)}\\sin[\\omega'(t-t_i)]\\Theta(t-t_i)\n\\label{_auto31} \\tag{43}\n\\end{equation}\n$$\n\nNow one can consider a series of impulses at times separated by\n$\\Delta t$, where each impulse is given by $F_i\\Delta t$. The sum\nabove now becomes an integral,\n\n\n
\n\n$$\n\\begin{eqnarray}\\label{eq:Greeny} \\tag{44}\nx(t)&=&\\int_{-\\infty}^\\infty dt'~F(t')\\frac{e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]}{m\\omega'}\\Theta(t-t')\\\\\n\\nonumber\n&=&\\int_{-\\infty}^\\infty dt'~F(t')G(t-t'),\\\\\n\\nonumber\nG(\\Delta t)&=&\\frac{e^{-\\beta\\Delta t}\\sin[\\omega' \\Delta t]}{m\\omega'}\\Theta(\\Delta t)\n\\end{eqnarray}\n$$\n\nThe quantity\n$e^{-\\beta(t-t')}\\sin[\\omega'(t-t')]/m\\omega'\\Theta(t-t')$ is called a\nGreen's function, $G(t-t')$. It describes the response at $t$ due to a\nforce applied at a time $t'$, and is a function of $t-t'$. The step\nfunction ensures that the response does not occur before the force is\napplied. One should remember that the form for $G$ would change if the\noscillator were either critically- or over-damped.\n\nWhen performing the integral in Eq. ([44](#eq:Greeny)) one can use\nangle addition formulas to factor out the part with the $t'$\ndependence in the integrand,\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:Greeny2} \\tag{45}\nx(t)&=&\\frac{1}{m\\omega'}e^{-\\beta t}\\left[I_c(t)\\sin(\\omega't)-I_s(t)\\cos(\\omega't)\\right],\\\\\n\\nonumber\nI_c(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\cos(\\omega't'),\\\\\n\\nonumber\nI_s(t)&\\equiv&\\int_{-\\infty}^t dt'~F(t')e^{\\beta t'}\\sin(\\omega't').\n\\end{eqnarray}\n$$\n\nIf the time $t$ is beyond any time at which the force acts,\n$F(t'>t)=0$, the coefficients $I_c$ and $I_s$ become independent of\n$t$.\n\n\nConsider an undamped oscillator ($\\beta\\rightarrow 0$), with\ncharacteristic frequency $\\omega_0$ and mass $m$, that is at rest\nuntil it feels a force described by a Gaussian form,\n\n$$\n\\begin{eqnarray*}\nF(t)&=&F_0 \\exp\\left\\{\\frac{-t^2}{2\\tau^2}\\right\\}.\n\\end{eqnarray*}\n$$\n\nFor large times ($t>>\\tau$), where the force has died off, find\n$x(t)$.\\\\ Solve for the coefficients $I_c$ and $I_s$ in\nEq. ([45](#eq:Greeny2)). Because the Gaussian is an even function,\n$I_s=0$, and one need only solve for $I_c$,\n\n$$\n\\begin{eqnarray*}\nI_c&=&F_0\\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}\\cos(\\omega_0 t')\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-t^{\\prime 2}/(2\\tau^2)}e^{i\\omega_0 t'}\\\\\n&=&\\Re F_0 \\int_{-\\infty}^\\infty dt'~e^{-(t'-i\\omega_0\\tau^2)^2/(2\\tau^2)}e^{-\\omega_0^2\\tau^2/2}\\\\\n&=&F_0\\tau \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}.\n\\end{eqnarray*}\n$$\n\nThe third step involved completing the square, and the final step used the fact that the integral\n\n$$\n\\begin{eqnarray*}\n\\int_{-\\infty}^\\infty dx~e^{-x^2/2}&=&\\sqrt{2\\pi}.\n\\end{eqnarray*}\n$$\n\nTo see that this integral is true, consider the square of the integral, which you can change to polar coordinates,\n\n$$\n\\begin{eqnarray*}\nI&=&\\int_{-\\infty}^\\infty dx~e^{-x^2/2}\\\\\nI^2&=&\\int_{-\\infty}^\\infty dxdy~e^{-(x^2+y^2)/2}\\\\\n&=&2\\pi\\int_0^\\infty rdr~e^{-r^2/2}\\\\\n&=&2\\pi.\n\\end{eqnarray*}\n$$\n\nFinally, the expression for $x$ from Eq. ([45](#eq:Greeny2)) is\n\n$$\n\\begin{eqnarray*}\nx(t>>\\tau)&=&\\frac{F_0\\tau}{m\\omega_0} \\sqrt{2\\pi} e^{-\\omega_0^2\\tau^2/2}\\sin(\\omega_0t).\n\\end{eqnarray*}\n$$\n\n## The classical pendulum and scaling the equations\n\nLet us end our discussion of oscillations with another classical case, the pendulum.\n\nThe angular equation of motion of the pendulum is given by\nNewton's equation and with no external force it reads\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+mgsin(\\theta)=0,\n\\label{_auto32} \\tag{46}\n\\end{equation}\n$$\n\nwith an angular velocity and acceleration given by\n\n\n
\n\n$$\n\\begin{equation}\n v=l\\frac{d\\theta}{dt},\n\\label{_auto33} \\tag{47}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\n a=l\\frac{d^2\\theta}{dt^2}.\n\\label{_auto34} \\tag{48}\n\\end{equation}\n$$\n\nWe do however expect that the motion will gradually come to an end due a viscous drag torque acting on the pendulum. \nIn the presence of the drag, the above equation becomes\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=0, \\label{eq:pend1} \\tag{49}\n\\end{equation}\n$$\n\nwhere $\\nu$ is now a positive constant parameterizing the viscosity\nof the medium in question. In order to maintain the motion against\nviscosity, it is necessary to add some external driving force. \nWe choose here a periodic driving force. The last equation becomes then\n\n\n
\n\n$$\n\\begin{equation}\n ml\\frac{d^2\\theta}{dt^2}+\\nu\\frac{d\\theta}{dt} +mgsin(\\theta)=Asin(\\omega t), \\label{eq:pend2} \\tag{50}\n\\end{equation}\n$$\n\nwith $A$ and $\\omega$ two constants representing the amplitude and \nthe angular frequency respectively. The latter is called the driving frequency.\n\n\n\nWe define\n\n$$\n\\omega_0=\\sqrt{g/l},\n$$\n\nthe so-called natural frequency and the new dimensionless quantities\n\n$$\n\\hat{t}=\\omega_0t,\n$$\n\nwith the dimensionless driving frequency\n\n$$\n\\hat{\\omega}=\\frac{\\omega}{\\omega_0},\n$$\n\nand introducing the quantity $Q$, called the *quality factor*,\n\n$$\nQ=\\frac{mg}{\\omega_0\\nu},\n$$\n\nand the dimensionless amplitude\n\n$$\n\\hat{A}=\\frac{A}{mg}\n$$\n\n## More on the Pendulum\n\nWe have\n\n$$\n\\frac{d^2\\theta}{d\\hat{t}^2}+\\frac{1}{Q}\\frac{d\\theta}{d\\hat{t}} \n +sin(\\theta)=\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThis equation can in turn be recast in terms of two coupled first-order differential equations as follows\n\n$$\n\\frac{d\\theta}{d\\hat{t}}=\\hat{v},\n$$\n\nand\n\n$$\n\\frac{d\\hat{v}}{d\\hat{t}}=-\\frac{\\hat{v}}{Q}-sin(\\theta)+\\hat{A}cos(\\hat{\\omega}\\hat{t}).\n$$\n\nThese are the equations to be solved. The factor $Q$ represents the\nnumber of oscillations of the undriven system that must occur before\nits energy is significantly reduced due to the viscous drag. The\namplitude $\\hat{A}$ is measured in units of the maximum possible\ngravitational torque while $\\hat{\\omega}$ is the angular frequency of\nthe external torque measured in units of the pendulum's natural\nfrequency.\n", "meta": {"hexsha": "eb444b3a58f88da78295929764963ab7ac512d80", "size": 165158, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/harmonic/ipynb/harmonic.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/pub/harmonic/ipynb/harmonic.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/pub/harmonic/ipynb/harmonic.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 56.8725895317, "max_line_length": 38544, "alphanum_fraction": 0.7428280798, "converted": true, "num_tokens": 17122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.1667839267851838}} {"text": "\n# PHY321: Classical Mechanics 1\n\n \n**Solution Homework 7, due to March 22**\n\nDate: **Mar 26, 2021**\n\n### Introduction to homework 7\n\nIn this week's homework we will apply our insights about harmonic\noscillations and link this with our activity from the lecture on\nFriday March 12. The relevant material to survey is chapter 5 of Taylor.\n\nWe have also added an exercise (exercise 2) related to our discussion of two-body problems. \nThe relevant reading background for exercise 2 is sections 8.1-8.2 of Taylor.\n\n\n\n### Exercise 1 (80 pt), particle/object in a harmonic oscillator potential\n\nIn the midterm and in exercise 4 of homework 6, we looked at an\nobject/particle moving in a potential which resulted in harmonic\noscillations. The aim here is to summarize in more detail the\nmaterial from harmonic oscillations. See also the bonus exercise below\nhere (from the discussions of Friday March 12).\n\n\nRelevant reading here is Taylor chapter 5 and the lecture notes on oscillations. \n\nWe will consider a particle of mass $m$ moving in a one-dimensional potential,\n\n$$\nV(x)=k\\frac{x^2}{2},\n$$\n\nwhere $k$ is a parameter.\n\nWe will limit ourselves to a one-dimensional system. You will need to select values for the initial conditions and the various parameters $k$, $m$, $b$, $\\omega$ and $F_0$ discussed here.\n\n* 1a (20pt) Assume no driving force first and add a drag force $-bv$, where $v$ is the velocity. Find the forces acting on the object. Find the analytical solutions to the equations of motion. Discuss the three cases: **underdamping**, **critical damping** and **overdamping**.\n\nThe text here is taken from the lecture notes of week 9. We have made this text more extensive than needed. This is done for the sake of completeness. We don't expect that you would provide this level of detail.\n\nWe consider only the case where the damping force is proportional to\nthe velocity. This is counter to dragging friction, where the force is\nproportional in strength to the normal force and independent of\nvelocity, and is also inconsistent with wind resistance, where the\nmagnitude of the drag force is proportional the square of the\nvelocity. Rolling resistance does seem to be mainly proportional to\nthe velocity. However, the main motivation for considering damping\nforces proportional to the velocity is that the math is more\nfriendly. This is because the differential equation is linear,\ni.e. each term is of order $x$, $\\dot{x}$, $\\ddot{x}\\cdots$, or even\nterms with no mention of $x$, and there are no terms such as $x^2$ or\n$x\\ddot{x}$. The equations of motion for a spring with damping force\n$-b\\dot{x}$ are\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nJust to make the solution a bit less messy, we rewrite this equation as\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:dampeddiffyq} \\tag{2}\n\\ddot{x}+2\\beta\\dot{x}+\\omega_0^2x=0,~~~~\\beta\\equiv b/2m,~\\omega_0\\equiv\\sqrt{k/m}.\n\\end{equation}\n$$\n\nBoth $\\beta$ and $\\omega$ have dimensions of inverse time. To find solutions (see appendix C in the text) you must make an educated guess at the form of the solution. To do this, first realize that the solution will need an arbitrary normalization $A$ because the equation is linear. Secondly, realize that if the form is\n\n\n
\n\n$$\n\\begin{equation}\nx=Ae^{rt}\n\\label{_auto2} \\tag{3}\n\\end{equation}\n$$\n\nthat each derivative simply brings out an extra power of $r$. This\nmeans that the $Ae^{rt}$ factors out and one can simply solve for an\nequation for $r$. Plugging this form into Eq. ([2](#eq:dampeddiffyq)),\n\n\n
\n\n$$\n\\begin{equation}\nr^2+2\\beta r+\\omega_0^2=0.\n\\label{_auto3} \\tag{4}\n\\end{equation}\n$$\n\nBecause this is a quadratic equation there will be two solutions,\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\beta\\pm\\sqrt{\\beta^2-\\omega_0^2}.\n\\label{_auto4} \\tag{5}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1t}+A_2e^{r_2t},\n\\label{_auto5} \\tag{6}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nThe roots listed above, $\\sqrt{\\omega_0^2-\\beta_0^2}$, will be\nimaginary if the damping is small and $\\beta<\\omega_0$. In that case,\n$r$ is complex and the factor $\\exp{(rt)}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. There are three cases:\n\n\n\n### Underdamped: $\\beta<\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1e^{-\\beta t}e^{i\\omega't}+A_2e^{-\\beta t}e^{-i\\omega't},~~\\omega'\\equiv\\sqrt{\\omega_0^2-\\beta^2}\\\\\n\\nonumber\n&=&(A_1+A_2)e^{-\\beta t}\\cos\\omega't+i(A_1-A_2)e^{-\\beta t}\\sin\\omega't.\n\\end{eqnarray}\n$$\n\nHere we have made use of the identity\n$e^{i\\omega't}=\\cos\\omega't+i\\sin\\omega't$. Because the constants are\narbitrary, and because the real and imaginary parts are both solutions\nindividually, we can simply consider the real part of the solution\nalone:\n\n\n
\n\n$$\n\\begin{eqnarray}\n\\label{eq:homogsolution} \\tag{7}\nx&=&B_1e^{-\\beta t}\\cos\\omega't+B_2e^{-\\beta t}\\sin\\omega't,\\\\\n\\nonumber \n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2}.\n\\end{eqnarray}\n$$\n\n### Critical dampling: $\\beta=\\omega_0$\n\nIn this case the two terms involving $r_1$ and $r_2$ are identical\nbecause $\\omega'=0$. Because we need to arbitrary constants, there\nneeds to be another solution. This is found by simply guessing, or by\ntaking the limit of $\\omega'\\rightarrow 0$ from the underdamped\nsolution. The solution is then\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:criticallydamped} \\tag{8}\nx=Ae^{-\\beta t}+Bte^{-\\beta t}.\n\\end{equation}\n$$\n\nThe critically damped solution is interesting because the solution\napproaches zero quickly, but does not oscillate. For a problem with\nzero initial velocity, the solution never crosses zero. This is a good\nchoice for designing shock absorbers or swinging doors.\n\n\n### Overdamped: $\\beta>\\omega_0$\n\n$$\n\\begin{eqnarray}\nx&=&A_1\\exp{-(\\beta+\\sqrt{\\beta^2-\\omega_0^2})t}+A_2\\exp{-(\\beta-\\sqrt{\\beta^2-\\omega_0^2})t}\n\\end{eqnarray}\n$$\n\nThis solution will also never pass the origin more than once, and then\nonly if the initial velocity is strong and initially toward zero.\n\n\n\n\nGiven $b$, $m$ and $\\omega_0$, find $x(t)$ for a particle whose\ninitial position is $x=0$ and has initial velocity $v_0$ (assuming an\nunderdamped solution).\n\nThe solution is of the form,\n\n$$\n\\begin{eqnarray*}\nx&=&e^{-\\beta t}\\left[A_1\\cos(\\omega' t)+A_2\\sin\\omega't\\right],\\\\\n\\dot{x}&=&-\\beta x+\\omega'e^{-\\beta t}\\left[-A_1\\sin\\omega't+A_2\\cos\\omega't\\right].\\\\\n\\omega'&\\equiv&\\sqrt{\\omega_0^2-\\beta^2},~~~\\beta\\equiv b/2m.\n\\end{eqnarray*}\n$$\n\nFrom the initial conditions, $A_1=0$ because $x(0)=0$ and $\\omega'A_2=v_0$. So\n\n$$\nx=\\frac{v_0}{\\omega'}e^{-\\beta t}\\sin\\omega't.\n$$\n\n* 1b (5pt) Scale your equations of motion in terms of a dimensionless time $\\tau = \\omega_0 t$, where $t$ is time and $\\omega_0^2=k/m$ is the so-called natural frequency. \n\nTo scale the equations we start again with the full equation\n\n\n
\n\n$$\n\\begin{equation}\nm\\ddot{x}+b\\dot{x}+kx=0.\n\\label{_auto6} \\tag{9}\n\\end{equation}\n$$\n\nWe divide by $m$ and get\n\n\n
\n\n$$\n\\begin{equation}\n\\ddot{x}+\\frac{b}{m}\\dot{x}+\\frac{k}{m}x=0.\n\\label{_auto7} \\tag{10}\n\\end{equation}\n$$\n\nDefining the natural frequency $\\omega_0^2=k/m$ we introduce a dimensionless time $\\tau = \\omega_0 t$ and replace $t$ with $\\tau$.\nThis leads to us rewriting\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2 x}{dt^2}+\\frac{b}{m}\\frac{dx}{dt}+\\frac{k}{m}x=0,\n\\label{_auto8} \\tag{11}\n\\end{equation}\n$$\n\nas\n\n\n
\n\n$$\n\\begin{equation}\n\\omega_0^2\\frac{d^2 x}{d\\tau^2}+\\frac{\\omega_0b}{m}\\frac{dx}{d\\tau}+\\omega_0^2x=0,\n\\label{_auto9} \\tag{12}\n\\end{equation}\n$$\n\nand dividing by $\\omega_0^2$ and defining $\\gamma = b/(2m\\omega_0)$ we have the final scaled equation\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2 x}{d\\tau^2}+2\\gamma\\frac{dx}{d\\tau}+x=0.\n\\label{_auto10} \\tag{13}\n\\end{equation}\n$$\n\nThis equation has dimension length only and time $\\tau$ is dimensionless. It means also that our solutions become now\n\nIn this case the variable $r$ becomes\n\n\n
\n\n$$\n\\begin{equation}\nr=-\\gamma\\pm\\sqrt{\\gamma^2-1}.\n\\label{_auto11} \\tag{14}\n\\end{equation}\n$$\n\nWe refer to the two solutions as $r_1$ and $r_2$ corresponding to the\n$+$ and $-$ roots. As expected, there should be two arbitrary\nconstants involved in the solution,\n\n\n
\n\n$$\n\\begin{equation}\nx=A_1e^{r_1\\tau}+A_2e^{r_2\\tau},\n\\label{_auto12} \\tag{15}\n\\end{equation}\n$$\n\nwhere the coefficients $A_1$ and $A_2$ are determined by initial\nconditions.\n\nFor the roots listed above, $\\sqrt{\\gamma^2-1}$, will be\nimaginary if the damping is small and $\\gamma < 1$. In that case,\n$r$ is complex and the factor $\\exp{(rt)}$ will have some oscillatory\nbehavior. If the roots are real, there will only be exponentially\ndecaying solutions. For $\\gamma =1$, we have what we labeled as critical damping while for $\\gamma > 1$, we have over-critical damping.\n\nIn the codes below, we have implemented the dimensionless equations.\n\n\n\n* 1c (25pt) You can use your codes from either the first midterm or from homeworks 5 and/or 6. Study numerically the three cases from 1a, that is the underdamped motion, the critically damped one and finally the overdamped one. Compare your numerical results with the analytical ones from 1a. Discuss your results. You can use the Euler-Cromer method, or the Velocity-Verlet method or the Runge-Kutta methods discussed during the lectures, see for example . Alternatively, you could use the **odeint** solvers included functionality in Python, see . Give a short argument about the numerical algorithm you ended up using. \n\nWe have chosen to implement the Runge-Kutta4 method since this has a\ntruncation error in terms of the step size $\\Delta t$ to the power of\nfive. The codes are included after part 1d.\n\n\n\n* 1d (30pt) We add now a driving force $F=F_0\\cos{(\\omega t}$. Find the particular solution and its analytical solution. Include this force in your code (remember to scale the equations) and compare your numerical results with the analytical results. Discuss your results. How does the system evolve over time with a given frequency $\\omega$ for the driving force? Is energy conserved? If not, why? \n\nTo find a particular solution, one first guesses at the form,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:partform} \\tag{16}\nx_p(t)=D\\cos(\\omega t-\\delta),\n\\end{equation}\n$$\n\nand rewrite the differential equation as\n\n\n
\n\n$$\n\\begin{equation}\nD\\left\\{-\\omega^2\\cos(\\omega t-\\delta)-2\\beta\\omega\\sin(\\omega t-\\delta)+\\omega_0^2\\cos(\\omega t-\\delta)\\right\\}=\\frac{F_0}{m}\\cos(\\omega t).\n\\label{_auto13} \\tag{17}\n\\end{equation}\n$$\n\nOne can now use angle addition formulas to get\n\n$$\n\\begin{eqnarray}\nD\\left\\{(-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta)\\cos(\\omega t)\\right.&&\\\\\n\\nonumber\n\\left.+(-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta)\\sin(\\omega t)\\right\\}\n&=&\\frac{F_0}{m}\\cos(\\omega t).\n\\end{eqnarray}\n$$\n\nBoth the $\\cos$ and $\\sin$ terms need to equate if the expression is to hold at all times. Thus, this becomes two equations\n\n$$\n\\begin{eqnarray}\nD\\left\\{-\\omega^2\\cos\\delta+2\\beta\\omega\\sin\\delta+\\omega_0^2\\cos\\delta\\right\\}&=&\\frac{F_0}{m}\\\\\n\\nonumber\n-\\omega^2\\sin\\delta-2\\beta\\omega\\cos\\delta+\\omega_0^2\\sin\\delta&=&0.\n\\end{eqnarray}\n$$\n\nAfter dividing by $\\cos\\delta$, the lower expression leads to\n\n\n
\n\n$$\n\\begin{equation}\n\\tan\\delta=\\frac{2\\beta\\omega}{\\omega_0^2-\\omega^2}.\n\\label{_auto14} \\tag{18}\n\\end{equation}\n$$\n\nUsing the identities $\\tan^2+1=\\csc^2$ and $\\sin^2+\\cos^2=1$, one can also express $\\sin\\delta$ and $\\cos\\delta$,\n\n$$\n\\begin{eqnarray}\n\\sin\\delta&=&\\frac{2\\beta\\omega}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}},\\\\\n\\nonumber\n\\cos\\delta&=&\\frac{(\\omega_0^2-\\omega^2)}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}\n\\end{eqnarray}\n$$\n\nInserting the expressions for $\\cos\\delta$ and $\\sin\\delta$ into the expression for $D$,\n\n\n
\n\n$$\n\\begin{equation}\n\\label{eq:Ddrive} \\tag{19}\nD=\\frac{F_0/m}{\\sqrt{(\\omega_0^2-\\omega^2)^2+4\\omega^2\\beta^2}}.\n\\end{equation}\n$$\n\nFor a given initial condition, e.g. initial displacement and velocity,\none must add the homogenous solution then solve for the two arbitrary\nconstants. However, because the homogenous solutions decay with time\nas $e^{-\\beta t}$, the particular solution is all that remains at\nlarge times, and is therefore the steady state solution. Because the\narbitrary constants are all in the homogenous solution, all memory of\nthe initial conditions are lost at large times, $t>>1/\\beta$.\n\nThe amplitude of the motion, $D$, is linearly proportional to the\ndriving force ($F_0/m$), but also depends on the driving frequency\n$\\omega$. For small $\\beta$ the maximum will occur at\n$\\omega=\\omega_0$. This is referred to as a resonance. In the limit\n$\\beta\\rightarrow 0$ the amplitude at resonance approaches infinity.\n\n\n\n\nLet us now for simplicty assume that our external force is given by\n\n$$\nF_{\\mathrm{ext}}(t) = F_0\\cos{(\\omega t)},\n$$\n\nwhere $F_0$ is a constant (what is its dimension?) and $\\omega$ is the frequency of the applied external driving force.\n\n\nIntroducing the external force into our lovely differential equation\nand dividing by $m$ and introducing $\\omega_0^2=\\sqrt{k/m}$ we have\n\n$$\n\\frac{d^2x}{dt^2} + \\frac{b}{m}\\frac{dx}{dt}+\\omega_0^2x(t) =\\frac{F_0}{m}\\cos{(\\omega t)},\n$$\n\nThereafter we introduce a dimensionless time $\\tau = t\\omega_0$\nand a dimensionless frequency $\\tilde{\\omega}=\\omega/\\omega_0$. We have then\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\frac{F_0}{m\\omega_0^2}\\cos{(\\tilde{\\omega}\\tau)},\n$$\n\nIntroducing a new amplitude $\\tilde{F} =F_0/(m\\omega_0^2)$ (check dimensionality again) we have\n\n$$\n\\frac{d^2x}{d\\tau^2} + \\frac{b}{m\\omega_0}\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nOur final step, as we did in the case of various types of damping, is\nto define $\\gamma = b/(2m\\omega_0)$ and rewrite our equations as\n\n$$\n\\frac{d^2x}{d\\tau^2} + 2\\gamma\\frac{dx}{d\\tau}+x(\\tau) =\\tilde{F}\\cos{(\\tilde{\\omega}\\tau)}.\n$$\n\nThese are the equations implemented in the codes below. In the code example below we have chosen the initial position to be\n$x_0=1.0$ (skipping the units), the initial velocity $v_0=0$, $k=m=1$ giving $\\omega_0 =1.0$ and $\\gamma=1.0$, $\\tilde{\\omega}=0.0$ and $\\tilde{F_0}=0.0$.\nThese definitions gives us for the homogenous solution a classical critical case since $\\gamma = 1$, resulting in the homogenous solution only (show this with the given initial conditions))\n\n$$\nx_h(\\tau)=x_0(\\exp{-(\\tau)}+\\tau\\exp{-(\\tau)}).\n$$\n\nEnergy is not conserved since we have a time and velocity dependent total net force acting on the system.\n\nNote that here the forward Euler method does not know the specific force function to be called.\nIt receives just an input the name. We can easily change the force by adding another function.\n\n\n```python\ndef ForwardEuler(v,x,t,n,Force):\n for i in range(n-1):\n v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n```\n\n\n```python\ndef SpringForce(v,x,t):\n# note here that we have divided by mass and we return the acceleration\n return -2*gamma*v-x+Ftilde*cos(t*Omegatilde)\n```\n\nIt is easy to add a new method like the Euler-Cromer\n\n\n```python\ndef ForwardEulerCromer(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n v[i+1] = v[i] + DeltaT*a\n x[i+1] = x[i] + DeltaT*v[i+1]\n t[i+1] = t[i] + DeltaT\n```\n\nand the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces))\n\n\n```python\ndef VelocityVerlet(v,x,t,n,Force):\n for i in range(n-1):\n a = Force(v[i],x[i],t[i])\n x[i+1] = x[i] + DeltaT*v[i]+0.5*a*DeltaT*DeltaT\n anew = Force(v[i],x[i+1],t[i+1])\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK2(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Final result\n x[i+1] = x[i]+k2x\n v[i+1] = v[i]+k2v\n\tt[i+1] = t[i]+DeltaT\n```\n\nFinally, we can now add the Runge-Kutta2 method via a new function\n\n\n```python\ndef RK4(v,x,t,n,Force):\n for i in range(n-1):\n# Setting up k1\n k1x = DeltaT*v[i]\n k1v = DeltaT*Force(v[i],x[i],t[i])\n# Setting up k2\n vv = v[i]+k1v*0.5\n xx = x[i]+k1x*0.5\n k2x = DeltaT*vv\n k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k3\n vv = v[i]+k2v*0.5\n xx = x[i]+k2x*0.5\n k3x = DeltaT*vv\n k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5)\n# Setting up k4\n vv = v[i]+k3v\n xx = x[i]+k3x\n k4x = DeltaT*vv\n k4v = DeltaT*Force(vv,xx,t[i]+DeltaT)\n# Final result\n x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6.\n v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6.\n t[i+1] = t[i] + DeltaT\n```\n\nThe code below uses the Runge-Kutta4 methods.\n\n\n```python\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 20 # in dimensionless time\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, v, and x\nt = np.zeros(n)\nv = np.zeros(n)\nx = np.zeros(n)\n# Initial conditions (can change to more than one dim)\nx0 = 1.0 \nv0 = 0.0\nx[0] = x0\nv[0] = v0\ngamma = 1.0\nOmegatilde = 0.0\nFtilde = 0.0\n# Start integrating using Euler's method\n# Note that we define the force function as a SpringForce\nRK4(v,x,t,n,SpringForce)\n# Here we define the analytical solution for the critical damping case\nxanalytic = np.zeros(n)\nxanalytic = x0*np.exp(-t)+x0*t*np.exp(-t)\n\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('x[m]')\nax.set_xlabel('t[s]')\nax.plot(t, np.abs(x-xanalytic))\nfig.tight_layout()\nsave_fig(\"ForcedBlockRK4\")\nplt.show()\n```\n\nHere we have plotted the difference (absolute value) between the analytical solution and numerical one and we see that the error is extremely small with the chosen parameters. Feel free to explore other situations.\n\n\n\n\n\n\n\n\n### Exercise 2 (20pt), Center-of-Mass and Relative Coordinates and Reference Frames\n\nWe define the two-body center-of-mass coordinate and relative coordinate by expressing the trajectories for\n$\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ into the center-of-mass coordinate\n$\\boldsymbol{R}_{\\rm cm}$\n\n$$\n\\boldsymbol{R}_{\\rm cm}\\equiv\\frac{m_1\\boldsymbol{r}_1+m_2\\boldsymbol{r}_2}{m_1+m_2},\n$$\n\nand the relative coordinate\n\n$$\n\\boldsymbol{r}\\equiv\\boldsymbol{r}_1-\\boldsymbol{r_2}.\n$$\n\nHere, we assume the two particles interact only with one another, so $\\boldsymbol{F}_{12}=-\\boldsymbol{F}_{21}$ (where $\\boldsymbol{F}_{ij}$ is the force on $i$ due to $j$.\n\n* 2a (5pt) Show that the equations of motion then become $\\ddot{\\boldsymbol{R}}_{\\rm cm}=0$ and $\\mu\\ddot{\\boldsymbol{r}}=\\boldsymbol{F}_{12}$, with the reduced mass $\\mu=m_1m_2/(m_1+m_2)$.\n\nThe first expression simply states that the center of mass coordinate $\\boldsymbol{R}_{\\rm cm}$ moves at a fixed velocity. The second expression can be rewritten in terms of the reduced mass $\\mu$.\n\nLet us first start with some basic definitions. We have the center of mass coordinate $\\boldsymbol{R}$ defined as (for two particles)\n\n$$\n\\boldsymbol{R}=\\frac{m_1\\boldsymbol{r}_1+m_2\\boldsymbol{r}_2}{M},\n$$\n\nwhere $m_1$ and $m_2$ are the masses of the two objects and $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ their respective positions defined according to a chosen origin. Here $M=m_1+m_2$ is the total mass.\n\nThe relative position is defined as\n\n$$\n\\boldsymbol{r} =\\boldsymbol{r}_1-\\boldsymbol{r}_2,\n$$\n\nand we then define $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ in terms of the relative and center of mass positions as\n\n$$\n\\boldsymbol{r}_1=\\boldsymbol{R}+\\frac{m_2}{M}\\boldsymbol{r},\n$$\n\nand\n\n$$\n\\boldsymbol{r}_2=\\boldsymbol{R}-\\frac{m_1}{M}\\boldsymbol{r},\n$$\n\nThe total linear momentum is then defined as\n\n$$\n\\boldsymbol{P}=\\sum_{i=1}^Nm_i\\frac{\\boldsymbol{r}_i}{dt},\n$$\n\nwhere $N=2$ in our case. With the above definition of the center of mass position, we see that we can rewrite the total linear momentum as (multiplying the center of mass position with $M$)\n\n$$\n\\boldsymbol{P}=M\\frac{d\\boldsymbol{R}}{dt}=M\\dot{\\boldsymbol{R}}.\n$$\n\nThis result is also an answer to a part of exercise 2b, see below.\n\nThe net force acting on the system is given by the time derivative of the linear momentum (assuming mass is time independent)\nand we have\n\n$$\n\\boldsymbol{F}^{\\mathrm{net}}=\\dot{\\boldsymbol{P}}=M\\ddot{\\boldsymbol{R}}.\n$$\n\nThe net force acting on the system is given by the sum of the forces acting on the two object, that is we have\n\n$$\n\\boldsymbol{F}^{\\mathrm{net}}=\\boldsymbol{F}_1+\\boldsymbol{F}_2=\\dot{\\boldsymbol{P}}=M\\ddot{\\boldsymbol{R}}.\n$$\n\nIn our case the forces are given by the internal forces only. The force acting on object $1$ is thus $\\boldsymbol{F}_{12}$ and the one acting on object $2$ is $\\boldsymbol{F}_{12}$. We have also defined that $\\boldsymbol{F}_{12}=-\\boldsymbol{F}_{21}$. This means thar we have\n\n$$\n\\boldsymbol{F}_1+\\boldsymbol{F}_2=\\boldsymbol{F}_{12}+\\boldsymbol{F}_{21}=0=\\dot{\\boldsymbol{P}}=M\\ddot{\\boldsymbol{R}},\n$$\n\nwhich is what we wanted to show. The center of mass velocity is thus a constant of the motion. We could also define the so-called center of mass reference frame where we simply set $\\boldsymbol{R}=0$.\n\nThis has also another important consequence for our forces. If we assume that our force depends only on the positions, it means that the gradient of the potential with respect to the center of mass position is zero, that is\n\n$$\nM\\ddot{d\\boldsymbol{R}}=-\\boldsymbol{\\nabla}_{\\boldsymbol{R}}V =0!\n$$\n\nAn alternative way is\n\n$$\n\\begin{eqnarray}\n\\ddot{\\boldsymbol{R}}_{\\rm cm}&=&\\frac{1}{m_1+m_2}\\left\\{m_1\\ddot{\\boldsymbol{r}}_1+m_2\\ddot{\\boldsymbol{r}}_2\\right\\}\\\\\n\\nonumber\n&=&\\frac{1}{m_1+m_2}\\left\\{\\boldsymbol{F}_{12}+\\boldsymbol{F}_{21}\\right\\}=0.\\\\\n\\ddot{\\boldsymbol{r}}&=&\\ddot{\\boldsymbol{r}}_1-\\ddot{\\boldsymbol{r}}_2=\\left(\\frac{\\boldsymbol{F}_{12}}{m_1}-\\frac{\\boldsymbol{F}_{21}}{m_2}\\right)\\\\\n\\nonumber\n&=&\\left(\\frac{1}{m_1}+\\frac{1}{m_2}\\right)\\boldsymbol{F}_{12}.\n\\end{eqnarray}\n$$\n\nThe first expression simply states that the center of mass coordinate\n$\\boldsymbol{R}_{\\rm cm}$ moves at a fixed velocity. The second expression\ncan be rewritten in terms of the reduced mass $\\mu$.\n\n$$\n\\begin{eqnarray}\n\\mu \\ddot{\\boldsymbol{r}}&=&\\boldsymbol{F}_{12},\\\\\n\\frac{1}{\\mu}&=&\\frac{1}{m_1}+\\frac{1}{m_2},~~~~\\mu=\\frac{m_1m_2}{m_1+m_2}.\n\\end{eqnarray}\n$$\n\nThus, one can treat the trajectory as a one-body problem where the\nreduced mass is $\\mu$, and a second trivial problem for the center of\nmass. The reduced mass is especially convenient when one is\nconsidering gravitational problems, as we have seen during the lectures of weeks 11-13.\n\n\n\n\n* 2b (5pt) Show that the linear momenta for the center-of-mass $\\boldsymbol{P}$ motion and the relative motion $\\boldsymbol{q}$ are given by $\\boldsymbol{P}=M\\dot{\\boldsymbol{R}}_{\\rm cm}$ with $M=m_1+m_2$ and $\\boldsymbol{q}=\\mu\\dot{\\boldsymbol{r}}$. The linear momentum of the relative motion is defined $\\boldsymbol{q} = (m_2\\boldsymbol{p}_1-m_1\\boldsymbol{p}_2)/(m_1+m_2)$.\n\nIn 2a we showed, as an intermediate step that the total linear momentum is given by\n\n$$\n\\boldsymbol{P}=\\sum_{i=1}^Nm_i\\frac{d\\boldsymbol{r}_i}{dt}=M\\dot{\\boldsymbol{R}}.\n$$\n\nFor the relative momentum $\\boldsymbol{q}$, we have that the time derivative of $\\boldsymbol{r}$ is\n\n$$\n\\dot{\\boldsymbol{r}} =\\dot{\\boldsymbol{r}}_1-\\dot{\\boldsymbol{r}}_2,\n$$\n\nWe now also that the momenta $\\boldsymbol{p}_1=m_1\\dot{\\boldsymbol{r}}_1$ and\n$\\boldsymbol{p}_2=m_2\\dot{\\boldsymbol{r}}_2$. Using these expressions we can rewrite\n\n$$\n\\dot{\\boldsymbol{r}} =\\frac{\\boldsymbol{p}_1}{m_1}-\\frac{\\boldsymbol{p}_2}{m_2},\n$$\n\nwhich we can rewrite as\n\n$$\n\\dot{\\boldsymbol{r}} =\\frac{m_2\\boldsymbol{p}_1-m_1\\boldsymbol{p}_2}{m_1m_2},\n$$\n\nand dividing both sides with $M$ we have\n\n$$\n\\frac{m_1m_2}{M}\\dot{\\boldsymbol{r}} =\\frac{m_2\\boldsymbol{p}_1-m_1\\boldsymbol{p}_2}{M}.\n$$\n\nIntroducing the reduced mass $\\mu=m_1m_2/M$ we have finally\n\n$$\n\\mu\\dot{\\boldsymbol{r}} =\\frac{m_2\\boldsymbol{p}_1-m_1\\boldsymbol{p}_2}{M}.\n$$\n\nAnd $\\mu\\dot{\\boldsymbol{r}}$ defines the relative momentum $\\boldsymbol{q}=\\mu\\dot{\\boldsymbol{r}}$. \n\nWhen we introduce the Lagrangian formalism we will see that it is much easier to derive these equations.\n\n* 2c (5pt) Show then that the kinetic energy for two objects can then be written as\n\n$$\nK=\\frac{P^2}{2M}+\\frac{q^2}{2\\mu}.\n$$\n\nHere we just need to use our definitions of kinetic energy in terms of the coordinates $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$.\n\nWe have that\n\n$$\nK=\\frac{p_1^2}{2m_1}+\\frac{p_2^2}{2m_2},\n$$\n\nand with $\\boldsymbol{p}_1=m_1\\dot{\\boldsymbol{r}}_1$ and $\\boldsymbol{p}_2=m_2\\dot{\\boldsymbol{r}}_2$ and using\n\n$$\n\\dot{\\boldsymbol{r}}_1=\\dot{\\boldsymbol{R}}+\\frac{m_2}{M}\\dot{\\boldsymbol{r}},\n$$\n\nand\n\n$$\n\\dot{\\boldsymbol{r}}_2=\\dot{\\boldsymbol{R}}-\\frac{m_1}{M}\\dot{\\boldsymbol{r}},\n$$\n\nwe obtain (after squaring the expressions for $\\dot{\\boldsymbol{r}}_1$ and $\\dot{\\boldsymbol{r}}_2$) we have\n\n$$\nK=\\frac{(m_1+m_2)\\dot{\\boldsymbol{R}}^2}{2}+\\frac{(m_1+m_2)m_1m_2\\dot{\\boldsymbol{r}}^2}{2M^2},\n$$\n\nwhich we simplify to\n\n$$\nK=\\frac{\\dot{\\boldsymbol{P}}^2}{2M}+\\frac{\\mu\\dot{\\boldsymbol{q}}^2}{2},\n$$\n\nwhich is what we wanted to show.\n\n* 2d (5pt) Show that the total angular momentum for two-particles in the center-of-mass frame $\\boldsymbol{R}=0$, is given by\n\n$$\n\\boldsymbol{L}=\\boldsymbol{r}\\times \\mu\\dot{\\boldsymbol{r}}.\n$$\n\nHere we need again that\n\n$$\n\\boldsymbol{r} =\\boldsymbol{r}_1-\\boldsymbol{r}_2,\n$$\n\nand we then define $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ in terms of the relative and center of mass positions with $\\boldsymbol{R}=0$\n\n$$\n\\boldsymbol{r}_1=\\frac{m_2}{M}\\boldsymbol{r},\n$$\n\nand\n\n$$\n\\boldsymbol{r}_2=-\\frac{m_1}{M}\\boldsymbol{r},\n$$\n\nThe angular momentum (the total one) is the sum of the individual angular momenta (see homework 4) and we have\n\n$$\n\\boldsymbol{L} = \\boldsymbol{r}_1 \\times \\boldsymbol{p}_1+\\boldsymbol{r}_2 \\times \\boldsymbol{p}_2,\n$$\n\nand using that $m_1\\dot{\\boldsymbol{r}}_1=\\boldsymbol{p}_1$ and $m_2\\dot{\\boldsymbol{r}}_2=\\boldsymbol{p}_2$ we have\n\n$$\n\\boldsymbol{L} = m_1\\boldsymbol{r}_1 \\times \\dot{\\boldsymbol{r}}_1+m_2\\boldsymbol{r}_2 \\times \\dot{\\boldsymbol{r}}_2.\n$$\n\nInserting the equations for $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$ in terms of the relative motion, we have\n\n$$\n\\boldsymbol{L} = m_1 \\frac{m_2}{M}\\boldsymbol{r}\\times\\frac{m_2}{M}\\boldsymbol{r} +m_2 \\frac{m_1}{M}\\boldsymbol{r} \\times \\frac{m_1}{M}\\dot{\\boldsymbol{r}}.\n$$\n\nWe see that can rewrite this equation as\n\n$$\n\\boldsymbol{L}=\\boldsymbol{r}\\times \\mu\\dot{\\boldsymbol{r}},\n$$\n\nwhich is what we wanted to derive.\n", "meta": {"hexsha": "5746b273b4e4b1d782e3d38f8f970120ee4a20ec", "size": 64407, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/src/Homeworks/Solutions/solutionhw7.ipynb", "max_stars_repo_name": "mhjensen/Physics321", "max_stars_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/src/Homeworks/Solutions/solutionhw7.ipynb", "max_issues_repo_name": "mhjensen/Physics321", "max_issues_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/src/Homeworks/Solutions/solutionhw7.ipynb", "max_forks_repo_name": "mhjensen/Physics321", "max_forks_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 38.0431187242, "max_line_length": 15760, "alphanum_fraction": 0.6446659525, "converted": true, "num_tokens": 9478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017820478897, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.16647996281030844}} {"text": "# **Bienvenidos al taller introducción a Python!!**\n\n## **Sesion 1: Ejecutar y Salir**\n\nJupyter mezcla código y texto en diferentes tipos de bloques,llamados celdas.Hay dos tipos principales de celdas/\n\n**Celdas de Texto**\nLas entradas están escritas en markdown y pueden contener texto formateado, imágenes, ecuaciones y más. Las salidas se representan en lugar de la entrada cuando se ejecuta la celda.\n\n**Celdas de código**\nLas entradas contienen código Python.\nLassalidas se colocan debajo de la celda de entrada y contienen los resultados generados cuando se ejecuta el código de entrada.\n\n\n## CELDAS DE TEXTO\n\n# Markdown\n\nUn formato de texto plano simple para escribir listas, seleccionar enlaces, y otras cosas que pueden ir en una página web.\n\nPermite escribir reportes científicos rápidamente al igual que ecuaciones matemáticas de cualquier complejidad, imágenes, tablas\n\n## Formatación\n\n### **Negrita**, *Italica*; __Markdown__, _Markdown_\n\npráctica: escribe tu nombre con negrita\n\n\n# **TITULOS**\n\n# Heading 1\n## Heading 2\n### Heading 3\nHeading\n\npráctica: escribe tu nombre en heading 2\n\n\n\n## Creando Listas Markdown:\n\n* Item A\n 1. Subitem\n 2. Subitem\n* Item B\n - Subitem\n - Subitem\n\n\n### Otro ejemplo:\n1. Fruta\n * Manzana\n * Naranja\n * Banana\n2. Lacteos\n * Leche\n * Queso\n\npráctica: crea la siguiente lista 1. Obtener fondos. 2. Hacer el trabajo. *Diseñar *Recolectar *Analizar 3.Escribir 4. Publicar\n\n## Enlaces\n\nLos saltos de línea\nno importan.\n\nPero líneas en blanco\ncrean párrafos nuevos.\nLos saltos de línea no importan.\n\nPero líneas en blanco crean párrafos nuevos.\n\n[Crea enlaces](http://software-carpentry.org) con `[...](...)`.\nO usa el [nombre del enlace][Open_Science_Labs].\n\n[Open_Science_Labs]: https://opensciencelabs.org/\n\npráctica: crea un enlace, haz clik aqui\n\n\n## Insertar Imágenes:\n\n\n```python\n# \n```\n\n\n\n\n## Ecuaciones\n\nMarkdown estándar (como el que estamos usando para estas notas) no mostrará ecuaciones, pero el Cuaderno lo hará. \n\nLas ecuaciones en Markdown funcionan bajo marcaciones **Latex.** Para insertar una, basta con agregar un signo pesos al principio y al final de la ecuación. \n\n$x =$\n$4* cos(x)*$\n$43 x^3+x^2-2$\n$4* x * cos(x)* tan(x)$\n$*\\pi$ \n\n$\\sum_{i=1}^{N} 2^{-i} \\approx 1$\n(Probablemente sea más fácil copiar y pegar.) ¿Qué muestra? ¿Qué piensas que hace el subguión, _, circunflejo, ^, y el signo de dólar, $?\n\n\nEl cuaderno muestra la ecuación tal como se representaría a partir de la sintaxis de ecuación de LaTeX. El signo de dólar, $, se usa para indicarle a Markdown que el texto intermedio es una ecuación de LaTeX. Si no está familiarizado con LaTeX, el guion bajo, _, se usa para subíndices y el circunflejo, ^ , se usa para superíndices. Se usa un par de llaves, { y }, para agrupar el texto de manera que la declaracióni=1 se convierta en el subíndice y N se convierta en el superíndice. Similarmente, -i está entre llaves para hacer que toda la declaración sea el superíndice de 2. \\sum y \\approx son comandos LaTeX para símbolos de “suma” y “aproximado”.\n\n**Otros ejemplos**\n\n$\\begin{equation}\n\\sqrt{y\\,a} = \\sqrt[n]{b}\n\\end{equation}$\n\nAlgo más complicado\n\n $\n \\mathbf{V}_1 \\times \\mathbf{V}_2 = \\begin{vmatrix}\n \\mathbf{i} & \\mathbf{j} & \\mathbf{k} \\\\\n \\frac{\\partial X}{\\partial u} & \\frac{\\partial Y}{\\partial u} & 0 \\\\\n \\frac{\\partial X}{\\partial v} & \\frac{\\partial Y}{\\partial v} & 0\n \\end{vmatrix}\n $\n\nLímites:\n \n$\\begin{equation}\n\\lim_{x \\to \\infty} \\frac{\\sin(x)}{x} = 0\n\\end{equation}$\n\n# Puntos Clave\n\n* Los scripts de Python son archivos de texto plano.\n\n* Usa un cuaderno Juypiter Lab para editar y correr Python.\n\n* El Cuaderno tiene celdas de Comandos y Edición.\n\n* Usa el teclado y el ratón para seleccionar y editar celdas.\n\n* El Cuaderno convertirá Markdown en texto con formato.\n\n# Buen trabajo!!! \n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "0cff6f7663f2ae42e257560699471686886d3459", "size": 10077, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "sesion1.ipynb", "max_stars_repo_name": "Jud18/training-python-novice", "max_stars_repo_head_hexsha": "7bc3c342583ed4c67ce25bc5e4accf00a4b92ddb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-21T22:43:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T22:43:24.000Z", "max_issues_repo_path": "sesion1.ipynb", "max_issues_repo_name": "Jud18/training-python-novice", "max_issues_repo_head_hexsha": "7bc3c342583ed4c67ce25bc5e4accf00a4b92ddb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sesion1.ipynb", "max_forks_repo_name": "Jud18/training-python-novice", "max_forks_repo_head_hexsha": "7bc3c342583ed4c67ce25bc5e4accf00a4b92ddb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2021-08-21T22:11:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T03:16:06.000Z", "avg_line_length": 25.2556390977, "max_line_length": 661, "alphanum_fraction": 0.5649498859, "converted": true, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.16591072003244103}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n#####Version 0.1\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n####Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\" )\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to } )\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load( open(\"../styles/bmh_matplotlibrc.json\") )\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials) / 2, 2, k + 1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials) - 1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2 * p / (1 + p), color=\"#348ABD\", lw=3)\n# plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2 * (0.2) / 1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\")\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1. / 3, 2. / 3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0 + 0.25, .7 + 0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n##Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n###Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\")\n```\n\n###Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1. / l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1. / l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0, 1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n###But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC\n-----\n\nPyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.\n\nWe will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables:\n\n\n```\nimport pymc as pm\n\nalpha = 1.0 / count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\nlambda_1 = pm.Exponential(\"lambda_1\", alpha)\nlambda_2 = pm.Exponential(\"lambda_2\", alpha)\n\ntau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data)\n```\n\nIn the code above, we create the PyMC variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.\n\n\n```\nprint \"Random output:\", tau.random(), tau.random(), tau.random()\n```\n\n\n```\n@pm.deterministic\ndef lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):\n out = np.zeros(n_count_data)\n out[:tau] = lambda_1 # lambda before tau is lambda1\n out[tau:] = lambda_2 # lambda after (and including) tau is lambda2\n return out\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n`@pm.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well. \n\n\n```\nobservation = pm.Poisson(\"obs\", lambda_, value=count_data, observed=True)\n\nmodel = pm.Model([observation, lambda_1, lambda_2, tau])\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.\n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```\n# Mysterious code to be explained in Chapter 3.\nmcmc = pm.MCMC(model)\nmcmc.sample(40000, 10000, 1)\n```\n\n\n```\nlambda_1_samples = mcmc.trace('lambda_1')[:]\nlambda_2_samples = mcmc.trace('lambda_2')[:]\ntau_samples = mcmc.trace('tau')[:]\n```\n\n\n```\nfigsize(12.5, 10)\n# histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data) - 20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n###Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```\n# type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```\n# type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)\n\n\n```\n# type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010. \nPyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical \nSoftware, 35(4), pp. 1-81. \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```\nfrom IPython.core.display import HTML\n\n\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```\n\n```\n", "meta": {"hexsha": "95f9998c7762c5ad622f9e4035df29439495e4e9", "size": 181618, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/.ipynb_checkpoints/Chapter1_Introduction-checkpoint.ipynb", "max_stars_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-02-28T06:01:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T02:32:34.000Z", "max_issues_repo_path": "Chapter1_Introduction/.ipynb_checkpoints/Chapter1_Introduction-checkpoint.ipynb", "max_issues_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/.ipynb_checkpoints/Chapter1_Introduction-checkpoint.ipynb", "max_forks_repo_name": "brianzhang01/Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "f0ce2a6d35ac5a839c89b306ab5bda603e2f31bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-06-04T21:46:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-04T21:46:21.000Z", "avg_line_length": 181.4365634366, "max_line_length": 93043, "alphanum_fraction": 0.8446960103, "converted": true, "num_tokens": 11408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.16591071413428418}} {"text": "# Calculating the *steady* solution for $\\eta$ and $\\theta$ domain using BVP solvers and upwinding\n\\begin{equation}\\label{p1introhpa} \\Psi _{\\eta \\eta \\tau } = \\frac{1}{{R_s }}\\Psi _{\\eta \\eta \\eta \\eta } + \\Psi _{\\eta \\eta \\eta } \\Psi _\\theta - \\Psi _{\\eta \\eta \\theta } \\Psi _\\eta \\\\\n \\\\\n\\quad \\Psi(\\eta=\\mp 1) = 0, \\qquad \\Psi_\\eta(\\eta=\\mp 1) = - sin\\theta, \\qquad\n-1 \\le \\eta \\le1, \\quad 0 \\le \\theta \\le \\pi \\end{equation}\n\nThis is the notebook uses upwinding, **this numerical method is unstable with respect to shooting** and numerically too intensive for the BVP solver to even return an answer. **This code should be avoided.**\n\n\n```julia\nusing DifferentialEquations\nusing Plots\nusing Sundials\nusing BenchmarkTools\nusing Calculus\nusing DelimitedFiles\nusing Interpolations\nusing LaTeXStrings\nusing SparseArrays\nusing Debugger\n#using LSODA\nusing LinearAlgebra\n```\n\nIn this code the vector **u** is used to store **u** = $[\\Psi ... \\Psi_\\eta...\\Psi_{\\eta\\eta} ... \\Psi_{\\eta\\eta\\eta}]$ in a single 1-dimensional vector. The BVPSolver runs perfectly with the latter structure. However the BVPSolver has a few issues if a matrix M is used to store the derivatives of $\\Psi$ in columns e.g. $M = [\\Psi, \\Psi_\\eta,\\Psi_{\\eta\\eta}, \\Psi_{\\eta\\eta\\eta}]$ this is why the matrix form is not used in this code, interesting the ODE solver works perfectly with the Matrix form $M$.\n\n\n```julia\npyplot()\nfunction Ψ_smallr(θ::Float64, η::Float64 ,r::Float64) \n return(-η*(η^2-1)*sin(θ)/2.0 + r*η*(η^2-1)^2.0*(2.0+η^2)*sin(2*θ)/560.0 + \n r^2.0*η*(η^2-1)^2*((-591 -2294*η^2 + 161*η^4 + 1428*η^6)*sin(θ) + 3.0*(423 + 166*η^2 - 553*η^4 - 84*η^6)sin(3*θ))/62092800)\nend\n \nfunction Ψ_smallr_d1(θ::Float64, η::Float64 ,r::Float64) \n return(-(3.0*η^2-1)*sin(θ)/2.0 + r*(7*η^6-9*η^2+2)*sin(2*θ)/560.0 + \n r^2.0*(3*(-197 - 1112*η^2 + 6930*η^4 - 2772*η^6 - 8085*η^8 + 5236*η^10)*sin(θ) + (1269 - 6120*η^2 - 6930*η^4 + 24948*η^6 - 10395*η^8 - 2772*η^10)*sin(3*θ))/62092800.0)\nend\n \nfunction Ψ_smallr_d2(θ::Float64, η::Float64 ,r::Float64) \n return(-3.0*η*sin(θ) + r*(42*η^5-18*η)*sin(2*θ)/560.0 + \n r^2.0*(3*( - 2224*η + 27720*η^3 - 16632*η^5 - 64680*η^7 + 52360*η^9)*sin(θ) + (- 12240*η - 27720*η^3 + 149688*η^5 - 83160*η^7 - 27720*η^9)*sin(3*θ))/62092800.0)\nend \n \nfunction Ψ_smallr_d3(θ::Float64, η::Float64 ,r::Float64) \n return(-3.0*sin(θ) + r*(210*η^4-18)*sin(2*θ)/560.0 + \n r^2.0*(3*( - 2224 + 83160*η^2 - 83160*η^4 - 452760*η^6 + 471240*η^8)*sin(θ) + (- 12240 - 83160*η^2 + 748440*η^4 - 582120*η^6 - 249480*η^8)*sin(3*θ))/62092800.0)\nend \n\nfunction Ψ_bigr(θ::Float64, η::Float64) \n return(sin(pi*η)*sin(θ)/pi)\nend\n \nfunction Ψ_bigr_d1(θ::Float64, η::Float64) \n return(cos(pi*η)*sin(θ))\nend\n \n \nfunction Ψ_bigr_d2(θ::Float64, η::Float64) \n return(-sin(pi*η)*sin(θ)*pi)\nend \n \nfunction Ψ_bigr_d3(θ::Float64, η::Float64) \n return(-cos(pi*η)*sin(θ)*pi^2) \nend \n\n\"\"\"This is the differential equation for the ``\\\\psi(\\\\eta)^{(0)}`` term in the series.\n``\\\\Psi_{\\\\eta \\\\eta \\\\eta \\\\eta\n}^{(n)} = R_s( \\\\Psi_{\\\\eta}^{(0)} \\\\Psi _{\\\\eta \\\\eta}^{(0)} - \\\\Psi ^{(0)} \\\\Psi _{\\\\eta \\\\eta\n\\\\eta }^{(0)})``\n\"\"\"\n\nfunction steady_diffeq_psi_bvp!(dψ, ψ, p, η) # This works for the BVPsolver psi a vector of vectors \n #p[4] psi0 initial condition \n #p[3] Δθ\n #p[2] is the J value for the number of steps in the J direction\n #p[1] is the Reynolds number \n \n #dψ[1:j+1] .= ψ[j+2:2*j+2]\n #dψ[j+2:2*j+2] .= ψ[2*j+3:3*j+3]\n #dψ[2*j+3:3*j+3] .= ψ[3*j+4:4*j+4]\n #dψ[3*j+4:4*j+4] = (ψ[j+2:2*j+2].*(p[3]*ψ[2*j+3:3*j+3])-ψ[3*j+4:4*j+4].*(p[3]*ψ[1:j+1])).*p[1]\n r, J, Δθ, psi0 = p \n\n Psietaetaeta = @view ψ[3*J+4:4*J+4] #View are non allocating and are very fast to work with.\n Psietaeta = @view ψ[2*J+3:3*J+3]\n Psieta = @view ψ[J+2:2*J+2] \n Psi = @view ψ[1:J+1]\n DPsi4eta = @view dψ[3*J+4:4*J+4]\n DPsi3eta = @view dψ[2*J+3:3*J+3]\n DPsi2eta = @view dψ[J+2:2*J+2]\n DPsi1eta = @view dψ[1:J+1]\n \n Psi[1] = Psi[J+1] = 0.0\n \n #The first 3 derivatives at the next η step are assigned, the last ψ_ηηηη derivative is assigned manually\n @. DPsi1eta = Psieta\n @. DPsi2eta = Psietaeta\n @. DPsi3eta = Psietaetaeta \n \n #Near θ=0 boundary we have to use first order one sided θ derivative for ψ_ηηθ and ψ_θ\n DPsietaetaDtheta=(Psietaeta[2]-Psietaeta[1])/Δθ\n DPsiDtheta =(Psi[2]-Psi[1])/Δθ\n DPsi4eta[1] = (Psieta[1]*DPsietaetaDtheta - Psietaetaeta[1]*DPsiDtheta)*r\n #Near θ=π boundary we have to use first order one sided θ derivative for ψ_ηηθ and ψ_θ \n DPsietaetaDtheta=(Psietaeta[J+1]-Psietaeta[J])/Δθ\n DPsiDtheta=(Psi[J+1]-Psi[J])/Δθ\n DPsi4eta[J+1] = (Psieta[J+1]*DPsietaetaDtheta - Psietaetaeta[J+1]*DPsiDtheta)*r\n #Upwinding\n for j = 2:J #If \\psi_eta < 0 then upwind with forward difference\n if Psieta[j] < 0.0\n DPsietaetaDtheta=(Psietaeta[j+1]-Psietaeta[j])/Δθ\n if( j < J )\n DPsietaetaDtheta=(-0.5*Psietaeta[j+2]+2*Psietaeta[j+1]-1.5*Psietaeta[j])/Δθ\n end\n else\n DPsietaetaDtheta=(Psietaeta[j] -Psietaeta[j-1])/Δθ\n if (j > 2)\n DPsietaetaDtheta=( 0.5*Psietaeta[j-2]-2*Psietaeta[j-1]+1.5*Psietaeta[j])/Δθ\n end\n end\n if Psietaetaeta[j] > 0.0\n DPsiDtheta=(Psi[j+1]-Psi[j])/Δθ\n if j < J \n DPsiDtheta=(-0.5*Psi[j+2]+2*Psi[j+1]-1.5*Psi[j])/Δθ\n end\n else\n DPsiDtheta=(Psi[j] -Psi[j-1])/Δθ\n if j > 2\n DPsiDtheta=( 0.5*Psi[j-2]-2*Psi[j-1]+1.5*Psi[j])/Δθ\n end\n end\n DPsi4eta[j] = (Psieta[j]*DPsietaetaDtheta - Psietaetaeta[j]*DPsiDtheta)*r\n end\n \n #Fully expanded loops for the copying this makes the \n #@inbounds for i =1:j+1\n # dψ[i] = ψ[j+1+i] \n # dψ[j+1+i] = ψ[2*j+2+i]\n # dψ[2*j+2+i] = ψ[3*j+3+i]\n #end\n \n\nend\n\n\nfunction bc_bvp!(residual, u, p, η) # psi[1] is the beginning of the etaspan, and psi[end] is the ending\n #p[4] is the initial condition psi0\n #p[3] is the matrix A\n #p[2] is the J value for the number of steps in the J direction\n j=p[2]\n @inbounds for i = 1:j+1\n residual[i] = u[1][i] # The psi[1] (i.e,. psi^{0}) solution at the beginning of the time span should be 0\n residual[j+1+i] = u[1][j+1+i] - p[4][j+1+i] #First derivative of should be -1 at first time step\n residual[2*j+2+i] = u[end][i] # the solution at the end of the time span should be 0\n residual[3*j+3+i] = u[end][j+1+i] - p[4][j+1+i] #First derivative should be -sinθ at end time step\n end\nend\n\n\n\n```\n\n\n\n\n bc_bvp! (generic function with 1 method)\n\n\n\n\n```julia\nconst Reynolds_number = 5.0\nconst J = 64 #Number of steps take in the theta direction from 0 to pi, restart kernel if this value is changed\nconst Δθ = pi/J\nconst etaspan=(-1.0,1.0)\n\nDpsi_eta_eta_Dtheta = ones(J+1); #For the Boundary Value solver Dpsi_eta_eta_Dtheta can be declared as Float and not Real, mult! function can be unstable\nDpsi_Dtheta = ones(J+1);\n\nif (Reynolds_number < 40.0 )\n psi_eta = [-sin(j*Δθ) for j =0:J]\n psi_eta_eta= [ Ψ_smallr_d2(j*Δθ, -1.0, Reynolds_number) for j =0:J]\n psi_eta_eta_eta= [ Ψ_smallr_d3(j*Δθ, -1.0, Reynolds_number) for j =0:J]\nelse\n psi_eta = [-sin(j*Δθ) for j =0:J]\n psi_eta_eta= [ Ψ_bigr_d2(j*Δθ, -1.0) for j =0:J]\n psi_eta_eta_eta= [ Ψ_bigr_d3(j*Δθ, -1.0) for j =0:J]\nend\n\n\n\n```\n\n\n\n\n 65-element Vector{Float64}:\n 0.0\n 0.01124100546425288\n 0.021444449823525825\n 0.029582564452131872\n 0.03464712464519113\n 0.035659118108778594\n 0.03167828686972883\n 0.02181249649266373\n 0.005226883345215566\n -0.0188472730217972\n -0.051104009351686075\n -0.09215453120803657\n -0.14251952393649137\n ⋮\n -3.115884580402397\n -2.9018569658175566\n -2.669168827408323\n -2.4191392235800913\n -2.153250192068408\n -1.8731339406260503\n -1.5805582652946428\n -1.2774103577494045\n -0.9656791861345967\n -0.6474366542317724\n -0.3248177613799546\n -8.112811696021303e-16\n\n\n\n\n```julia\n#The initial conditions psi0 (note here psi0 means psi@t=0) must be sent as a matrix \n\n#This is the ODESolver variable psi0\n#Uncomment the code below to solve the ODE IVP problem\n\n#ψ0= hcat(zeros(J+1), psi_eta, psi_eta_eta , psi_eta_eta_eta) #This works for the ODESolver AND BVPSolver\n#ψ0 is declared as a Matrix\n#p= (Reynolds_number, J, A, ψ0, Dpsi_Dtheta, Dpsi_eta_eta_Dtheta)\n#prob = ODEProblem(steady_diffeq_psi!, ψ0, etaspan, p)\n#sol = @time solve(prob, reltol=1e-5, alg_hints = [:stiff], Rosenbrock23())\n#Dpsi_eta_eta_Dtheta = Array{Real,1}(undef,J+1) #This has to be declared as real type because stiff solvers output reals\n#Dpsi_Dtheta = Array{Real,1}(undef,J+1)\n\n\n#This works fine for R < 10 with Vern 7 but there is a problem with MethodError: no method matching Float64\n#ψ0 is declared as a vector, Rosenbrock cannot handle VECTOR when called\n#ψ0= vcat(zeros(J+1), psi_eta, psi_eta_eta , psi_eta_eta_eta) #This works for the ODESolver AND BVPSolver\n#Dpsi_eta_eta_Dtheta = Array{Real,1}(undef,J+1) #This has to be declared as real type because stiff solvers output reals\n#Dpsi_Dtheta = Array{Real,1}(undef,J+1)\n#p= (Reynolds_number, J, A, ψ0, Dpsi_Dtheta, Dpsi_eta_eta_Dtheta)\n#prob = ODEProblem(steady_diffeq_psi_bvp!, ψ0, etaspan, p)\n#sol = @time solve(prob, reltol=1e-5, alg_hints = [:stiff], Vern7())\n\n#This is the BVP solver, works with J =20 upto R=30 with small R bc, and upto R=60, 88 with bigR boundary conditions.\n#ψ0 is declared as a VECTOR bvp only knows how to handle vectors\n\nψ0= vcat(zeros(J+1), psi_eta, psi_eta_eta , psi_eta_eta_eta) #This works for the ODESolver AND BVPSolver\np= (Reynolds_number, J, Δθ, ψ0)\nbvp_psi_2point = TwoPointBVProblem(steady_diffeq_psi_bvp!, bc_bvp!, ψ0, etaspan, p)\nsol = @time solve(bvp_psi_2point, alg_hints = [:stiff], GeneralMIRK4(),dt=0.001) #Very accurate solver\n#sol_shooting = @time solve(bvp_psi_2point, alg_hints=[:stiff], reltol=1e-6, abstol=1e-6 , Shooting(Rosenbrock23()))\n```\n\n\n```julia\nplot(sol_shooting)\n```\n\n\n```julia\nMatrixPsis=readdlm(\"psifin.m\",Float64,);\nsize(MatrixPsis)\n\n\n```\n\n\n\n\n (103, 256)\n\n\n\n\n```julia\nxinterval=range(-1,stop=1,length=101)\nplot(xinterval,MatrixPsis[2:102,77])\n```\n\n\n```julia\ntheta_step=30\nmypsi = [i[theta_step] for i in sol.u]\netarange = [i for i in sol.t]\nplot!(etarange, mypsi, linecolor=:orange)\n\n```\n\n\n```julia\ntheta_step=20\n\nmypsi = [i[theta_step] for i in sol.u]\netarange = [i for i in sol.t]\nplot(etarange, mypsi, linecolor=:orange)\nplot!(x->Ψ_bigr((theta_step-1)*Δθ,x),-1,1, label=\"Large R analytical\", linestyle=:dash, linecolor=:red,xlabel = L\"\\eta\", ylabel = L\"\\Psi\",size=(800,400),yguidefontrotation=-90, legend=:outertopright)\nplot!(x->Ψ_smallr((theta_step-1)*Δθ,x,Reynolds_number),-1,1, label=\"Small R analytical\", linestyle=:dot, linecolor=:blue,xlabel = L\"\\eta\", ylabel = L\"\\Psi\",size=(800,400),yguidefontrotation=-90, legend=:outertopright)\ntitle!(L\"\\Psi\\ at\\ \\theta = \"*string((theta_step-1))*L\"\\pi/\"*string(J))\n```\n\n\n```julia\n#First derivative of psi wrt to eta at the theta=0 boundary \nprint(sol.u[1][2*J+3:3*J+3])\n\n```\n\n\n```julia\n#First derivative of intitial psi wrt to eta at the theta=0 boundary \n#print(ψ0[2*J+3:3*J+3])\n#for i=2*J+3:3*J+3\nfor i=3*J+4:4*J+4\nprintln(sol.u[1][i],\" \", Ψ_bigr_d3(Δθ*(i-3*J-4), -1.0),\" \", Ψ_smallr_d3(Δθ*(i-3*J-4), -1.0, Reynolds_number),)\nend\n```\n\n\n```julia\neta_vector = [i for i in sol.t]\neta_totalsteps = length(sol.u)\npsi_sol = zeros((J+1)*eta_totalsteps)\n\ncounter = 1\nfor j = 1:J+1\n for matrix in sol.u\n psi_sol[counter] = matrix[j,1]\n counter += 1\n end\nend\n\n```\n\n\n```julia\n#sol.u[end][1:J+1]\nmypsi\n```\n\n\n```julia\nfor plot_counter =1:5\ntheta_step = plot_counter\nif (theta_step > J+1)\n println(\"The value of theta_step should be lower than \"*string(J+2))\nelseif (theta_step < 1)\n println(\"The value of theta_step should be greater than 0\")\nend\npsi_attheta = @view psi_sol[ (eta_totalsteps*(theta_step-1) +1) : eta_totalsteps*theta_step ]\nplot(eta_vector,psi_attheta,label=\"Julia numerical solution\", size=(800,600), legend=:outertopright)\ntemp_plot =plot!(x->Ψ_smallr((theta_step-1)*Δθ,x,Reynolds_number),-1,1, label=\"Small R analytical\", xlabel = L\"\\eta\", ylabel = L\"\\Psi\",size=(800,400),yguidefontrotation=-90, legend=:outertopright)\ntitle!(L\"\\Psi\\ at\\ \\theta = \"*string((theta_step-1))*L\"\\pi/\"*string(J))\ndisplay(temp_plot)\nsleep(1)\nend\n```\n\n\n```julia\nψ0[:,1]\n```\n\n\n\n\n 260-element Vector{Float64}:\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n ⋮\n -3.115884580402397\n -2.9018569658175566\n -2.669168827408323\n -2.4191392235800913\n -2.153250192068408\n -1.8731339406260503\n -1.5805582652946428\n -1.2774103577494045\n -0.9656791861345967\n -0.6474366542317724\n -0.3248177613799546\n -8.112811696021303e-16\n\n\n\n\n```julia\nlength(sol.t)\n```\n\n\n```julia\neta_n = length(sol.t)\neta_values= [i for i in sol.t]\ntheta_values=\nX = x'.*ones(n)\ny=10:15\nY = y'.*ones(n)\nz=[i for i =1:n^2]\nz= reshape(z,(n,n))\nx = [j for j=1:n for i=1:n]\ny = [i for j=1:n for i=1:n]\neta_values\n```\n\n\n```julia\npyplot()\nplot(x,y,z,seriestype=:scatter, markersize = 7,camera=(-30,30))\n```\n\n\n```julia\n?TwoPointBVProblem\n```\n\n search: \u001b[0m\u001b[1mT\u001b[22m\u001b[0m\u001b[1mw\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1mP\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1mi\u001b[22m\u001b[0m\u001b[1mn\u001b[22m\u001b[0m\u001b[1mt\u001b[22m\u001b[0m\u001b[1mB\u001b[22m\u001b[0m\u001b[1mV\u001b[22m\u001b[0m\u001b[1mP\u001b[22m\u001b[0m\u001b[1mr\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1mb\u001b[22m\u001b[0m\u001b[1ml\u001b[22m\u001b[0m\u001b[1me\u001b[22m\u001b[0m\u001b[1mm\u001b[22m\n \n\n\n\n\n\n```julia\nstruct TwoPointBVProblem{iip}\n```\n\n\n\n\n\n```julia\n\n```\n", "meta": {"hexsha": "8d30fbe1d520d85bb88ee79623056832cafb4f1e", "size": 48423, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "SteadyPsiEtaTheta_BVP_Upwind.ipynb", "max_stars_repo_name": "gsagoo/SolvingDifferentialEquations", "max_stars_repo_head_hexsha": "63c2b231b45ad64206a11824198b3d5fe20c062b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SteadyPsiEtaTheta_BVP_Upwind.ipynb", "max_issues_repo_name": "gsagoo/SolvingDifferentialEquations", "max_issues_repo_head_hexsha": "63c2b231b45ad64206a11824198b3d5fe20c062b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SteadyPsiEtaTheta_BVP_Upwind.ipynb", "max_forks_repo_name": "gsagoo/SolvingDifferentialEquations", "max_forks_repo_head_hexsha": "63c2b231b45ad64206a11824198b3d5fe20c062b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.0037174721, "max_line_length": 22029, "alphanum_fraction": 0.7259773248, "converted": true, "num_tokens": 5591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.16480450138312547}} {"text": "```python\n%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom matplotlib import rcParams\nrcParams['figure.dpi'] = 120\nfrom IPython.display import HTML\nfrom IPython.display import YouTubeVideo\nfrom functools import partial\nYouTubeVideo_formato = partial(YouTubeVideo, modestbranding=1, disablekb=0,\n width=640, height=360, autoplay=0, rel=0, showinfo=0)\n```\n\n# Optimización matemática\n\nLa **optimización** es el procedimiento para:\n\n> Encontrar la mejor solución para un problema dentro de un conjunto de posibilidades\n\nLa optimización es un área bastante estudiada de las matemáticas y algunos problemas de optimización requieren de soluciones muy específicas\n\nEl objetivo de esta lección es entregar una revisión general a los problemas de optimización que podemos resolver usando las herramientas del módulo `scipy.optimize`\n\n## Problema general de optimización\n\nUsualmente un problema matemático de optimización se formula como\n\n$$\n\\begin{align}\n\\min_x &f(x) \\nonumber \\\\\n\\text{sujeto a: } & g_i(x) = 0, i=1,2\\ldots, I \\\\ \\nonumber \n& h_j(x) \\leq 0, j=1,2,\\ldots J \\nonumber\n\\end{align}\n$$\n\ndonde \n\n- $x \\in \\mathbb{R}^D$ se conoce como **variable o variables de decisión**\n- $f : \\mathbb{R}^D \\to \\mathbb{R}$ se conoce como **función objetivo**\n- $g_i : \\mathbb{R}^D \\to \\mathbb{R}$ se conocen como **restricciones de igualdad** \n- $h_j : \\mathbb{R} \\to \\mathbb{R}^H$ se conocen como **restricciones de desigualdad**\n\nEl problema de optimización es entonces\n\n> La búsqueda de un valor extremo de la función objetivo dentro del espacio definido por las restricciones\n\nUn valor extremo puede ser un mínimo o un máximo. En un problema particular usualmente sólo nos interesa uno de estos casos. \n\nDado que\n\n$$\n\\max_x f(\\vec x) \\equiv \\min_x - f(\\vec x),\n$$\n\nentonces hablaremos sólo de minimización sin pérdida de generalidad\n\n### Reconocer y clasificar problemas de optimización\n\nEstudiando algunas características del problema podemos seleccionar más fácilmente un algoritmo apropiado para resolverlo. Algunas preguntas guía que podemos realizar son\n\n¿Es mi función objetivo de una variable ($D=1$) versus multi-variable ($D>1$)?\n\n> Esto define la dimensionalidad o escala del problema\n\n\n¿Existen restricciones de igualidad y/o desigualidad que debo cumplir?\n\n> Algunos algoritmos sólo pueden resolver problemas sin restricciones\n\n¿Es mi función objetivo lineal o no lineal con respecto a la entrada?\n\n> Si todas las funciones son lineales entonces se pueden usar técnicas de **programación lineal**. Esto problemas son más simples que los no lineales\n\n¿Es mi función objetivo convexa o no convexa?\n\n> Una función no-convexa (derecha) puede tener múltiples mínimos locales. Por el contrario una función convexa (izquierda) tiene un único mínimo\n\n\n\n¿Es mi función objetivo continua y diferenciable o no-diferenciable?\n\n> Muchos métodos se basan en el gradiente de la función de costo para encontrar la solución óptima. Si la función objetivo no es suave y no puede diferenciarse entonces no podemos usar dichos métodos\n\n\n \n\n\n## Resolviendo un problema de optimización\n\nConsideremos primero el caso de una **función objetivo continua y derivable**. \n\nVeremos primero una solución analítica, luego una solución exhaustiva y finalmente una solución basada en métodos iterativos\n\n\n### Solución analítica\n\nLa forma más clásica para obtener la solución en este caso es encontrar las raices (ceros) de la derivada/gradiente de $f$. Es decir\n\n$$\n\\nabla f (x^*) = \\begin{pmatrix} \\frac{\\partial f}{\\partial x_1}, \\frac{\\partial f}{\\partial x_2}, \\ldots, \\frac{\\partial f}{\\partial x_D} \\end{pmatrix} = \\vec 0\n$$\n\nEstas soluciones se conocen como **puntos estacionarios** de $f$, que incluyen los mínimos, máximos y puntos silla\n\nLuego si las segunda derivada o matriz Hessiana de $f$\n\n$$\nH_{ij}^f (x) = \\frac{\\partial^2 f}{\\partial x_i \\partial x_j} (x^*)\n$$\n\nes positiva o semi-definida positiva entonces $x^*$ es un **mínimo local**\n\n**Receta**\n\n1. Obtener $x^*$ tal que $\\nabla f (x^*)=0$\n1. Probar que es un mínimo el Hessiano\n\n**Limitación** \n\nSólo es práctico si podemos despejar una expresión análitica de $x$ a partir de $\\nabla f (x^*)=0$. Esto se puede hacer algebraicamente o usando una librería de cálculo simbólico como [SimPy](https://www.sympy.org/en/index.html)\n\n**Ejemplos**\n\nConsideremos el siguiente problema\n\n$$\n\\min_x x^2 - 2x\n$$\n\nIgualando la primera derivada de la función objectivo a cero tenemos que $ 2x - 2 = 0$, es decir $x=1$ es un punto estacionario\n\nLa segunda derivada es mayor que cero por lo tanto corresponde a un mínimo\n\nConsidere ahora el siguiente problema no-convexo\n\n$$\nf(x) = x^2 - 2x + 5 \\sin(2x)\n$$\n\nLa derivada en este caso es\n\n$$\n\\frac{\\partial f}{\\partial x} = 2x - 2 + 10 \\cos(2x) = 0\n$$\n\nEn este caso no es posible despejar analiticamente $x$ sin hacer más simplificaciones o supuestos\n\n### Búsqueda exhaustiva de la mejor solución\n\nPodemos encontrar la mejor solución probando una gran cantidad de \"soluciones candidatas\" de forma numérica y guardando la mejor. Esto se suele describir como un \"método de fuerza bruta\". \n\n**Receta**\n\n1. Definimos una grilla para nuestro espacio de parámetros (dominio y resolución)\n1. Para cada elemento de la grilla calculamos la función de costo\n1. Buscamos el elemento con menor función de costo\n\n**Ventaja** \n\nSi la resolución es lo suficientemente fina podemos encontrar el mínimo global del dominio aunque la función sea no-convexa\n\n**Desventaja** \n\nEl costo computacional crece rapidamente con la dimensión de $x$, **explosión combinatorial**. Esto lo hace infactible en la mayoría de los casos reales\n\n### Método iterativos\n\nEn lugar de evaluar todo el espacio de posibilidades los métodos iterativos parten de una solución inicial y la refinan paso a paso. \n\nEn cada paso los métodos iterativos buscan la dirección que más los acerque a la solución óptima\n\nA continuación veremos algunos métodos iterativos clásicos para funciones continuas y derivables\n\n\n**Método de Newton**\n\nSea el valor actual de la variable de decisión $x_t$. Podemos escribir el valor que tendrá en el siguiente paso como\n\n$$\nx_{t+1} = x_t + \\Delta x\n$$\n\nLo que queremos es encontrar el mejor $\\Delta x$ según nuestra función objetivo. \n\nConsideremos la aproximación de Taylor de segundo orden de $f$\n\n$$\nf(x_{t} + \\Delta x) \\approx f(x_t) + \\nabla f (x_t) \\Delta x + \\frac{1}{2} \\Delta x^T H_f (x_t) \\Delta x \n$$\n\nSi derivamos en función de $\\Delta x$ e igualamos a cero se tiene que\n\n$$\n\\begin{align}\n\\nabla f (x_t) + H_f (x_t) \\Delta x &= 0 \\nonumber \\\\\n\\Delta x &= - [H_f (x_t)]^{-1}\\nabla f (x_t) \\nonumber \\\\\nx_{t+1} &= x_{t} - [H_f (x_t)]^{-1}\\nabla f (x_t) \\nonumber \n\\end{align}\n$$\n\nQue corresponde a la regla iterativa de Newton. La regla está función del **Gradiente** y del **Hessiano** de $f$\n\nNotar que\n\n- La solución depende de $x_0$ el valor inicial\n- Al utilizar el método de Newton estamos suponiendo que la aproximación de segundo orden es suficiente para nuestro problema\n- Si nuestro modelo tiene $M$ parámetros el Hessiano será una matriz de $M\\times M$. Si $M$ es muy grande usar el Hessiano podría ser infactible\n\n**Gradiente descendente (GD)**\n\nSi el Hessiano es prohibitivo podemos usar una aproximación de primer orden de la regla de Newton. Esto resulta en el clásico método conocido como **gradiente descendente**\n\n$$\nx_{t+1} = x_{t} - \\eta \\nabla f (x_t)\n$$\n\ndonde se reemplaza el Hessiano por una constante $\\eta$ llamado \"paso\" o \"tasa de aprendizaje\". \n\nEs sumamente importante calibrar adecuadamente este parámetro. A continuación veremos un ejemplo para ilustrar los comportamientos que del gradiente descedente ante distintas tasas de aprendizaje.\n\nLuego veremos que ocurre cuando optimizamos una función no convexa usando GD (o método de Newton)\n\n\n\n**Ejemplo** Influencia de la tasa de aprendizaje en GD\n\n¿Cómo cambia la optimización con distintos $\\eta$?\n\n- Un $\\eta$ muy pequeño hará que la convergencia sea muy lenta\n- Un $\\eta$ muy grande hará que la optimización sea inestable o que diverja\n\nConsideremos nuevamente optimizar la función \n\n$$\nf(x) = x^2 - 2x\n$$\n\nesta vez utilizando gradiente descedente\n\n\n```python\n%%capture \nfig, ax = plt.subplots(1, 3, figsize=(7, 2.5), tight_layout=True, sharey=True)\n\nx_plot = np.linspace(-4, 6, num=100)\nf = lambda x : x**2 - 2*x\ndf = lambda x : 2*x - 2\nx = [np.random.rand(5)*10-4 for k in range(3)]\netas = [0.011, 0.11, 1.1]\nsc = []\n\nfor k in range(3):\n ax[k].plot(x_plot, f(x_plot))\n sc.append(ax[k].scatter(x[k], f(x[k]), c='k', s=100))\n ax[k].set_ylabel(r'$f(x)$')\n ax[k].set_xlabel(r'$x$')\n ax[k].set_title(f'eta={etas[k]}')\n\ndef update_plot(n):\n for k in range(3):\n x_ = sc[k].get_offsets()[:, 0]\n x_ -= etas[k]*df(x_)\n sc[k].set_offsets(np.c_[x_, f(x_)])\n return sc[0], sc[1], sc[2]\n \nanim = animation.FuncAnimation(fig, update_plot, frames=20, interval=200, repeat=False, blit=True)\n```\n\nEn el siguiente ejemplo animado\n\n- Cada punto negro es una solución que parte de un valor inicial distinto\n- La linea azul es la función objetivo \n- Cada figura representa una tasa de aprendizaje distinta\n\n\n```python\nHTML(anim.to_html5_video())\n```\n\nLuego de 20 iteraciones podemos ver que\n\n- En el caso de la derecha las soluciones divergen\n- En el caso de la izquierda las soluciones no alcanzan a converger\n- En el caso central las soluciones convergen\n\n**Ejemplo:** Optimización de una función no convexa con GD\n\nConsideremos la función no convexa\n\n$$\nf(x) = x^2 - 2x + 5 \\sin(2x)\n$$\n\nla cual optimizaremos usando gradiente descedente. Recordemos que GD sólo puede garantizar que la solución es un punto estacionario. \n\nSi la función es no convexa entonces la solución dependerá fuertemente del valor inicial de $x$\n\n\n```python\n%%capture \n\nx_plot = np.linspace(-4, 6, num=100)\nf = lambda x : x**2 - 2*x + 5*np.sin(2*x)\ndf = lambda x : 2*x - 2 + 10*np.cos(2*x)\nx = np.linspace(-4, 6, num=10)\neta = 0.005\n\nfig = plt.figure(figsize=(7, 4), tight_layout=True)\ngs = fig.add_gridspec(3, 3)\nax1 = fig.add_subplot(gs[0:2, :])\nax2 = fig.add_subplot(gs[2, :])\n\nax1.plot(x_plot, f(x_plot), label=r'$x^2-2x+5\\sin(2x)$')\nax2.plot(x_plot, -df(x_plot))\nax2.plot(x_plot, [0]*len(x_plot), 'r--')\nsc = ax1.scatter(x, f(x), s=100, c='k', label='soluciones')\n\nax1.set_ylabel(r'$f(x)$')\nax1.legend()\nax2.set_xlabel(r'$x$')\nax2.set_ylabel(r'$-\\nabla f(x)$')\n\ndef update_plot(n):\n ax1.set_title(f\"Iteración {n}/50\")\n x = sc.get_offsets()[:, 0]\n x -= eta*df(x)\n sc.set_offsets(np.c_[x, f(x)])\n return sc,\n \nanim = animation.FuncAnimation(fig, update_plot, frames=50, interval=200, repeat=False, blit=True)\n```\n\nEn el siguiente ejemplo animado\n\n- Cada punto negro es una solución que parte de un valor inicial distinto\n- El gráfico superior es la función objetivo \n- El gráfico inferior es el gradiente de al función objetivo y la linea punteada roja son los ceros de la derivada\n\n\n\n```python\nHTML(anim.to_html5_video())\n```\n\nLuego de 50 iteraciones podemos ver como distintas soluciones iniciales resultan en distintos mínimos\n\nUna estrategia cuando se usa GD en funciones no-convexas es justamente utilizar y comparar varias condiciones iniciales distintas\n\n\n## Módulo [`scipy.optimize`](https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#optimization-scipy-optimize)\n\nPodemos realizar optimización numérica usando el módulo `scipy.optimize`. La función principal de este módulo es `minimize` la cual engloba a una larga lista de optimizadores\n\nSus argumentos principales son\n\n```python\nfrom scipy.optimize import minimize\nminimize(fun, # Función objetivo \n x0, # Valor inicial de la variable de decisión\n args=(), # Argumentos adicionales de fun\n method=None, # El método de optimización a usar (más detalles a continuación)\n jac=None, # Función que calcula la matriz de primeras derivadas (jacobiano)\n bounds=None, # Secuencia de tuplas (min, max) con cotas para x \n constraints=(), # Diccinario o lista de restricciones (más detalles a continuación)\n tol=None, # Tolerancia para el término de la optimización\n callback=None, # Una función que se ejecuta luego de cada iteración\n options=None, # Diccionario con las opciones especificas para cada método\n ...\n )\n```\n\nLa función objetivo debe estar definida de la siguiente forma\n\n```python\ndef fun(x, *args):\n ...\n return f \n```\n\ndonde `x` es la variable a optimizar y `f` debe ser un valor escalar flotante. Los argumentos adicionales a `x` se deben desempaquetar de la tupla `args`\n\nLa función de primeras derivadas debe seguir una forma similar\n\n```python\ndef jac(x, *args):\n ...\n return dx # Esto es un arreglo con la misma dimesión de x\n```\n\ndonde `x` y `args` deben ser coincidir con `fun`. El argumento `jac` es opcional. Si no se especifica las derivadas se calcularán de forma numérica, lo cual es menos eficiente. Además recordar que no todos los métodos requieren de primeras derivadas\n\nLa función `optimize` retorna un objeto de tipo [`OptimizeResult`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.OptimizeResult.html#scipy.optimize.OptimizeResult), cuyos atributos más importantes son\n\n- `x`: Mejor valor encontrado de la variable de decisión\n- `fun`: Valor de la función objetivo en el óptimo encontrado\n- `jac`: Valor de la matriz de primeras derivadas en el óptimo encontrado\n- `success`: Booleano que indica si la optimización se llevó a cabo con exito\n- `message:` Mensaje indicando la razón de término, útil para debuggear\n\nA continuación describiremos algunos de los métodos disponibles a través del argumento `method` de `minimize`\n\n### Optimización sin restricciones \n\nCon estos métodos no se puede especificar el argumento `constraint` o `bounds`. Por ejemplo están\n\n- [`method=CG`](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-cg.html#optimize-minimize-cg): Gradiente conjugado. Es una versión de GD con tasa de aprendizaje adaptiva\n- [`method=BFGS`](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-bfgs.html#optimize-minimize-bfgs): Es un método de tipo [quasi-Newton](https://en.wikipedia.org/wiki/Quasi-Newton_method) con Hessiano inverso aproximado a cada paso. Es el método por defecto en optimize y es en general una buena opción\n\nLos cuales usan gradientes, ya sea numérico o especificado mediante el argumento `jac`. Si la derivada puede obtenerse analiticamente y es confiable los siguientes métodos tendrán un desempeño superior a las alternativas\n \nLuego están\n\n- [`method=Nelder-Mead`](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-neldermead.html#optimize-minimize-neldermead): Es una heurística tipo simplex. [Animación que muestra su funcionamiento](https://www.youtube.com/watch?v=HUqLxHfxWqU)\n- [`method=Powell`](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-powell.html#optimize-minimize-powell): Algoritmo de búsqueda de linea siguiendo una dirección a la vez. [Animación que muestra su funcionamiento](https://www.youtube.com/watch?v=4TYJGihyuDg)\n\nLos cuales no usan gradientes. Estos métodos pueden usarse cuando la función objetivo es no-derivable o demasiado ruidosa para ser derivada\n\n### Ejercicio práctico\n\nSea la función del \"dromedario invertido\" definida como\n\n$$\nf(x, y) = (4 - 2.1 x^2 + \\frac{1}{3} x^4) x^2 + x y + 4 y^2 (y^2 - 1) \n$$\n\nEncuentre el mínimo usando `minimize`\n\n- Implemente la función de costo y su primera derivada\n- Considere las siguientes soluciones iniciales $[1, 1]$ y $[-1, -1]$\n- Muestre el mejor valor de $x$, el mejor valor de la función objetivo y el *status* de término\n- (Opcional) Muestre graficamente la función y las soluciones encontradas\n\n**Solución paso a paso con comentarios**\n\n\n```python\nYouTubeVideo_formato('rApw8Zhy1Kg')\n```\n\n### Optimización con restricciones\n\nCon estos métodos se pueden incorporar restricciones al problema ya sea en forma de cotas para las variables o ecuaciones de igualdad/desigualdad que las variables deben cumplir\n\n- Las restricciones de igualdad deben ser siempre de la forma $g(x) = 0$\n- Las restricciones de desigualdad deben ser siempre de la forma $h(x) \\geq 0 $\n\nEn la práctica las restricciones se entregan como una tupla en el argumento `constraint` de `method`. Cada restricción es un diccionario con las llaves `type` y `fun` para especificar el tipo (string `eq` o `ineq`) y la función, respectivamente. Opcionalmente se puede especificar `jac`, la matriz de primeras derivadas de `fun` y `arg` una tupla con argumentos adicionales para `fun` y `jac`\n\nPor ejemplo si tengo la siguiente restricción (de desigualdad)\n\n$$\nx^2 \\geq 1 + 2x\n$$\n\nla tengo que escribir como:\n\n```python\n>>> h1 = {'type': 'ineq', \n 'fun' : lambda x: x**2 - 2*x -1,\n 'jac' : lambda x: np.array([2*x - 2])}\n```\n\nLos métodos que permiten especificar restricciones son\n\n- `method=L-BFGS-B`: Similar a BFGS pero permite añadir cotas para la variable de decisión\n- `method=SLSQP`: *Sequential Least Squares Programming*. Este método acepta cotas, restricciones de igualdad y restricciones de desigualdad\n\n### Ejercicio práctico\n\nSea la siguiente función de costo con dos variables de decisión\n\n$$\n\\min f(x, y) = -(2xy+2x-x^2-2y^2) \n$$\n\nsujeta a \n\n$$\nx^3 - y = 0 ~\\wedge~y-(x-1)^4-2 \\geq 0 \n$$\n\ndonde\n\n$$\n0.5\\leq x \\leq 1.5 ~\\wedge~ 1.5 \\leq y \\leq 2.5\n$$\n\n- Escriba la función de costo, restricciones y cotas\n- Muestre la solución del problema de optimización obtenida con BFGS (ignorando restricciones y cotas), L-BFGS-B (ignorando restricciones) y SLSQP. Use $x_0 = 0$ y $y_0 = 1$ como solución inicial\n- (Opcional) Muestre graficamente la solución del problema\n\n**Solución paso a paso con comentarios**\n\n\n```python\nYouTubeVideo_formato('60nw7S7eo8c')\n```\n\n\n\nEn la gráfica\n- El gradiente de color es la función objetivo\n- La sombra rectangular son las cotas\n- La linea punteada es la restricción de igualdad\n- La linea de puntos es la restricción de desigualdad\n\n## Resumen de la lección\n\nEn esta lección hemos aprendido a\n\n- Reconocer y diferenciar distintos problemas de optimización matemática\n- Resolver problemas de optimización matemática sin y con restricciones usando `scipy`\n - Debemos escoger un optimizador apropiado en función del problema a resolver\n - Si nuestro problema es no convexo es conveniente probar varias soluciones iniciales distintas\n - Siempre debemos comprobar la convergencia de los algoritmos de optimización que usemos\n\nSi quieres profundizar en este temas sugiero revisar\n\n- [Comparativa detallada entre los distintos métodos de optimización](https://scipy-lectures.org/advanced/mathematical_optimization/index.html) \n- [Encontrando raices de una función con `scipy`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html#scipy.optimize.root)\n- [Problemas de programación lineal con `scipy`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html#scipy.optimize.linprog)\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "d777b0ce67b454b90285ab34a96a6f39a115d6b0", "size": 27547, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "clases/unidad2/2_calculus/optimization.ipynb", "max_stars_repo_name": "magister-informatica-uach/INFO147", "max_stars_repo_head_hexsha": "3898eb6f589a22beefb5972a0c911bb9dd098c6d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2019-04-12T21:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T14:30:09.000Z", "max_issues_repo_path": "clases/unidad2/2_calculus/optimization.ipynb", "max_issues_repo_name": "magister-informatica-uach/INFO147", "max_issues_repo_head_hexsha": "3898eb6f589a22beefb5972a0c911bb9dd098c6d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clases/unidad2/2_calculus/optimization.ipynb", "max_forks_repo_name": "magister-informatica-uach/INFO147", "max_forks_repo_head_hexsha": "3898eb6f589a22beefb5972a0c911bb9dd098c6d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2019-04-12T20:00:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T21:48:53.000Z", "avg_line_length": 36.8768406961, "max_line_length": 401, "alphanum_fraction": 0.6015174066, "converted": true, "num_tokens": 5528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368443773709, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.16427022416716822}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](g). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\nimport json\ns = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\nplt.rcParams.update(s)\n```\n\n //anaconda/lib/python3.5/site-packages/matplotlib/__init__.py:913: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.\n warnings.warn(self.msg_depr % (key, alt_key))\n\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau >= idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n 100%|██████████| 10000/10000 [00:10<00:00, 975.23it/s]\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nlambda_1_samples.mean()\n```\n\n\n\n\n 17.762659476522295\n\n\n\n\n```python\nlambda_2_samples.mean()\n```\n\n\n\n\n 22.696630372585794\n\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n(lambda_1_samples/lambda_2_samples).mean()\n```\n\n\n\n\n 0.78385372425665323\n\n\n\n\n```python\n(lambda_1_samples.mean()/lambda_2_samples.mean())\n```\n\n\n\n\n 0.78261218449312131\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nlambda_1_samples[tau_samples < 45].mean()\n```\n\n\n\n\n 17.762315804333266\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/n_is_never_large).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "6e8d1e4839ccc927b3905f338484defe460b69b1", "size": 297322, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "david-hoffman/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "56b00bb45dad4dedcc1174cec3e67b1e75423ead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-02T02:15:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T02:15:19.000Z", "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "david-hoffman/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "56b00bb45dad4dedcc1174cec3e67b1e75423ead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "david-hoffman/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "56b00bb45dad4dedcc1174cec3e67b1e75423ead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-10-24T18:43:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:30:55.000Z", "avg_line_length": 265.9409660107, "max_line_length": 87350, "alphanum_fraction": 0.8912727615, "converted": true, "num_tokens": 11294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.16412311099490695}} {"text": "\n\n# Lambda School Data Science Module 143\n\n## Introduction to Bayesian Inference\n\n!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_vs_bayesians.png)\n\n*[XKCD 1132](https://www.xkcd.com/1132/)*\n\n\n## Prepare - Bayes' Theorem and the Bayesian mindset\n\nBayes' theorem possesses a near-mythical quality - a bit of math that somehow magically evaluates a situation. But this mythicalness has more to do with its reputation and advanced applications than the actual core of it - deriving it is actually remarkably straightforward.\n\n### The Law of Total Probability\n\nBy definition, the total probability of all outcomes (events) if some variable (event space) $A$ is 1. That is:\n\n$$P(A) = \\sum_n P(A_n) = 1$$\n\nThe law of total probability takes this further, considering two variables ($A$ and $B$) and relating their marginal probabilities (their likelihoods considered independently, without reference to one another) and their conditional probabilities (their likelihoods considered jointly). A marginal probability is simply notated as e.g. $P(A)$, while a conditional probability is notated $P(A|B)$, which reads \"probability of $A$ *given* $B$\".\n\nThe law of total probability states:\n\n$$P(A) = \\sum_n P(A | B_n) P(B_n)$$\n\n\nIn words - the total probability of $A$ is equal to the sum of the conditional probability of $A$ on any given event $B_n$ times the probability of that event $B_n$, and summed over all possible events in $B$.\n\n### The Law of Conditional Probability\n\nWhat's the probability of something conditioned on something else? To determine this we have to go back to set theory and think about the intersection of sets:\n\nThe formula for actual calculation:\n\n$$P(A|B) = \\frac{P(A \\cap B)}{P(B)}$$\n\nprobability of a given b\n\n\n\n\nThink of the overall rectangle as the whole probability space, $A$ as the left circle, $B$ as the right circle, and their intersection as the red area. Try to visualize the ratio being described in the above formula, and how it is different from just the $P(A)$ (not conditioned on $B$).\n\nWe can see how this relates back to the law of total probability - multiply both sides by $P(B)$ and you get $P(A|B)P(B) = P(A \\cap B)$ - replaced back into the law of total probability we get $P(A) = \\sum_n P(A \\cap B_n)$.\n\nThis may not seem like an improvement at first, but try to relate it back to the above picture - if you think of sets as physical objects, we're saying that the total probability of $A$ given $B$ is all the little pieces of it intersected with $B$, added together. The conditional probability is then just that again, but divided by the probability of $B$ itself happening in the first place.\n\n### Bayes Theorem\n\nHere is is, the seemingly magic tool:\n\n$$P(A|B) = \\frac{P(B|A)P(A)}{P(B)}$$\n\nIn words - the probability of $A$ conditioned on $B$ is the probability of $B$ conditioned on $A$, times the probability of $A$ and divided by the probability of $B$. These unconditioned probabilities are referred to as \"prior beliefs\", and the conditioned probabilities as \"updated.\"\n\nWhy is this important? Scroll back up to the XKCD example - the Bayesian statistician draws a less absurd conclusion because their prior belief in the likelihood that the sun will go nova is extremely low. So, even when updated based on evidence from a detector that is $35/36 = 0.972$ accurate, the prior belief doesn't shift enough to change their overall opinion.\n\nThere's many examples of Bayes' theorem - one less absurd example is to apply to [breathalyzer tests](https://www.bayestheorem.net/breathalyzer-example/). You may think that a breathalyzer test that is 100% accurate for true positives (detecting somebody who is drunk) is pretty good, but what if it also has 8% false positives (indicating somebody is drunk when they're not)? And furthermore, the rate of drunk driving (and thus our prior belief) is 1/1000.\n\nWhat is the likelihood somebody really is drunk if they test positive? Some may guess it's 92% - the difference between the true positives and the false positives. But we have a prior belief of the background/true rate of drunk driving. Sounds like a job for Bayes' theorem!\n\n$$\n\\begin{aligned}\nP(Drunk | Positive) &= \\frac{P(Positive | Drunk)P(Drunk)}{P(Positive)} \\\\\n&= \\frac{1 \\times 0.001}{0.08} \\\\\n&= 0.0125\n\\end{aligned}\n$$\n\nIn other words, the likelihood that somebody is drunk given they tested positive with a breathalyzer in this situation is only 1.25% - probably much lower than you'd guess. This is why, in practice, it's important to have a repeated test to confirm (the probability of two false positives in a row is $0.08 * 0.08 = 0.0064$, much lower), and Bayes' theorem has been relevant in court cases where proper consideration of evidence was important.\n\n## Derive Bayes' Rule\n\n\\begin{align}\nP(A\\B = )\n\n## Live Lecture - Deriving Bayes' Theorem, Calculating Bayesian Confidence\n\nNotice that $P(A|B)$ appears in the above laws - in Bayesian terms, this is the belief in $A$ updated for the evidence $B$. So all we need to do is solve for this term to derive Bayes' theorem. Let's do it together!\n\n\n```\n# Activity 2 - Use SciPy to calculate Bayesian confidence intervals\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bayes_mvs.html#scipy.stats.bayes_mvs\n\nfrom scipy import stats\nimport numpy as np\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=.5, size=100)\nprint(coinflips)\n```\n\n [0 1 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0\n 0 1 0 0 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 0 1\n 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0]\n\n\n\n```\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean , mean-interval, mean+interval)\n```\n\n\n```\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.47, 0.3704689875017368, 0.5695310124982632)\n\n\n\n\n```\nstats.bayes_mvs(coinflips, alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.47, minmax=(0.37046898750173674, 0.5695310124982632)),\n Variance(statistic=0.25680412371134015, minmax=(0.1939698977025208, 0.3395533426586547)),\n Std_dev(statistic=0.5054540733507159, minmax=(0.44042013771229943, 0.5827120581030176)))\n\n\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n\n```\n# TODO - code!\ndef prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk):\n return(prob_drunk_prior * prob_positive)/prob_positive_drunk\n```\n\n\n```\nprob_drunk_given_positive(1,.001,.08)\n```\n\n\n\n\n 0.0125\n\n\n\n\n```\nimport pandas as pd\n```\n\n\n```\ncongressional_Voting_R = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data')\n```\n\n\n```\ncon = congressional_Voting_R.replace({'n': 0, 'y': 1, '?': np.nan})\nc = con.dropna()\nc.columns = ['party','handicapped-infants','water-project-cost-sharing','adoption-of-the-budget-resolution','physician-fee-freeze','el-salvador-aid', 'religious-groups-schools', 'anti-satellite-test-ban', 'aid-to-nicaraguan-contras','mx-missile', 'immigration','synfuels-corporation-cutback','education-spending','superfund-right-to-sue', 'crime', 'duty-free-exports', 'export-administration-act-south-africa']\n```\n\n\n```\ndem = c[c['party']=='democrat']\nrep = c[c['party']=='republican']\n```\n\n\n```\ndem = dem.drop(columns = ['party'])\ndem.head(3)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
handicapped-infantswater-project-cost-sharingadoption-of-the-budget-resolutionphysician-fee-freezeel-salvador-aidreligious-groups-schoolsanti-satellite-test-banaid-to-nicaraguan-contrasmx-missileimmigrationsynfuels-corporation-cutbackeducation-spendingsuperfund-right-to-suecrimeduty-free-exportsexport-administration-act-south-africa
40.01.01.00.01.01.00.00.00.00.00.00.01.01.01.01.0
181.01.01.00.00.00.01.01.01.00.01.00.00.00.01.01.0
221.01.01.00.00.00.01.01.01.00.00.00.00.00.01.01.0
\n
\n\n\n\n\n```\nrep = rep.drop(columns = ['party'])\nrep.head(3)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
handicapped-infantswater-project-cost-sharingadoption-of-the-budget-resolutionphysician-fee-freezeel-salvador-aidreligious-groups-schoolsanti-satellite-test-banaid-to-nicaraguan-contrasmx-missileimmigrationsynfuels-corporation-cutbackeducation-spendingsuperfund-right-to-suecrimeduty-free-exportsexport-administration-act-south-africa
70.01.00.01.01.01.00.00.00.00.00.01.01.01.00.01.0
271.00.00.01.01.00.01.01.01.00.00.01.01.01.00.01.0
290.01.00.01.01.01.00.00.00.00.00.01.01.01.00.00.0
\n
\n\n\n\n\n```\nstats.bayes_mvs(list(dem['physician-fee-freeze']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.04838709677419355, minmax=(0.010088360711719258, 0.08668583283666784)),\n Variance(statistic=0.047187416688882974, minmax=(0.03669713193303354, 0.060615532442368454)),\n Std_dev(statistic=0.21677830124397068, minmax=(0.19156495486657663, 0.2462022185975757)))\n\n\n\n\n```\nprint(0.08668-0.01008)\n```\n\n 0.07659999999999999\n\n\n\n```\nstats.bayes_mvs(list(rep['physician-fee-freeze']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.9907407407407407, minmax=(0.9723853391655276, 1.009096142315954)),\n Variance(statistic=0.009435626102292767, minmax=(0.007204512108429059, 0.012343097409435866)),\n Std_dev(statistic=0.09690615065950328, minmax=(0.08487939743205684, 0.11109949329063505)))\n\n\n\n\n```\nprint(1.009-0.9723)\n```\n\n 0.036699999999999844\n\n\n\n```\nstats.bayes_mvs(list(dem['adoption-of-the-budget-resolution']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.8548387096774194, minmax=(0.791966749899413, 0.9177106694554258)),\n Variance(statistic=0.12716608904292187, minmax=(0.09889566063309035, 0.1633537230226539)),\n Std_dev(statistic=0.3558675308324249, minmax=(0.31447680460264527, 0.4041704133439927)))\n\n\n\n\n```\nprint(0.9177-0.7919)\n```\n\n 0.1257999999999999\n\n\n\n```\nstats.bayes_mvs(list(rep['adoption-of-the-budget-resolution']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.1574074074074074, minmax=(0.08761355698812176, 0.22720125782669306)),\n Variance(statistic=0.13641975308641976, minmax=(0.10416243207233418, 0.17845581020932047)),\n Std_dev(statistic=0.36847210103926065, minmax=(0.32274205191194744, 0.42244030372269226)))\n\n\n\n\n```\nprint(0.2272-0.08761)\n```\n\n 0.13959000000000002\n\n\n\n```\nstats.bayes_mvs(list(dem['water-project-cost-sharing']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.45161290322580644, minmax=(0.3627917755681809, 0.540434030883432)),\n Variance(statistic=0.2537989869368169, minmax=(0.19737666440818039, 0.32602252477477267)),\n Std_dev(statistic=0.502744872227253, minmax=(0.44427093581302435, 0.5709838218152706)))\n\n\n\n\n```\nprint(0.5404-0.3627)\n```\n\n 0.17769999999999997\n\n\n\n```\nstats.bayes_mvs(list(rep['water-project-cost-sharing']), alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.4722222222222222, minmax=(0.3765480931771919, 0.5678963512672525)),\n Variance(statistic=0.2563492063492063, minmax=(0.19573380092713347, 0.33534003896476705)),\n Std_dev(statistic=0.5051053514391345, minmax=(0.44241812906698735, 0.5790855195605974)))\n\n\n\n\n```\nprint(0.5678-0.3765)\n```\n\n 0.19129999999999997\n\n\n\n```\n# Set some parameters to apply to all plots. These can be overridden\n# in each plot if desired\nimport matplotlib\n# Plot size to 14\" x 7\"\nmatplotlib.rc('figure', figsize = (14, 7))\n# Font size to 14\nmatplotlib.rc('font', size = 14)\n# Do not display top and right frame lines\nmatplotlib.rc('axes.spines', top = False, right = False)\n# Remove grid lines\nmatplotlib.rc('axes', grid = False)\n# Set backgound color to white\nmatplotlib.rc('axes', facecolor = 'white')\n```\n\n\n```\n# libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n \n# width of the bars\nbarWidth = 0.3\n \n# Choose the height of the blue bars\nbars1 = [0.0483, 0.8548, 0.4516]\n \n# Choose the height of the cyan bars\nbars2 = [0.9907, 0.1574, 0.4722]\n \n# Choose the height of the error bars (bars1)\nyer1 = [0.07659, 0.1257, 0.1776]\n \n# Choose the height of the error bars (bars2)\nyer2 = [0.03669, 0.1395, 0.1912]\n \n# The x position of bars\nr1 = np.arange(len(bars1))\nr2 = [x + barWidth for x in r1]\n \n# Create blue bars\nplt.bar(r1, bars1, width = barWidth, color = 'cyan', yerr=yer1, capsize=7, label='Democratic Votes')\n \n# Create cyan bars\nplt.bar(r2, bars2, width = barWidth, color = 'red', yerr=yer2, capsize=7, label='Republican Votes')\n \n# general layout\nplt.xticks([r + barWidth for r in range(len(bars1))], ['physician-fee-freeze', 'adoption-of-the-budget-resolution', 'water-project-cost-sharing'])\nplt.ylabel('Bipartisan Difference')\nplt.legend()\n\nplt.figure(1, figsize=(20, 7))\n\nplt.title('Party Leanings By Topic via Bayesian Statistical Analysis')\n \n# Show graphic\nplt.show()\n\n```\n\n\n```\n#4. In your own words, summarize the difference between Bayesian and Frequentist statistics:\n```\n\n\nIn Bayesian Statistics, a hypothesis is experimented on little by little and the more experiments done, the more probable the hypothesis becomes. There is no assumption for any given fact. The answer is arrived through a random sampling of trials to show based on the errors, an approximation. In Frequentist Statistics, assumptions of hypothesis are expected as a given and the hypothesis is considered a concrete phenomenon until proven differently. \n\n## Resources\n\n- [Worked example of Bayes rule calculation](https://en.wikipedia.org/wiki/Bayes'_theorem#Examples) (helpful as it fully breaks out the denominator)\n- [Source code for mvsdist in scipy](https://github.com/scipy/scipy/blob/90534919e139d2a81c24bf08341734ff41a3db12/scipy/stats/morestats.py#L139)\n", "meta": {"hexsha": "4679bdb44bab17f333144ed6f6d3a30d2df569b8", "size": 76652, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lily_Su_Assignment14_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_stars_repo_name": "LilySu/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_stars_repo_head_hexsha": "6bfecdd1fdae835d8ffe3cffca57747488447d08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lily_Su_Assignment14_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_issues_repo_name": "LilySu/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_issues_repo_head_hexsha": "6bfecdd1fdae835d8ffe3cffca57747488447d08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-09-17T16:06:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T16:07:38.000Z", "max_forks_repo_path": "Lily_Su_Assignment14_LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_forks_repo_name": "LilySu/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_forks_repo_head_hexsha": "6bfecdd1fdae835d8ffe3cffca57747488447d08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.1439330544, "max_line_length": 32978, "alphanum_fraction": 0.6623441006, "converted": true, "num_tokens": 5908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046493573919, "lm_q2_score": 0.38491215153977604, "lm_q1q2_score": 0.16262717361971238}} {"text": "```python\n%matplotlib inline\n```\n\n# Set theory and proofs\n\nMathematics, as it is taught at school, is usually taught by example. Pupils are asked to learn the various mathematical \"laws\" by rote. For example, we all know from school that $$3 + 5 = 8$$ and $$\\frac{d}{dx} x^2 = 2x.$$ We rarely pause and ask, why is this the case, and what are we really doing?\n\nIn fact, a lot is going on in these equations. For example, we would have to spend a lot of time explaining what $dx$ \"really\" is in $$\\frac{d}{dx} x^2 = 2x.$$ We would either have to introduce the notion of an **infinitesimal** or resort to Silvanus Thompson's explanation from *Calculus Made Easy* (1910):\n
\n$dx$ means a little bit of $x$.\n
\n\nThis explanation may be sufficient if we want to *do* mathematics rather than *understand* it. Thompson uses the Ancient Simian Proverb as an epigraph to his work:\n
\nWhat one fool can do, another can.\n
\n\n

\n

\n\n
\n\nWhat are we doing, what is mathematics anyway? **\"Mathematics\"** is not a \"-logy\", unlike many of the sciences. The word itself comes from the Ancient Greek μαθηματικός (mathēmatikós, \"fond of learning\"). Thus mathematics is... a form of learning? This definition is as abstract as mathematics itself...\n\nIt was probably G. H. Hardy in *A Mathematician's Apology* (1940) who defined mathematics as the \"study of patterns\":\n
\nA mathematician, like a painter or a poet, is a maker of patterns. If his patterns are more permanent than theirs, it is because they are made with ideas.\n
\n\n

\n

\n\n
\n\nLynn Arthur Steen seconds him in *The Science of Patterns* (Science, 1988):\n
\nMathematics is often defined as the science of space and number, as the discipline rooted in geometry and arithmetic. Although the diversity of modern mathematics has always exceeded this definition, it was not until the recent resonance of computers and mathematics that a more apt definition became fully evident. Mathematics is the science of patterns. The mathematician seeks patterns in number, in space, in science, in computers, and in imagination.\n
\n\n

\n

\n\n
\n\nAccording to this definition, mathematics is a *study of patterns*. And patterns are more general than numbers. Therefore, a number cannot be the most basic \"unit\" of study in mathematics. What is this most basic \"unit\"? What abstraction could we introduce to study patterns in all their various forms, including numbers?\n\nIn 1874, Georg Cantor introduced just such an abstraction in *On a Property of the Collection of All Real Algebraic Numbers*: the *set*. It has proved to be a very fruitful abstraction, allowing us, among other things, to formalise the notion of *infinity*.\n\n

\n

\n\n
\n\n## Sets\n\nA **set** is (arguably) the most fundamental object in mathematics. It is a collection of distinct objects. For example, we could talk about the set of numbers from one up to ten, inclusive. We could give this set a name, say, $S$, and write it like so: $$S = \\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10\\}.$$ We refer to objects in a particular set as its **elements**. We have just *defined* a particular set by listing its elements. Thus 3 is an element of $S$, and we write $$3 \\in S.$$ On the other hand, 11 is not an element of $S$, and we write $$11 \\notin S.$$ Neither, in fact, is Joe: $$\\text{Joe} \\notin S.$$\n\n## Finite and infinite sets\n\nThis particular set, $$S = \\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10\\},$$ is **finite**. Consider the set of all **natural numbers**: $$\\mathbb{N} = \\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...\\}.$$ There is no way to list all of its elements, of course, but at least, if we had an infinite amount of time, we could enumerate (list) them: \"one\", \"two\", \"three\", and so on. We call such sets **countably infinite** or **denumerable**.\n\n## Equivalence of sets\n\nTwo sets, $A$ and $B$ are said to be **equivalent** or **equinumerous** (we write $A \\sim B$) if a one-to-one correspondence can be set up between all their elements. For example, the sets $A = \\{1, 2, 3\\}$ and $B = \\{a, b, c\\}$ are equivalent:\n$$\n1 \\mapsto a, \\\\\n2 \\mapsto b, \\\\\n3 \\mapsto c.$$\nThis is not the only such one-to-one correspondence; for example, we could use this one:\n$$\n1 \\mapsto b, \\\\\n2 \\mapsto a, \\\\\n3 \\mapsto c.\n$$\n\nOn the other hand, $A = \\{1, 2\\}$ and $B = \\{a, b, c\\}$ are not equivalent: we need a *one-to-one* correspondence between *all* elements of $A$ and all the elements of $B$, but $A$ has fewer elements than $B$.\n\nFinite sets are equivalent if and only if (or, to use Paul Halmos's abbreviation, **iff**) they have the same number of elements. In fact, equivalence is a generalisation of this notion (that the sets have the same number of elements) to sets with infinitely many elements.\n\nThus every countably infinite (denumerable) set is equivalent to the set of natural numbers, $\\mathbb{N}$: enumerating a set or listing its elements is the same as finding a one-to-one correspondence between the elements of this set and natural numbers.\n\nAre positive rational numbers (i.e. fractions $\\frac{p}{q}$, $p, q \\in \\mathbb{N}$, $q \\neq 0$) denumerable? What do you think?\n\nFirst, note that positive rationals can be arranged in a table:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$p$: $1$ $2$ $3$ $4$ $5$ $\\ldots$
$q$
$1$ $\\frac{1}{1}$ $\\frac{2}{1}$ $\\frac{3}{1}$ $\\frac{4}{1}$ $\\frac{5}{1}$ $\\ldots$
$2$ $\\frac{1}{2}$ $\\frac{2}{2}$ $\\frac{3}{2}$ $\\frac{4}{2}$ $\\frac{5}{2}$ $\\ldots$
$3$ $\\frac{1}{3}$ $\\frac{2}{3}$ $\\frac{3}{3}$ $\\frac{4}{3}$ $\\frac{5}{3}$ $\\ldots$
$4$ $\\frac{1}{4}$ $\\frac{2}{4}$ $\\frac{3}{4}$ $\\frac{4}{4}$ $\\frac{5}{4}$ $\\ldots$
$5$ $\\frac{1}{5}$ $\\frac{2}{5}$ $\\frac{3}{5}$ $\\frac{4}{5}$ $\\frac{5}{5}$ $\\ldots$
$\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\ddots$
\n\nNot all entries in this table are distinct, for example, $\\frac{1}{1} = \\frac{2}{2} = \\frac{3}{3} = \\frac{4}{4} = \\frac{5}{5}$, $\\frac{2}{4} = \\frac{1}{2}$, etc. Let us erase all rational numbers that have non-trivial common factors in the numerator and denominator, while keeping the first occurrence. All rational numbers in our table are now unique; if we continue the table indefinitely, it will include all positive rational numbers:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$p$: $1$ $2$ $3$ $4$ $5$ $\\ldots$
$q$
$1$ $\\frac{1}{1}$ $\\frac{2}{1}$ $\\frac{3}{1}$ $\\frac{4}{1}$ $\\frac{5}{1}$ $\\ldots$
$2$ $\\frac{1}{2}$ $\\frac{3}{2}$ $\\frac{5}{2}$ $\\ldots$
$3$ $\\frac{1}{3}$ $\\frac{2}{3}$ $\\frac{4}{3}$ $\\frac{5}{3}$ $\\ldots$
$4$ $\\frac{1}{4}$ $\\frac{3}{4}$ $\\frac{5}{4}$ $\\ldots$
$5$ $\\frac{1}{5}$ $\\frac{2}{5}$ $\\frac{3}{5}$ $\\frac{4}{5}$ $\\ldots$
$\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\ddots$
\n\nFinally, we associate these numbers with the natural numbers $1, 2, 3, \\ldots$. We start in the top-left corner of the table and then follow the arrows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$p$: $1$ $2$ $3$ $4$ $5$ $\\ldots$
$q$
$1$ $\\frac{1}{1}$ $\\frac{2}{1}$ $\\rightarrow$ $\\frac{3}{1}$ $\\frac{4}{1}$ $\\rightarrow$ $\\frac{5}{1}$ $\\ldots$
$\\downarrow$ $\\nearrow$ $\\swarrow$ $\\nearrow$ $\\swarrow$
$2$ $\\frac{1}{2}$ $\\swarrow$ $\\frac{3}{2}$ $\\swarrow$ $\\frac{5}{2}$ $\\ldots$
$\\swarrow$ $\\nearrow$ $\\swarrow$ $\\nearrow$
$3$ $\\frac{1}{3}$ $\\frac{2}{3}$ $\\swarrow$ $\\frac{4}{3}$ $\\frac{5}{3}$ $\\ldots$
$\\downarrow$ $\\nearrow$ $\\swarrow$ $\\nearrow$ $\\swarrow$
$4$ $\\frac{1}{4}$ $\\swarrow$ $\\frac{3}{4}$ $\\swarrow$ $\\frac{5}{4}$ $\\ldots$
$\\swarrow$ $\\nearrow$ $\\swarrow$ $\\nearrow$
$5$ $\\frac{1}{5}$ $\\frac{2}{5}$ $\\frac{3}{5}$ $\\frac{4}{5}$ $\\swarrow$ $\\ldots$
$\\downarrow$ $\\nearrow$ $\\swarrow$ $\\nearrow$ $\\swarrow$
$\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\ddots$
\n\nIt is easy to see that all *negative* rational numbers are also denumerable: we simply put the minus sign before the fractions in the tables above.\n\nWhat about all **real numbers**, including positive and negative rationals, such as $\\frac{1}{2}$ and $-\\frac{1}{2}$, zero, and irrationals, such as $\\sqrt{2}$, $\\pi = 3.1415926535\\ldots$ and $e = 2.7182818284\\ldots$? Clearly, this set (denoted $\\mathbb{R}$) is also infinite. Can we enumerate it?\n\nWe know that all real numbers can be written as decimal fractions, e.g. $\\pi = 3.1415926535...$. Suppose we can enumerate all real numbers between 0 and 1, inclusive:\n$$\na_1 = 0.a_{11}a_{12}a_{13}a_{14}a_{15}\\ldots, \\\\\na_2 = 0.a_{21}a_{22}a_{23}a_{24}a_{25}\\ldots, \\\\\na_3 = 0.a_{31}a_{32}a_{33}a_{34}a_{35}\\ldots, \\\\\n\\vdots \\\\\na_k = 0.a_{k1}a_{k2}a_{k3}a_{k4}a_{k5}\\ldots, \\\\\n\\vdots \\\\\n$$\nHere $a_{11}, a_{12}, a_{13}, a_{14}, a_{15}, \\ldots, a_{21}, a_{22}, a_{23}, \\ldots$ are all decimal digits, $0, 1, 2, 3, \\ldots 9$.\n\nIf indeed it is possible to enumerate all real numbers between 0 and 1, then all of them appear on our list. But consider the number $b$ which differs from $a_1$ in the first digit (so that digit is anything but $a_{11}$), from $a_2$ in the second digit (so that digit is anything but $a_{22}$), from $a_3$ in the third digit (so that digit is anything but $a_{33}$), and so on. We have highlighted these digits below:\n$$\na_1 = 0.\\mathbf{a_{11}}a_{12}a_{13}a_{14}a_{15}\\ldots, \\\\\na_2 = 0.a_{21}\\mathbf{a_{22}}a_{23}a_{24}a_{25}\\ldots, \\\\\na_3 = 0.a_{31}a_{32}\\mathbf{a_{33}}a_{34}a_{35}\\ldots, \\\\\n\\vdots \\\\\na_k = 0.a_{k1}a_{k2}a_{k3}a_{k4}a_{k5}\\ldots \\mathbf{a_{kk}}\\ldots, \\\\\n\\vdots \\\\\n$$\n\nBy construction, $b$ differs from *all* numbers on our list, therefore $b$ is *not* on our list. So our attempt to enumerate all numbers between 0 and 1 (let alone *all* real numbers!) has failed.\n\nWe have just shown that real numbers are not enumerable using the so-called **Cantor's diagonal slash argument**. It is a \"diagonal slash\" for obvious reasons, while it's \"Cantor's\" because the aforementioned Georg Cantor discovered it.\n\nIncidentally, Cantor's set theory, which has become the foundation of modern mathematics, was initially rejected by many prominent mathematicians. Leopold Kronecker, for instance, said:\n
\nI don't know what predominates in Cantor's theory — philosophy or theology, but I am sure that there is no mathematics there.\n
\n\nThus the set $\\mathbb{R}$, just like the set $\\mathbb{N}$, is infinite, but it is even \"more\" infinite that $\\mathbb{N}$: it is **uncountable** or **uncountably infinite**: we can't even enumerate it! In set theory this idea of *different kinds of infinity* generates further to the notion of **cardinality**.\n\n## Subsets and supersets\n\nNotice that all elements of our example set $$S = \\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10\\}$$ are also elements of $\\mathbb{N}$. We say that $S$ is a **subset** of $\\mathbb{N}$ and write $$S \\subseteq \\mathbb{N}.$$ Of course, $$\\mathbb{N} \\nsubseteq S.$$\n\nWe could, equivalently, say that $\\mathbb{N}$ is a **superset** of $S$ and write $$\\mathbb{N} \\supseteq S.$$\n\nSimilarly, $$\\mathbb{N} \\subseteq \\mathbb{R},$$ which is the same thing as $$\\mathbb{R} \\supseteq \\mathbb{N},$$ and $$\\mathbb{R} \\nsubseteq \\mathbb{N},$$ which is the same thing as $$\\mathbb{N} \\nsupseteq \\mathbb{R}.$$\n\nSince $S$ is a subset of $\\mathbb{N}$, we could use the following \"syntactic sugar\" to define $S$:\n$$S = \\{x \\, | \\, x \\in \\mathbb{N}, x \\leq 10\\}.$$\nWe read \"$|$\" as \"such that\". Thus, instead of listing all elements of a set, we could define it by mentioning a particular **property** of its elements, such as $x \\leq 10$.\n\nWe can write $$|S| = 10$$ to indicate that $S$ has exactly 10 elements.\n\n## Equality of sets\n\nAny two sets $A$ and $B$ are equal, $A = B$, iff (if and only if) $A \\subseteq B$ *and* $B \\subseteq A$.\n\nWe shall add that we consider only distinct objects when talking about elements of sets. Repeats are not allowed. Thus $\\{2, 2\\}$ is really the same set as $\\{2\\}$ and it is deemed to contain exactly one element.\n\nNor do we care about the order of elements in a set: $\\{1, 2, 3\\}$ and $\\{3, 2, 1\\}$, for instance, are deemed to be equal.\n\nA set containing a single element, such as $\\{5\\}$, is called a **singleton** set. We distinguish sets from their elements. Thus $5 \\in A$, whereas $\\{5\\} \\notin A$. This is because $\\{5\\}$ is *not* the *number five*, it is a *set containing* the number five.\n\nIn the programming language Python there is a data structure called `set`, which works according to principles that mimic those of a mathematical set.\n\n\n```python\nA = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n```\n\n\n```python\nA\n```\n\n\n\n\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\n\n\n\n```python\nset([2, 3, 4]).issubset(A)\n```\n\n\n\n\n True\n\n\n\n\n```python\nA.issubset(set([2, 3, 4]))\n```\n\n\n\n\n False\n\n\n\n\n```python\nset([2, 3, 4]) == A\n```\n\n\n\n\n False\n\n\n\n\n```python\nset([1, 2, 3]) == set([3, 2, 1])\n```\n\n\n\n\n True\n\n\n\n\n```python\nset([2, 2]) == set([2])\n```\n\n\n\n\n True\n\n\n\n\n```python\nset([2, 2])\n```\n\n\n\n\n {2}\n\n\n\n\n```python\nlen(set([2, 2]))\n```\n\n\n\n\n 1\n\n\n\n\n```python\nB = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 1, 1])\n```\n\n\n```python\nA.issubset(B)\n```\n\n\n\n\n True\n\n\n\n\n```python\nB.issubset(A)\n```\n\n\n\n\n True\n\n\n\n\n```python\nA == B\n```\n\n\n\n\n True\n\n\n\n\n```python\nlen(B)\n```\n\n\n\n\n 10\n\n\n\n\n```python\nset(['foo', 'bar', 'baz', 1, 2, 3, 4, 5, 1./7.])\n```\n\n\n\n\n {0.14285714285714285, 1, 2, 3, 4, 5, 'baz', 'foo', 'bar'}\n\n\n\n## Proof by contradiction\n\nWhen we were asked whether the set of positive rational numbers was denumerable, we simply enumerated its elements. We **proved** the statement \"the set of rational numbers is denumerable\" by actually finding — constructing — the requisite enumeration. Such a proof is known as a **constructive proof**: the existence of a mathematical object (in this case, the one-to-one correspondence between the natural numbers and the positive rational numbers) is demonstrated by creating or providing a method for creating the object.\n\n**Cantor's diagonal slash argument** is an example of a different kind of proof — **proof by contradiction** or, in Latin, ***reductio ad absurdum***.\n\nIn *A Mathematician's Apology*, G. H. Hardy described proof by contradiction as \"one of a mathematician's finest weapons\", saying\n
\nIt is a far finer gambit than any chess gambit: a chess player may offer the sacrifice of a pawn or even a piece, but a mathematician offers the game.\n
\n\nHere is another example. This one is due to Euclid (c. 300 BC).\n\n

\n

\n\n
\n\nRecall that a prime is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. The first few primes are 2, 3, 5, 7, 11, 13, 17, 19, 23. Indeed, we can quickly come up with a list of primes using Python list comprehensions (in practice there are *far* more efficient algorithms for finding primes):\n\n\n```python\n[x for x in range(2, 100) if all(x % y != 0 for y in range(2, x))]\n```\n\n\n\n\n [2,\n 3,\n 5,\n 7,\n 11,\n 13,\n 17,\n 19,\n 23,\n 29,\n 31,\n 37,\n 41,\n 43,\n 47,\n 53,\n 59,\n 61,\n 67,\n 71,\n 73,\n 79,\n 83,\n 89,\n 97]\n\n\n\nHow do you prove that there are infinitely many primes, i.e. the set of all primes is infinite (obviously, countably infinite, since it is a subset of natural numbers, a countably infinite set)?\n\nSince we are talking about proofs by contradiction, it may be sensible to assume that that's how we shall proceed. Assume *for a contradiction* that $P$, the set of *all* primes, is finite. Say, there exist exactly $n$ primes, $n \\in \\mathbb{N}$:\n$$P = \\{p_1, p_2, p_3, \\ldots, p_n\\}.$$\n\nMultiplying the elements of $P$ together, we obtain another number. Let us add 1 to that number to obtain\n$$a = p_1 p_2 p_3 \\ldots p_n + 1.$$\nClearly this number is greater than any of the elements of $P$, so it is not in $P$. Since, by our assumption, $P$ contains all primes, $a$ is not a prime. Then there exists some prime in $P$, say, $p_k$, $1 \\leq k \\leq n$, that divides a. Then,\n$$a = p_k \\cdot b, \\quad b \\in \\mathbb{N}.$$\nBut then\n$$\n\\begin{align}\n1 &= a - p_1 p_2 p_3 \\ldots p_n \\\\\n &= p_k \\cdot b - p_1 \\ldots p_{k-1} p_k p_{k+1} \\ldots p_n \\\\\n &= p_k (b - p_1 \\ldots p_{k-1} p_{k+1} \\ldots p_n).\n\\end{align}\n$$\nIn other words, $p_k$ divides 1. Since no natural number other than 1 divides 1, we have a contradiction. Our assumption that $P$ is finite must have been wrong. There are therefore infinitely many primes. **Q.E.D.** (which signifies the end of the proof and is an initialism of the Latin phrase *quod erat demonstrandum*, \"what was to be demonstrated\").\n\nInstead of Q.E.D., people sometimes put the **Halmos symbol**, □, at the end of the proof.\n\nHere is yet another example: prove that $\\sqrt{2}$ is not a rational number, i.e. that $\\sqrt{2}$ is irrational.\n\n*Assume for a contradiction* that $\\sqrt{2}$ is rational. Then we can write it as $\\sqrt{2} = \\frac{p}{q}$, where $p$ and $q$ are natural numbers, $q \\neq 0$. Further, we can assume that $\\frac{p}{q}$ is a fraction in lowest terms, i.e. there is no prime that divides both $p$ and $q$. (Thus $\\frac{3}{9}$ is not in lowest terms, since $3$ divides both $3$ and $9$, whereas $\\frac{1}{3}$ is.) \n\nSince $\\sqrt{2} = \\frac{p}{q}$, on squaring both sides, we obtain $2 = \\frac{p^2}{q^2}$, hence $p^2 = 2q^2$. Since the right-hand side is even, the left-hand side must be even. Therefore $p$ is even, say $p = 2a$ for some $a \\in \\mathbb{N}$. But then $p^2 = 4a^2$, so $4a^2 = 2q^2$, whence $q^2 = 2a^2$, thus $q$ is even.\n\nThis contradicts our assumption that $\\frac{p}{q}$ is a fraction in lowest terms. We have reached the contradiction. Therefore $\\sqrt{2}$ cannot be written as a fraction in the form $\\frac{p}{q}$. In other words, $\\sqrt{2}$ is irrational. □\n\nThat $\\sqrt{2}$ is irrational was discovered by Pythagoras and his followers, i.e. the Pythagoreans, in the 6th century BC. Prior to this discovery, people believed that all numbers were rational, i.e. could be expressed as simple fractions.\n\n

\n

\n\n
\n\nThe discovery of irrational numbers is said to have been shocking to the Pythagoreans (as it violated their mystical worldview). They kept this discovery secret. Hippasus of Metapontum divulged this secret and is supposed to have drowned at sea, apparently as a punishment from the gods for divulging it.\n\n

\n

\n\n
\n\n## Russell's paradox and Zermelo-Fraenkel set theory\n\nOur treatment of set theory is very informal. In practice it was built out of axioms. Refer to *Naïve set theory* by Paul Halmos for a more detailed overview.\n\n

\n

\n\n
\n\nNow, suppose that we have a set containing all sets that are not elements of themselves. Symbolically, let $$R = \\{x \\, | \\, x \\notin x\\}.$$ Is $R$ an element of itself?\n\nIf it were, $R \\in R$, then we could substitute it for $x$ in \"$x \\, | \\, x \\notin x$\", and so $R \\notin R$.\n\nIf it weren't, then $R \\notin R$, and, by definition, since $R$ is not an element of itself, it is in $R$, $R \\in R$.\n\nThus we have a paradox: $R \\in R \\Leftrightarrow R \\notin R$.\n\nThis particular paradox was discovered by Bertrand Russell in 1901 and bears his name, so it is called **Russell's paradox**.\n\n

\n

\n\n
\n\nThis paradox confounded the so-called **naïve set theorists**, who did not know how to deal with it. Eventually, in 1908, Ernst Zermelo proposed an axiomatisation of set theory that avoided the paradoxes of naïve set theory, which was eventually elaborated by Abraham Fraenkel, Thoralf Skolem, and Zermelo himself. The result became known as the **Zermelo-Fraenkel set theory** or **ZFC**. It is ZFC that remains the canonical axiomatic set theory to this day.\n\nWe won't go into the details of how Russell's paradox is resolved in ZFC, but we shall prefer to talk about **collections** or **families** of sets, rather than sets of sets.\n\n## Union and intersection\n\nThe **union** of two sets $A$ and $B$ is the set of elements which are in $A$, in $B$, or in both $A$ and $B$: $$A \\cup B = \\{x \\, | \\, x \\in A \\text{ or } x \\in B\\}.$$\n\nWe can check that, in Python,\n\n\n```python\nA = set([3, 5, 7, 9])\nB = set([1, 2, 3])\nA.union(B)\n```\n\n\n\n\n {1, 2, 3, 5, 7, 9}\n\n\n\nThe **intersection** of two sets $A$ and $B$ is the set of elements which are in $A$ *and* in $B$: $$A \\cap B = \\{x \\, | \\, x \\in A \\text{ and } x \\in B\\}.$$\n\nIn Python,\n\n\n```python\nA = set([3, 5, 7, 9])\nB = set([1, 2, 3])\nA.intersection(B)\n```\n\n\n\n\n {3}\n\n\n\n**Venn diagrams** are helpful in visualising sets, including set unions and intersections (which are, of course, themselves sets).\n\nThe Python package `matplotlib_venn` is helpful in constructing them. It can be installed using `easy_install matplotlib-venn`.\n\n\n```python\nfrom matplotlib_venn import venn2\nv = venn2(subsets = (2, 2, 1));\nv.get_label_by_id('01').set_text('')\nv.get_patch_by_id('01').set_linewidth(2)\nv.get_patch_by_id('01').set_edgecolor('black')\nv.get_patch_by_id('01').set_facecolor('white')\n\nv.get_label_by_id('10').set_text('')\nv.get_patch_by_id('10').set_linewidth(2)\nv.get_patch_by_id('10').set_edgecolor('black')\nv.get_patch_by_id('10').set_facecolor('white')\n\nv.get_label_by_id('11').set_text('$A \\cap B$')\nv.get_patch_by_id('11').set_linewidth(2)\nv.get_patch_by_id('11').set_edgecolor('black')\nv.get_patch_by_id('11').set_facecolor('#ff0000')\n```\n\n\n```python\nfrom matplotlib_venn import venn2\nv = venn2(subsets = (2, 2, 1));\nv.get_label_by_id('01').set_text('')\nv.get_patch_by_id('01').set_linewidth(2)\nv.get_patch_by_id('01').set_edgecolor('black')\nv.get_patch_by_id('01').set_facecolor('#ff0000')\n\nv.get_label_by_id('10').set_text('')\nv.get_patch_by_id('10').set_linewidth(2)\nv.get_patch_by_id('10').set_edgecolor('black')\nv.get_patch_by_id('10').set_facecolor('#ff0000')\n\nv.get_label_by_id('11').set_text('$A \\cup B$')\nv.get_patch_by_id('11').set_linewidth(2)\nv.get_patch_by_id('11').set_edgecolor('black')\nv.get_patch_by_id('11').set_facecolor('#ff0000')\n```\n\nJohn Venn (1834 - 1923) was an English logician and philosopher. He introduced the diagrams that would later bear his name in an 1880 paper entitled *On the Diagrammatic and Mechanical Representation of Propositions and Reasonings*.\n\n

\n

\n\n
\n\nThere is a stained glass window at Gonville and Caius College, Cambridge, where Venn studied and worked, commemorating Venn and the Venn diagram.\n\n

\n

\n\n
\n\nThe union and intersection may be extended to more than two sets. For example, let $G$ be the set of Greek uppercase letter glyphs,\n\n$$G = \\{A, B, \\Gamma, \\Delta, E, Z, H, \\Theta, I, K, \\Lambda, M, N, \\Xi, O, \\Pi, P, \\Sigma, T, Y, \\Phi, X, \\Psi, \\Omega\\},$$\n\n$E$ be the set of English uppercase letter glyphs,\n\n$$E = \\{A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z\\},$$\n\nand $R$ be the set of Russian uppercase letter glyphs,\n\n$$R = \\{\\text{А, Б, В, Г, Д, Е, Ё, Ж, З, И, Й, К, Л, М, Н, О, П, Р, С, Т, У, Ф, Х, Ц, Ч, Ш, Щ, Ъ, Ы, Ь, Э, Ю, Я}\\}$$.\n\nThen their intersection is given by\n\n$$G \\cap E \\cap R = \\{A, B, E, H, K, M, O, P, T, X, Y\\}.$$\n\n\n

\n

\n\n
\n\nWe can also take unions and intersections of infinitely many sets. Let $N_2$ denote the set of positive multiples of 2,\n$$N_2 = \\{2, 4, 6, 8, 10, 12, \\ldots\\},$$\n$N_3$ denote the set of positive multiples of 3,\n$$N_3 = \\{3, 6, 9, 12, 15, 18, \\ldots\\},$$\nand so on. Then we can write\n$$\\mathbb{N} = \\{1\\} \\cup \\bigcup_{i=2}^{\\infty} N_i.$$\nSince here we have taken a union of countably many sets (we can enumerate $N_2, N_3, N_4, \\ldots$), we refer to $\\bigcup_{i=2}^{\\infty} N_i$ as a **countable union**.\n\nIt is also possible to define uncountable, or **arbitrary**, unions and intersections.\n\nUnions and intersections are connected by the following relations:\n$$\n(A \\cup B) \\cap C = (A \\cap C) \\cup (B \\cap C), \\\\\n(A \\cap B) \\cup C = (A \\cup C) \\cap (B \\cup C).\n$$\n\n## Set difference, De Morgan's laws\n\nAnother important operation on sets is the **set difference**,\n$$A \\setminus B = \\{x \\, | \\, x \\in A \\text{ and } x \\notin B\\}.$$\n\nIf we assume that all the sets that we are considering are subsets of some large set $\\Omega$, we may write $A^{\\complement}$, $A'$, or $\\overline{A}$ instead of $\\Omega \\setminus A$ and refer to $\\Omega \\setminus A$ as the **complement** of $A$ (in $\\Omega$).\n\nThe following relations, known as **De Morgan's laws**, so named after the 19-th century British mathematician Augustus De Morgan, play an important part in **set theory**:\n$$\\overline{A \\cup B} = \\overline{A} \\cap \\overline{B},$$\nand\n$$\\overline{A \\cap B} = \\overline{A} \\cup \\overline{B}.$$\n\nThey can be generalised to arbitrary unions and intersections of infinitely many sets.\n\nHere is an exercise for you: *prove De Morgan's laws*.\n\nAssume that an element belongs to the set on the left-hand side and show that it also belongs to the set on the right-hand side (so the set on the left-hand side is a subset of the set on the right-hand side). Then assume that an element belongs to the set on the right-hand side and show that it also belongs to the set on the left-hand side (so the set on the right-hand side is a subset of the set on the left-hand side). If two sets are subsets of each other, then they are equal.\n\n## Cartesian products\n\nThe Cartesian product of two sets $A$ and $B$, written $A \\times B$, is the set of all ordered pairs $(a, b)$ where $a \\in A$ and $b \\in B$.\n\nFor example, the Cartesian product of the sets $A = \\{\\text{foo}, \\text{bar}, \\text{baz}\\}$ and $B = \\{3, 12\\}$ is the set\n$$A \\times B = \\{(\\text{foo}, 3), (\\text{bar}, 3), (\\text{baz}, 3), (\\text{foo}, 12), (\\text{bar}, 12), (\\text{baz}, 12)\\}.$$\n\nAs another example, consider the 2-dimensional plane, the set of pairs $(x, y)$ with $x \\in \\mathbb{R}$, $y \\in \\mathbb{R}$.\n\nMore generally, Cartesian products can be defined for $n \\in \\mathbb{N}$ sets. For example, the 3-dimensional space, the set of triples $(x, y, z)$, $x \\in \\mathbb{R}$, $y \\in \\mathbb{R}$, $z \\in \\mathbb{R}$, is a 3-fold Cartesian product $\\mathbb{R}^3 = \\mathbb{R} \\times \\mathbb{R} \\times \\mathbb{R}$.\n\n

\n

\n\n
\n\n## Functions\n\nA **binary relation** *R* between a set $X$ (the **set of departure**) and a set $Y$ (the **set of destination** or **codomain**) is specified by its **graph**, $G$, which is a set of ordered pairs $(x, y)$, a subset of the cartesian product $X \\times Y$. The binary relation is also known as a **mapping** or **correspondence**.\n\nThe statement $(x, y) \\in G$ is read as **\"$x$ is $R$-related to $y$\"** and is denoted $xRy$ or $R(x, y)$. The order is important: $xRy$ does not necessarily imply $yRx$ for a particular binary relation $R$.\n\nIf $R$ is a binary relation between $X$ and $Y$, then the set $\\{y \\in Y \\,|\\, xRy \\text{ for some } x \\in X\\}$ is called the **image** or **range**, of $R$. The set $\\{x \\in X \\,|\\, xRy \\text{ for some } y \\in Y\\}$ is called the **domain** of $R$.\n\nA **function** $f$ from a set $X$ to a set $Y$ (we sometimes write $f: X \\rightarrow Y$) is a special case of a binary relation: it is defined by a set $G \\subseteq X \\times Y$ of ordered pairs $(x, y)$ such that, for *each* element $x \\in X$ there corresponds *one, and only one,* pair $(x, y) \\in G$, and we write $f(x) = y$ or $f: x \\mapsto y$.\n\nSuppose that $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$.\n\nIs the binary relation $f: A \\rightarrow B$ defined by $G_f = \\{(1, b), (2, a)\\}$ a function?\n\n\n\n\n\n
*x**f(x)*
$1$$b$
$2$$a$
\n\nIndeed, it is a function: to *each* element of $x$, $f$ maps *exactly one* element of $B$.\n\nSuppose that $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$, as before.\n\nIs the binary relation $g: A \\rightarrow B$ defined by $G_g = \\{(1, b), (1, a), (2, a)\\}$ a function?\n\n\n\n\n\n\n
*x**g(x)*
$1$$b$
$1$$a$
$2$$a$
\n\nNo, it isn't: two distinct elements of $B$, $a, b \\in B$, are mapped to $1 \\in A$, so $g$ is not a function by definition.\n\nSuppose that $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$, as before.\n\nIs the binary relation $h: A \\rightarrow B$ defined by $G_h = \\{(2, a)\\}$ a function?\n\n\n\n\n
*x**h(x)*
$2$$a$
\n\nNo, it isn't: $h$ doesn't map any element of $B$ to $1 \\in A$.\n\nSuppose that $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$, as before.\n\nIs the binary relation $\\alpha: A \\rightarrow B$ defined by $G_{\\alpha} = \\{(1, a), (2, a)\\}$ a function?\n\n\n\n\n\n
*x**$\\alpha$(x)*
$1$$a$
$2$$a$
\n\nIndeed it is: to *each* element of $A$ there corresponds *exactly one* element of $B$.\n\nNow, consider the binary relation $s: \\mathbb{R} \\rightarrow \\mathbb{R}$ defined, for all $x \\in \\mathbb{R}$, by $s(x) = x^2$ or, in another notation, $s: x \\mapsto x^2$:\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nxs = np.linspace(-10., 10., 50)\nplt.plot(xs, [x*x for x in xs]);\nplt.xlabel('x')\nplt.ylabel('s(x)');\n```\n\nIs this a function?\n\nIndeed, $s$ is a function: to *each* $x \\in \\mathbb{R}$ there corresponds one, and only one (thus exactly one) $s(x) \\in \\mathbb{R}$.\n\nWhat about the binary relation $r: \\mathbb{R} \\rightarrow \\mathbb{R}$ defined, for all $x \\in \\mathbb{R}$, by $r(x) = \\sqrt{x}$?\n\nFirst of all, this definition doesn't quite make sense. $\\sqrt{\\cdot}$ is defined only for nonnegative real numbers.\n\nSuppose we redefine $r: \\mathbb{R} \\rightarrow \\mathbb{R}$: for all $x \\geq 0$, $r(x) = \\sqrt{x}$.\n\nIs this now a function?\n\nIt's not a function $r: \\mathbb{R} \\rightarrow \\mathbb{R}$, since it does not define a value $f(x)$ for *all* $x \\in \\mathbb{R}$, only for those $x$ that are nonnegative.\n\nHow could we fix the definition of $r$ so that it is a function?\n\nOne way to do it is to define it as $r: \\mathbb{R}_{\\geq 0} \\rightarrow \\mathbb{R}$, where $\\mathbb{R}_{\\geq 0}$ is the set of *nonnegative* real numbers.\n\n\n```python\nxs = np.linspace(-10., 10., 50)\nxs = [x for x in xs if x >= 0]\nplt.plot(xs, [np.sqrt(x) for x in xs]);\nplt.xlabel('x')\nplt.ylabel('s(x)');\n```\n\n## Image and inverse image\n\nLet $f: X \\rightarrow Y$ be a function and $A \\subseteq X$. Then the **image** $f[A]$ of $A$ under $f$ is the set $$f[A] = \\{y \\in Y \\,|\\, y = f(x) \\text{ for some } x \\in A\\}.$$\n\nThis is consistent with the definition of the **image** of a function given above: the image of the function $f$ is the image $f[X]$ of the entire set $X$.\n\nLet $f: X \\rightarrow Y$ be a function and $B \\subseteq Y$. Then the **preimage** or **inverse image** of $B$ under $f$ is the set $$f^{-1}[B] = \\{x \\in X \\,|\\, f(x) \\in B\\}.$$\n\nFor example, for $f: \\mathbb{R} \\rightarrow \\mathbb{R}$, $f: x \\mapsto x^2$, the inverse image of the singleton set $\\{4\\}$ is the set $\\{-2, 2\\}$. The inverse image of the set $\\{4, 9\\}$ is the set $\\{-3, -2, 2, 3\\}$.\n\nThe inverse image of the union of two sets is equal to the union of their inverse images:\n$$f^{-1}[A \\cup B] = f^{-1}[A] \\cup f^{-1}[B].$$\n\nExercise: How would you prove this?\n\nThe inverse image of the intersection of two sets is equal to the intersection of their inverse images:\n$$f^{-1}[A \\cap B] = f^{-1}[A] \\cap f^{-1}[B].$$\n\nThe image of the union of two sets is equal to the union of their images:\n$$f[A \\cup B] = f[A] \\cup f[B].$$\n\nIs the image of the intersection of two sets equal to the intersection of their images:\n$$f[A \\cap B] \\overset{?}{=} f[A] \\cap f[B].$$\n\nThe image of the intersection of two sets is, in general, *not* equal to the intersection of their images:\n$$f[A \\cap B] \\neq f[A] \\cap f[B].$$\n\nTo see this, consider $f: \\mathbb{R} \\times \\mathbb{R} \\rightarrow \\mathbb{R}$, defined by $f: (x, y) \\mapsto x$, a **projection** on the $x$-plane.\n\nDefine $A = \\{(x, 0) \\,|\\, 0 \\leq x \\leq 1\\}$ and $A = \\{(x, 1) \\,|\\, 0 \\leq x \\leq 1\\}$.\n\nThe two sets do not intersect, or, in other words, their intersection is the so-called **empty set**: $A \\cap B = \\{\\} = \\emptyset$.\n\nHowever, the images of the two sets coincide: $f(A) = f(B) = \\{x \\,|\\, 0 \\leq x \\leq 1\\}$.\n\nWe have just disproven\n$$f[A \\cap B] = f[A] \\cap f[B],$$\nequivalently, we have just proven\n$$f[A \\cap B] \\neq f[A] \\cap f[B].$$\nby producing a particular **counterexample** — this is yet another proof method, very common in mathematics. □\n\n## One-to-one, onto, bijections, and inverse functions\n\nA function $f: X \\rightarrow Y$ is **injective** or **one-to-one** if each possible element $y \\in Y$ of its codomain $y$ is mapped to by at most one argument $x \\in X$. We call **injective** functions **injections**.\n\nIt is **surjective** or **onto** if each possible element $y \\in Y$ is mapped to by at least one argument $x \\in X$. We call **surjective** functions **surjections**.\n\nIt is **bijective** if it is both injective and surjective (one-to-one and onto). We call such functions **bijections** or **one-to-one correspondences**.\n\nA function $f: X \\rightarrow Y$ is **invertible** if there exists a function $g: Y \\rightarrow X$ such that, for all $y \\in Y$, $g(f(x)) = x$. We call $g$ an inverse of $f$ and sometimes denote it by $f^{-1}$.\n\nOne can check that a function is invertible iff it is a bijection.\n\nSuppose that $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$.\n\nIs the function $f: A \\rightarrow B$ defined by $G_f = \\{(1, b), (2, a)\\}$ one-to-one, onto, a bijection, invertible?\n\n\n\n\n\n
*x**f(x)*
$1$$b$
$2$$a$
\n\n* It is one-to-one, since for each element it its image, $f[A]$, there corresponds a single element of $A$: to $a$, there corresponds 2, and to $b$, there corresponds 1.\n\n* It is *not* onto, since no element of $A$ is mapped to $c \\in B$.\n\n* Since the function is *not* one-to-one *and* onto, but only one-to-one, it is not a bijection.\n\n* Therefore it is not invertible. Indeed we could not define the inverse function $f^{-1}: B \\rightarrow A$ since we wouldn't be able to map $c \\in B$ to anything — it wouldn't be a function.\n\nAs before, $A = \\{1, 2\\}$, $B = \\{a, b, c\\}$.\n\nIs the function $\\alpha: A \\rightarrow B$ defined by $G_{\\alpha} = \\{(1, a), (2, a)\\}$ one-to-one, onto, a bijection, invertible?\n\n\n\n\n\n
*x**$\\alpha$(x)*
$1$$a$
$2$$a$
\n\n* It is *not* one-to-one, since for $a \\in f[A]$, there correspond two elements of $A$: 1 and 2: $f(1) = f(2) = a$.\n* It is *not* onto, since no element of $A$ is mapped to $b \\in B$, nor is there an element of $A$ mapped to $c \\in B$.\n* Since the function is *not* one-to-one *and* onto, in fact, it is neither, it is not a bijection.\n* Therefore it is not invertible.\n\nIn fact, is there *any* bijection (and therefore *any* invertible function) between $A = \\{1, 2\\}$ and $B = \\{a, b, c\\}$?\n\nSince $|A| \\neq |B|$ there isn't!\n\nBut between $C = \\{1, 2\\}$ and $D = \\{a, b\\}$ there are two bijections. One is\n$\\beta: C \\rightarrow D$ defined by $G_{\\beta} = \\{(1, a), (2, b)\\}$:\n\n\n\n\n\n
*x**$\\beta$(x)*
$1$$a$
$2$$b$
\n\nIts inverse is $\\beta^{-1}: D \\rightarrow C$ defined by $G_{\\beta^{-1}} = \\{(a, 1), (b, 2)\\}$:\n\n\n\n\n\n
*y**$\\beta^{-1}$(y)*
$a$$1$
$b$$2$
\n\nThe other bijection between $C = \\{1, 2\\}$ and $D = \\{a, b\\}$ is $\\gamma: C \\rightarrow D$ defined by $G_{\\gamma} = \\{(1, b), (2, a)\\}$:\n\n\n\n\n\n
*x**$\\gamma$(x)*
$1$$b$
$2$$a$
\n\nIts inverse is $\\gamma^{-1}: D \\rightarrow C$ defined by $G_{\\gamma^{-1}} = \\{(a, 2), (b, 1)\\}$:\n\n\n\n\n\n
*y**$\\gamma^{-1}$(y)*
$a$$2$
$b$$1$
\n\nSince $\\gamma$ is a bijection, so is $\\gamma^{-1}$, and it is therefore invertible; the inverse of $\\gamma^{-1}$ is $\\gamma$.\n\n## How natural numbers can be constructed from sets\n\nWe have mentioned that sets are the \"most general\" mathematical objects. But then we informally introduced other objects, such as ordered pairs. At first sight, ordered pairs are different from sets. Why do we then say that sets are the \"most general\" mathematical objects?\n\nIn fact, ordered pairs can be expressed as sets. There are several ways to do this, one of them the so-called **Kuratowski's definition** proposed in 1921 by Kazimierz Kuratowski:\n$$(a, b) = \\{\\{a\\}, \\{a, b\\}\\}.$$\n\nThis definition can be used even when the two elements of the pair are identical:\n$$(a, a) = \\{\\{a\\}, \\{a, a\\}\\} = \\{\\{a\\}, \\{a\\}\\} = \\{\\{a\\}\\}.$$\n\nTriples can be defined as nested pairs:\n$$(a, b, c) = (a, (b, c)),$$\nand so on.\n\nBut what about *numbers*? Surely there is no way to use sets to define numbers?\n\nIn fact, we can define natural numbers and zero as follows:\n$$\n0 = \\{\\} = \\emptyset, \\\\\n1 = \\{0\\} = \\{\\emptyset\\}, \\\\\n2 = \\{0, 1\\} = \\{\\emptyset, \\{\\emptyset\\}\\}, \\\\\n3 = \\{0, 1, 2\\} = \\{\\emptyset, \\{\\emptyset\\}, \\{\\emptyset, \\{\\emptyset\\}\\}\\}, \\\\\n\\vdots\n$$\n\nThis definition is part of the Zermelo-Fraenkel (ZF) set theory. We can then use the **Dedekind-Peano axioms** to define arithmetic for natural numbers in terms of set theory.\n\nHaving constructed $\\mathbb{N}$, we can then construct the rationals $\\mathbb{Q}$, the reals $\\mathbb{R}$, building on the foundation of set theory.\n\nProceeding onwards, we obtain... the rest of mathematics!\n", "meta": {"hexsha": "39603de65c228942720f1efdc906d648b0977dfd", "size": 140465, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tsa/src/jupyter/python/foundations/set-theory.ipynb", "max_stars_repo_name": "mikimaus78/ml_monorepo", "max_stars_repo_head_hexsha": "b2c2627ff0e86e27f6829170d0dac168d8e5783b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 51, "max_stars_repo_stars_event_min_datetime": "2019-02-01T19:43:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T09:07:03.000Z", "max_issues_repo_path": "tsa/src/jupyter/python/foundations/set-theory.ipynb", "max_issues_repo_name": "mikimaus78/ml_monorepo", "max_issues_repo_head_hexsha": "b2c2627ff0e86e27f6829170d0dac168d8e5783b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-02-23T18:54:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-09T01:30:32.000Z", "max_forks_repo_path": "tsa/src/jupyter/python/foundations/set-theory.ipynb", "max_forks_repo_name": "mikimaus78/ml_monorepo", "max_forks_repo_head_hexsha": "b2c2627ff0e86e27f6829170d0dac168d8e5783b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2019-02-08T02:00:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T23:17:00.000Z", "avg_line_length": 69.2969906265, "max_line_length": 23418, "alphanum_fraction": 0.7271562311, "converted": true, "num_tokens": 15507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.16171350136883797}} {"text": "# CS109B Data Science 2: Advanced Topics in Data Science \n\n## Lab 4 - Bayesian Analysis\n\n**Harvard University**
\n**Spring 2020**
\n**Instructors:** Mark Glickman, Pavlos Protopapas, and Chris Tanner
\n**Lab Instructors:** Chris Tanner and Eleni Angelaki Kaxiras
\n**Content:** Eleni Angelaki Kaxiras\n\n---\n\n\n```python\n## RUN THIS CELL TO PROPERLY HIGHLIGHT THE EXERCISES\nimport requests\nfrom IPython.core.display import HTML\nstyles = requests.get(\"https://raw.githubusercontent.com/Harvard-IACS/2019-CS109B/master/content/styles/cs109.css\").text\nHTML(styles)\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\nimport pymc3 as pm\nfrom pymc3 import summary\n```\n\n WARNING (theano.configdefaults): g++ not available, if using conda: `conda install m2w64-toolchain`\n C:\\Users\\Jose\\Anaconda3\\envs\\cs109b\\lib\\site-packages\\theano\\configdefaults.py:560: UserWarning: DeprecationWarning: there is no c++ compiler.This is deprecated and with Theano 0.11 a c++ compiler will be mandatory\n warnings.warn(\"DeprecationWarning: there is no c++ compiler.\"\n WARNING (theano.configdefaults): g++ not detected ! Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string.\n WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport pandas as pd\n%matplotlib inline \n\nimport warnings\nwarnings.filterwarnings('ignore')\n```\n\n\n```python\nprint('Running on PyMC3 v{}'.format(pm.__version__))\n```\n\n Running on PyMC3 v3.8\n\n\n\n```javascript\n%%javascript\nIPython.OutputArea.auto_scroll_threshold = 20000;\n```\n\n\n \n\n\n\n\n## Learning Objectives\n\nBy the end of this lab, you should be able to:\n* Understand how probability distributions work.\n* Apply Bayes Rule in calculating probabilities.\n* Understand how to apply Bayesian analysis using PyMC3\n* Avoid getting fired when talking to your Bayesian employer.\n\n**This lab corresponds to Lectures 6, 7, and 8, and maps to Homework 3.**\n\n## Table of Contents\n\n1. The Bayesian Way of Thinking or Is this a Fair Coin?\n2. [Intro to `pyMC3`](#pymc3). \n3. [Bayesian Linear Regression](#blr).\n4. [Try this at Home: Example on Mining Disasters](#no4).\n\n## 1. The Bayesian way of Thinking\n\n```\nHere is my state of knowledge about the situation. Here is some data, I am now going to revise my state of knowledge.\n```\n\n
Table Exercise: Discuss the statement above with your table mates and make sure everyone understands what it means and what constitutes Bayesian way of thinking. Finally, count the Bayesians among you.
\n\n### A. Bayes Rule\n\n\\begin{equation}\n\\label{eq:bayes} \nP(A|\\textbf{B}) = \\frac{P(\\textbf{B} |A) P(A) }{P(\\textbf{B})} \n\\end{equation}\n\n$P(A|\\textbf{B})$ is the **posterior** distribution, prob(hypothesis | data) \n\n$P(\\textbf{B} |A)$ is the **likelihood** function, how probable is my data **B** for different values of the parameters\n\n$P(A)$ is the marginal probability to observe the data, called the **prior**, this captures our belief about the data before observing it.\n\n$P(\\textbf{B})$ is the marginal distribution (sometimes called marginal likelihood)\n\n
\n
Table Exercise: Solve the Monty Hall Paradox using Bayes Rule.
\n\n\n\nYou are invited to play a game. There are 3 doors behind **one** of which are the keys to a brand new red Tesla. There is a goat behind each of the other two. \n\nYou are asked to pick one door, and let's say you pick **Door1**. The host knows where the keys are. Of the two remaining closed doors, he will always open the door that has a goat behind it. He'll say \"I will do you a favor and open **Door2**\". So he opens Door2 inside which there is, of course, a goat. He now asks you, do you want to open the initial Door you chose or change to **Door3**? Generally, in this game, when you are presented with this choice should you swap the doors?\n\n**Initial Steps:**\n- Start by defining the `events` of this probabilities game. One definition is:\n \n - $A_i$: car is behind door $i$ \n \n - $B_i$ host opens door $i$\n \n$i\\in[1,2,3]$\n \n- In more math terms, the question is: is the probability that the price is behind **Door 1** higher than the probability that the price is behind **Door2**, given that an event **has occured**?\n\n### B. Bayes Rule written with Probability Distributions\n\nWe have data that we believe come from an underlying distribution of unknown parameters. If we find those parameters, we know everything about the process that generated this data and we can make inferences (create new data).\n\n\\begin{equation}\n\\label{eq:bayes} \nP(\\theta|\\textbf{D}) = \\frac{P(\\textbf{D} |\\theta) P(\\theta) }{P(\\textbf{D})} \n\\end{equation}\n\n#### But what is $\\theta \\;$?\n\n$\\theta$ is an unknown yet fixed set of parameters. In Bayesian inference we express our belief about what $\\theta$ might be and instead of trying to guess $\\theta$ exactly, we look for its **probability distribution**. What that means is that we are looking for the **parameters** of that distribution. For example, for a Poisson distribution our $\\theta$ is only $\\lambda$. In a normal distribution, our $\\theta$ is often just $\\mu$ and $\\sigma$.\n\n### C. A review of Common Probability Distributions\n\n#### Discrete Distributions\n\nThe random variable has a **probability mass function (pmf)** which measures the probability that our random variable will take a specific value $y$, denoted $P(Y=y)$.\n\n- **Bernoulli** (binary outcome, success has probability $\\theta$, $one$ trial):\n$\nP(Y=k) = \\theta^k(1-\\theta)^{1-k}\n$\n
\n- **Binomial** (binary outcome, success has probability $\\theta$, $n$ trials):\n\\begin{equation}\nP(Y=k) = {{n}\\choose{k}} \\cdot \\theta^k(1-\\theta)^{n-k}\n\\end{equation}\n\n*Note*: Binomial(1,$p$) = Bernouli($p$)\n
\n- **Negative Binomial**\n
\n- **Poisson** (counts independent events occurring at a rate)\n\\begin{equation}\nP\\left( Y=y|\\lambda \\right) = \\frac{{e^{ - \\lambda } \\lambda ^y }}{{y!}}\n\\end{equation}\ny = 0,1,2,...\n
\n- **Discrete Uniform** \n
\n- **Categorical, or Multinulli** (random variables can take any of K possible categories, each having its own probability; this is a generalization of the Bernoulli distribution for a discrete variable with more than two possible outcomes, such as the roll of a die)\n
\n- **Dirichlet-multinomial** (a generalization of the beta distribution for many variables)\n\n#### Continuous Distributions\n\nThe random variable has a **probability density function (pdf)**.\n- **Uniform** (variable equally likely to be near each value in interval $(a,b)$)\n\\begin{equation}\nP(X = x) = \\frac{1}{b - a}\n\\end{equation}\nanywhere within the interval $(a, b)$, and zero elsewhere.\n
\n- **Normal** (a.k.a. Gaussian)\n\\begin{equation}\nX \\sim \\mathcal{N}(\\mu,\\,\\sigma^{2})\n\\end{equation} \n\n A Normal distribution can be parameterized either in terms of precision $\\tau$ or standard deviation ($\\sigma^{2}$. The link between the two is given by\n\\begin{equation}\n\\tau = \\frac{1}{\\sigma^{2}}\n\\end{equation}\n - Mean $\\mu$\n - Variance $\\frac{1}{\\tau}$ or $\\sigma^{2}$\n - Parameters: `mu: float`, `sigma: float` or `tau: float`\n
\n- **Beta** (variable ($\\theta$) taking on values in the interval $[0,1]$, and parametrized by two positive parameters, $\\alpha$ and $\\beta$ that control the shape of the distribution. \n \n*Note:*Beta is a good distribution to use for priors (beliefs) because its range is $[0,1]$ which is the natural range for a probability and because we can model a wide range of functions by changing the $\\alpha$ and $\\beta$ parameters.\n\n\\begin{equation}\n\\label{eq:beta} \nP(\\theta) = \\frac{1}{B(\\alpha, \\beta)} {\\theta}^{\\alpha - 1} (1 - \\theta)^{\\beta - 1} \\propto {\\theta}^{\\alpha - 1} (1 - \\theta)^{\\beta - 1}\n\\end{equation}\n\n\nwhere the normalisation constant, $B$, is a beta function of $\\alpha$ and $\\beta$,\n\n\n\\begin{equation}\nB(\\alpha, \\beta) = \\int_{t=0}^1 t^{\\alpha - 1} (1 - t)^{\\beta - 1} dt.\n\\end{equation}\n
\n- **Exponential**\n
\n- **Gamma**\n\n\n\n #### Code Resources:\n - Statistical Distributions in numpy/scipy: [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html)\n - Statistical Distributions in pyMC3: [distributions in PyMC3](https://docs.pymc.io/api/distributions.html) (we will see those below).\n\n
Exercise: Plot a Discrete variable
\n\nChange the value of $\\mu$ in the Poisson PMF and see how the plot changes. Remember that the y-axis in a discrete probability distribution shows the probability of the random variable having a specific value in the x-axis.\n\n\\begin{equation}\nP\\left( X=k \\right) = \\frac{{e^{ - \\mu } \\mu ^k }}{{k!}}\n\\end{equation}\n\n**stats.poisson.pmf(x, mu)** $\\mu$(mu) is our $\\theta$ in this case.\n\n\n```python\nplt.style.use('seaborn-darkgrid')\nx = np.arange(0, 30)\nfor m in [0.5, 3, 8]:\n pmf = stats.poisson.pmf(x, m)\n plt.plot(x, pmf, 'o', alpha=0.5, label='$\\mu$ = {}'.format(m))\nplt.xlabel('random variable', fontsize=12)\nplt.ylabel('probability', fontsize=12)\nplt.legend(loc=1)\nplt.ylim=(-0.1)\nplt.show()\n```\n\n\n```python\n# same for binomial\nplt.style.use('seaborn-darkgrid')\nx = np.arange(0, 22)\nns = [10, 17]\nps = [0.5, 0.7]\nfor n, p in zip(ns, ps):\n pmf = stats.binom.pmf(x, n, p)\n plt.plot(x, pmf, 'o', alpha=0.5, label='n = {}, p = {}'.format(n, p))\nplt.xlabel('x', fontsize=14)\nplt.ylabel('f(x)', fontsize=14)\nplt.legend(loc=1)\nplt.show()\n```\n\n\n```python\n# discrete uniform\nplt.style.use('seaborn-darkgrid')\nls = [0]\nus = [3] # watch out, this number can only be integer!\nfor l, u in zip(ls, us):\n x = np.arange(l, u+1)\n pmf = [1.0 / (u - l + 1)] * len(x)\n plt.plot(x, pmf, '-o', label='lower = {}, upper = {}'.format(l, u))\nplt.xlabel('x', fontsize=12)\nplt.ylabel('probability P(x)', fontsize=12)\nplt.legend(loc=1)\nplt.show()\n```\n\n
Exercise: Plot a continuous variable
\n\nChange the value of $\\mu$ in the Uniform PDF and see how the plot changes.\n \nRemember that the y-axis in a continuous probability distribution does not shows the actual probability of the random variable having a specific value in the x-axis because that probability is zero!. Instead, to see the probability that the variable is within a small margin we look at the integral below the curve of the PDF.\n\nThe uniform is often used as a noninformative prior.\n\n```\nUniform - numpy.random.uniform(a=0.0, b=1.0, size)\n```\n\n$\\alpha$ and $\\beta$ are our parameters. `size` is how many tries to perform.\nOur $\\theta$ is basically the combination of the parameters a,b. We can also call it \n\\begin{equation}\n\\mu = (a+b)/2\n\\end{equation}\n\n\n```python\nfrom scipy.stats import uniform\n\nr = uniform.rvs(size=1000)\nplt.plot(r, uniform.pdf(r),'r-', lw=5, alpha=0.6, label='uniform pdf')\nplt.hist(r, density=True, histtype='stepfilled', alpha=0.2)\nplt.ylabel(r'probability density')\nplt.xlabel(f'random variable')\nplt.legend(loc='best', frameon=False)\nplt.show()\n```\n\n\n```python\nfrom scipy.stats import beta\n\nalphas = [0.5, 1.5, 3.0]\nbetas = [0.5, 1.5, 3.0]\nx = np.linspace(0, 1, 1000) \ncolors = ['red', 'green', 'blue']\n\nfig, ax = plt.subplots(figsize=(8, 5))\n\nfor a, b, colors in zip(alphas, betas, colors):\n dist = beta(a, b)\n plt.plot(x, dist.pdf(x), c=colors,\n label=f'a={a}, b={b}')\n\nax.set_ylim(0, 3)\n\nax.set_xlabel(r'$\\theta$')\nax.set_ylabel(r'$p(\\theta|\\alpha,\\beta)$')\nax.set_title('Beta Distribution')\n\nax.legend(loc='best')\nfig.show();\n```\n\n\n```python\nplt.style.use('seaborn-darkgrid')\nx = np.linspace(-5, 5, 1000)\nmus = [0., 0., 0., -2.]\nsigmas = [0.4, 1., 2., 0.4]\nfor mu, sigma in zip(mus, sigmas):\n pdf = stats.norm.pdf(x, mu, sigma)\n plt.plot(x, pdf, label=r'$\\mu$ = '+ f'{mu},' + r'$\\sigma$ = ' + f'{sigma}') \nplt.xlabel('random variable', fontsize=12)\nplt.ylabel('probability density', fontsize=12)\nplt.legend(loc=1)\nplt.show()\n```\n\n\n```python\nplt.style.use('seaborn-darkgrid')\nx = np.linspace(-5, 5, 1000)\nmus = [0., 0., 0., -2.] # mean\nsigmas = [0.4, 1., 2., 0.4] # std\nfor mu, sigma in zip(mus, sigmas):\n plt.plot(x, uniform.pdf(x, mu, sigma), lw=5, alpha=0.4, \\\n label=r'$\\mu$ = '+ f'{mu},' + r'$\\sigma$ = ' + f'{sigma}')\nplt.xlabel('random variable', fontsize=12)\nplt.ylabel('probability density', fontsize=12)\nplt.legend(loc=1)\nplt.show()\n```\n\n### D. Is this a Fair Coin?\n\nWe do not want to promote gambling but let's say you visit the casino in **Monte Carlo**. You want to test your theory that casinos are dubious places where coins have been manipulated to have a larger probability for tails. So you will try to estimate how fair a coin is based on 100 flips.
\nYou begin by flipping the coin. You get either Heads ($H$) or Tails ($T$) as our observed data and want to see if your posterior probabilities change as you obtain more data, that is, more coin flips. A nice way to visualize this is to plot the posterior probabilities as we observe more flips (data). \n\nWe will be using Bayes rule. $\\textbf{D}$ is our data.\n\n\\begin{equation}\n\\label{eq:bayes} \nP(\\theta|\\textbf{D}) = \\frac{P(\\textbf{D} |\\theta) P(\\theta) }{P(\\textbf{D})} \n\\end{equation}\n\nIn the case of a coin toss when we observe $k$ heads in $n$ tosses:\n\\begin{equation}\n\\label{eq:bayes} \nP(\\theta|\\textbf{k}) = Beta(\\alpha + \\textbf{k}, \\beta + n - \\textbf{k}) \n\\end{equation}\n\nwe can say that $\\alpha$ and $\\beta$ play the roles of a \"prior number of heads\" and \"prior number of tails\".\n\n\n```python\n# play with the priors - here we manually set them but we could be sampling from a separate Beta\ntrials = np.array([0, 1, 3, 5, 10, 15, 20, 100, 200, 300])\nheads = np.array([0, 1, 2, 4, 8, 10, 10, 50, 180, 150])\nx = np.linspace(0, 1, 100)\n\n# for simplicity we set a,b=1\n\nplt.figure(figsize=(10,8))\nfor k, N in enumerate(trials):\n sx = plt.subplot(len(trials)/2, 2, k+1)\n a = 1\n b = 1\n posterior = stats.beta.pdf(x, a + heads[k], b + trials[k] - heads[k]) \n plt.plot(x, posterior, alpha = 0.5, label=f'{trials[k]} tosses\\n {heads[k]} heads');\n plt.fill_between(x, 0, posterior, color=\"#348ABD\", alpha=0.4) \n plt.legend(loc='upper left', fontsize=10)\n plt.legend()\n plt.autoscale(tight=True)\n \nplt.suptitle(\"Posterior probabilities for coin flips\", fontsize=15);\nplt.tight_layout()\nplt.subplots_adjust(top=0.88)\n```\n\n [Top](#top)\n\n## 2. Introduction to `pyMC3`\n \nPyMC3 is a Python library for programming Bayesian analysis, and more specifically, data creation, model definition, model fitting, and posterior analysis. It uses the concept of a `model` which contains assigned parametric statistical distributions to unknown quantities in the model. Within models we define random variables and their distributions. A distribution requires at least a `name` argument, and other `parameters` that define it. You may also use the `logp()` method in the model to build the model log-likelihood function. We define and fit the model.\n\nPyMC3 includes a comprehensive set of pre-defined statistical distributions that can be used as model building blocks. Although they are not meant to be used outside of a `model`, you can invoke them by using the prefix `pm`, as in `pm.Normal`. \n\n#### Markov Chain Monte Carlo (MCMC) Simulations\n\nPyMC3 uses the **No-U-Turn Sampler (NUTS)** and the **Random Walk Metropolis**, two Markov chain Monte Carlo (MCMC) algorithms for sampling in posterior space. Monte Carlo gets into the name because when we sample in posterior space, we choose our next move via a pseudo-random process. NUTS is a sophisticated algorithm that can handle a large number of unknown (albeit continuous) variables.\n\n\n```python\nwith pm.Model() as model:\n z = pm.Normal('z', mu=0., sigma=5.) \n x = pm.Normal('x', mu=z, sigma=1., observed=5.) \nprint(x.logp({'z': 2.5})) \nprint(z.random(10, 100)[:10]) \n```\n\n -4.043938533204672\n [ 3.21027345 -9.88943966 3.56132318 12.99151964 -0.12312991 0.17071064\n 0.89774742 -9.30987855 2.1307332 -8.02704872]\n\n\n**References**:\n\n- *Salvatier J, Wiecki TV, Fonnesbeck C. 2016. Probabilistic programming in Python using PyMC3. PeerJ Computer Science 2:e55* [(https://doi.org/10.7717/peerj-cs.55)](https://doi.org/10.7717/peerj-cs.55)\n- [Distributions in PyMC3](https://docs.pymc.io/api/distributions.html)\n- [More Details on Distributions](https://docs.pymc.io/developer_guide.html)\n\nInformation about PyMC3 functions including descriptions of distributions, sampling methods, and other functions, is available via the `help` command.\n\n\n```python\n#help(pm.Poisson)\n```\n\n [Top](#top)\n\n## 3. Bayesian Linear Regression\n\nLet's say we want to predict outcomes Y as normally distributed observations with an expected value $mu$ that is a linear function of two predictor variables, $\\bf{x}_1$ and $\\bf{x}_2$.\n\n\\begin{equation}\n\\mu = \\alpha + \\beta_1 \\bf{x}_1 + \\beta_2 x_2 \n\\end{equation}\n\n\\begin{equation}\nY \\sim \\mathcal{N}(\\mu,\\,\\sigma^{2})\n\\end{equation} \n\nwhere $\\sigma^2$ represents the measurement error. \n\nIn this example, we will use $\\sigma^2 = 10$\n\nWe also choose the parameters as normal distributions:\n\n\\begin{eqnarray}\n\\alpha \\sim \\mathcal{N}(0,\\,10) \\\\\n\\beta_i \\sim \\mathcal{N}(0,\\,10) \\\\\n\\sigma^2 \\sim |\\mathcal{N}(0,\\,10)|\n\\end{eqnarray} \n\nWe will artificially create the data to predict on. We will then see if our model predicts them correctly.\n\n\n```python\n# Initialize random number generator\nnp.random.seed(123)\n\n# True parameter values\nalpha, sigma = 1, 1\nbeta = [1, 2.5]\n\n# Size of dataset\nsize = 100\n\n# Predictor variable\nX1 = np.linspace(0, 1, size)\nX2 = np.linspace(0,.2, size)\n\n# Simulate outcome variable\nY = alpha + beta[0]*X1 + beta[1]*X2 + np.random.randn(size)*sigma\n\nfig, ax = plt.subplots(1,2, figsize=(10,6), sharex=True)\nax[0].scatter(X1,Y)\nax[1].scatter(X2,Y)\nax[0].set_xlabel(r'$x_1$', fontsize=14) \nax[0].set_ylabel(r'$Y$', fontsize=14)\nax[1].set_xlabel(r'$x_2$', fontsize=14) \nax[1].set_ylabel(r'$Y$', fontsize=14)\n```\n\n\n```python\nfrom pymc3 import Model, Normal, HalfNormal\n\nbasic_model = Model()\n\nwith basic_model:\n\n # Priors for unknown model parameters, specifically create stochastic random variables \n # with Normal prior distributions for the regression coefficients,\n # and a half-normal distribution for the standard deviation of the observations, σ.\n alpha = Normal('alpha', mu=0, sd=10)\n beta = Normal('beta', mu=0, sd=10, shape=2)\n sigma = HalfNormal('sigma', sd=1)\n\n # Expected value of outcome - posterior\n mu = alpha + beta[0]*X1 + beta[1]*X2\n\n # Likelihood (sampling distribution) of observations\n Y_obs = Normal('Y_obs', mu=mu, sd=sigma, observed=Y)\n```\n\n\n```python\n# model fitting with sampling\nfrom pymc3 import NUTS, sample, find_MAP\nfrom scipy import optimize\n\nwith basic_model:\n\n # obtain starting values via MAP\n start = find_MAP(fmin=optimize.fmin_powell)\n\n # instantiate sampler\n step = NUTS(scaling=start)\n\n # draw 2000 posterior samples\n trace = sample(2000, step, start=start)\n```\n\n logp = -164.5: 5%|▌ | 271/5000 [00:01<00:22, 208.69it/s] \n\n\n Optimization terminated successfully.\n Current function value: 164.496957\n Iterations: 6\n Function evaluations: 271\n\n\n Multiprocess sampling (4 chains in 4 jobs)\n NUTS: [sigma, beta, alpha]\n Sampling 4 chains, 0 divergences: 100%|██████████| 10000/10000 [14:32<00:00, 11.46draws/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nfrom pymc3 import traceplot\n\ntraceplot(trace);\n```\n\n\n```python\nresults = pm.summary(trace, \n var_names=['alpha', 'beta', 'sigma'])\nresults\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
meansdhpd_3%hpd_97%mcse_meanmcse_sdess_meaness_sdess_bulkess_tailr_hat
alpha1.0090.2290.5911.4390.0030.0024733.04733.04729.04248.01.00
beta[0]1.5451.996-2.0915.2990.0600.0451116.0982.01136.01261.01.01
beta[1]-0.0479.806-18.41518.2630.2960.2171095.01020.01118.01286.01.01
sigma1.1460.0800.9961.2960.0010.0017500.07400.07638.05353.01.00
\n
\n\n\n\nThis linear regression example is from the original paper on PyMC3: *Salvatier J, Wiecki TV, Fonnesbeck C. 2016. Probabilistic programming in Python using PyMC3. PeerJ Computer Science 2:e55 https://doi.org/10.7717/peerj-cs.55*\n\n [Top](#top)\n\n## 4. Try this at Home: Example on Mining Disasters\nWe will go over the classical `mining disasters from 1851 to 1962` dataset. \n\nThis example is from the [pyMC3 Docs](https://docs.pymc.io/notebooks/getting_started.html).\n\n\n```python\nimport pandas as pd\ndisaster_data = pd.Series([4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6,\n 3, 3, 5, 4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2, 5,\n 2, 2, 3, 4, 2, 1, 3, np.nan, 2, 1, 1, 1, 1, 3, 0, 0,\n 1, 0, 1, 1, 0, 0, 3, 1, 0, 3, 2, 2, 0, 1, 1, 1,\n 0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 1, 0, 2,\n 3, 3, 1, np.nan, 2, 1, 1, 1, 1, 2, 4, 2, 0, 0, 1, 4,\n 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1])\nfontsize = 12\nyears = np.arange(1851, 1962)\nplt.figure(figsize=(10,5))\n#plt.scatter(years, disaster_data); \nplt.bar(years, disaster_data)\nplt.ylabel('Disaster count', size=fontsize)\nplt.xlabel('Year', size=fontsize);\nplt.title('Was there a Turning Point in Mining disasters from 1851 to 1962?', size=15);\n```\n\n#### Building the model\n\n**Step1:** We choose the probability model for our experiment. Occurrences of disasters in the time series is thought to follow a **Poisson** process with a large **rate** parameter in the early part of the time series, and from one with a smaller **rate** in the later part. We are interested in locating the change point in the series, which perhaps is related to changes in mining safety regulations. \n\n```\ndisasters = pm.Poisson('disasters', rate, observed=disaster_data)\n```\n\nWe have two rates, `early_rate` if $t<=s$, and `late_rate` if $t>s$, where $s$ is the year the switch was made (a.k.a. the `switchpoint`). \n\n**Step2:** Choose a prior distributions of the two rates, what we believe the rates were before we observed the data, and the switchpoint. We choose Exponential.\n```\nearly_rate = pm.Exponential('early_rate', 1)\n```\n\nThe parameters of this model are: \n\n\n**Note:** Watch for missing values. Missing values are handled transparently by passing a MaskedArray or a pandas.DataFrame. Behind the scenes, another random variable, disasters.missing_values is created to model the missing values. If you pass a np.array with missing values you will get an error.\n\n\n```python\nwith pm.Model() as disaster_model:\n\n # discrete\n switchpoint = pm.DiscreteUniform('switchpoint', lower=years.min(), upper=years.max(), testval=1900)\n\n # Priors for pre- and post-switch rates number of disasters\n early_rate = pm.Exponential('early_rate', 1)\n late_rate = pm.Exponential('late_rate', 1)\n\n # our theta - allocate appropriate Poisson rates to years before and after current\n # switch is an `if` statement in puMC3\n rate = pm.math.switch(switchpoint >= years, early_rate, late_rate)\n\n # our observed data as a likelihood function of the `rate` parameters\n # shows how we think our data is distributed\n disasters = pm.Poisson('disasters', rate, observed=disaster_data)\n```\n\n#### Model Fitting\n\n\n```python\n# there are defaults but we can also more explicitly set the sampling algorithms\nwith disaster_model:\n \n # for continuous variables\n step1 = pm.NUTS([early_rate, late_rate])\n \n # for discrete variables\n step2 = pm.Metropolis([switchpoint, disasters.missing_values[0]] )\n\n trace = pm.sample(10000, step=[step1, step2])\n # try different number of samples\n #trace = pm.sample(5000, step=[step1, step2])\n```\n\n#### Posterior Analysis\n\nOn the left side plots we notice that our early rate is between 2.5 and 3.5 disasters a year. In the late period it seems to be between 0.6 and 1.2 so definitely lower.\n\nThe right side plots show the samples we drew to come to our conclusion.\n\n\n```python\npm.traceplot(trace, ['early_rate', 'late_rate', 'switchpoint'], figsize=(20,10));\n```\n\n\n```python\nresults = pm.summary(trace, \n var_names=['early_rate', 'late_rate', 'switchpoint'])\nresults\n```\n", "meta": {"hexsha": "a495de831bbbfba26cc0981d6cc19145a4c87e0c", "size": 490756, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/labs/lab04/notebook/cs109b_lab04_bayes.ipynb", "max_stars_repo_name": "jlopezra/2020-CS109B", "max_stars_repo_head_hexsha": "530b2fd9f3f225e8fe4ea38bdc42fbe0ebdea98e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/labs/lab04/notebook/cs109b_lab04_bayes.ipynb", "max_issues_repo_name": "jlopezra/2020-CS109B", "max_issues_repo_head_hexsha": "530b2fd9f3f225e8fe4ea38bdc42fbe0ebdea98e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/labs/lab04/notebook/cs109b_lab04_bayes.ipynb", "max_forks_repo_name": "jlopezra/2020-CS109B", "max_forks_repo_head_hexsha": "530b2fd9f3f225e8fe4ea38bdc42fbe0ebdea98e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 379.8421052632, "max_line_length": 211676, "alphanum_fraction": 0.926279047, "converted": true, "num_tokens": 8239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1614604046488889}} {"text": "```python\nimport numpy as np\nimport scipy.linalg\nimport matplotlib.pyplot as plt\nimport sympy\nfrom ipywidgets import interact\nfrom numba import jit\nimport time\nfrom sklearn import linear_model\nimport scipy.sparse\n```\n\n---\n\n# Item I\n\nWhat is a...\n\n---\n\n### a) Singular matrix\n\nA square matrix ($n\\times n$) $A$ is singular if there doesn't exist a square matrix ($n \\times n$) $B$ such that:\n$$\nBA = I_n \\, \\wedge \\, AB = I_n\n$$\nwhere $I_n$ is the $n \\times n$ identity matrix. $B$ is denoted as $A^{-1}$.\n\nThe following conditions for $A$ are equivalent:\n* $A$ is singular.\n* Its determinant is 0.\n* At least one of its eigenvalues is 0.\n* $\\text{rank}(A) < n $.\n* The equation $A\\vec{x} = \\vec{0}$ has infinite solutions.\n\nProperties:\n* The equation $A\\vec{x} = \\vec{b}$, with $\\vec{b}\\neq \\vec{0}$, can have zero or infinite solutions.\n* $(A^{-1})^{-1} = A$.\n* $(kA)^{-1} = k^{-1} A^{-1}$, if $k \\neq 0$.\n* $(A^T)^{-1} = (A^{-1})^T$\n* $\\text{det}(A^{-1}) = \\text{det}(A)^{-1}$\n* $A^{-1} = Q \\Lambda^{-1} Q^{-1}$, where $Q$ and $\\Lambda$ are matrices obtained from the [eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) of the matrix: $A = Q \\Lambda Q^{-1}$.\n\n### b) Vandermonde matrix\n\nIs a $m \\times n$ matrix with the following structure:\n$$\nV = \\begin{bmatrix}1&\\alpha _{1}&\\alpha _{1}^{2}&\\dots &\\alpha _{1}^{n-1}\\\\1&\\alpha _{2}&\\alpha _{2}^{2}&\\dots &\\alpha _{2}^{n-1}\\\\1&\\alpha _{3}&\\alpha _{3}^{2}&\\dots &\\alpha _{3}^{n-1}\\\\\\vdots &\\vdots &\\vdots &\\ddots &\\vdots \\\\1&\\alpha _{m}&\\alpha _{m}^{2}&\\dots &\\alpha _{m}^{n-1}\\end{bmatrix}\n$$\n\n* It evaluates a polynomial at a set of points. It maps the coefficients of a polynomial to the value it acquires at the $\\alpha_i$'s.\n* $\\det(V) = \\prod_{1\\leq i < j \\leq n} (\\alpha_j-\\alpha_i)$.\n* A $m \\times n$ rectangular Vandermonde matrix such that $m \\leq n$ has maximum rank $m$ iff all $x_i$ are distinct.\n* A $m \\times n$ rectangular Vandermonde matrix such that $n \\leq m$ has maximum rank $n$ iff there are $n$ of the $\\alpha_i$ that are distinct.\n* A $n \\times n$ Vandermonde matrix is invertible iff the $\\alpha_i$ are distinct. [A direct formula to compute it is known](https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19660023042.pdf).\n* The discrete Fourier transform is defined by the [DFT matrix](https://en.wikipedia.org/wiki/DFT_matrix), which is a specific Vandermonde matrix where the numbers $\\alpha_i$ are chosen to be roots of unity.\n\n### c) Symmetric matrix\n\nA square matrix $A$ so that $A = A^T$.\n\n* Every square diagonal matrix is symmetric.\n* With $A,B$ symmetric, $A+B$ is symmetric.\n* With $A,B$ symmetric, iff $AB=BA$, then $AB$ is symmetric.\n* Given $n$ integer, $A^n$ is symmetric.\n* If $A^{-1}$ exists, it is symmetric.\n* If $A \\in \\mathbb{R}^{n\\times n}$, then $\\langle A\\vec{x}, \\vec{y} \\rangle = \\langle \\vec{x}, A\\vec{y} \\rangle \\quad \\forall \\vec{x},\\vec{y}, \\in \\mathbb{R}^n$\n* If $A$ is congruent with $R$, i.e. there exists an invertible matrix $P$ so that $P^T AP = B$, then $B$ is also symmetric.\n* Every squared real matrix can be docmposed into two real symmetric matrices.\n* If $A \\in \\mathbb{R}$, it is also hermitian (and has their properties!).\n\n### d) Hermitian matrix\n\nA square matrix $A$ so that $A = A^*$, where $A^* = \\overline{A^T}$.\n* $a_{ij} = \\overline{a_{ji}}$\n* All the eigenvalues $A$ are real.\n* $A$ is normal, i.e. $A^*A = AA^*$.\n* $\\langle \\vec{v}, A\\vec{v} \\rangle \\in \\mathbb{R}$\n* If $A$ is also positive-definite (i.e. $\\vec{z}^* A \\vec{z} > 0, \\forall z \\neq \\vec{0}$), then $A=LL^*$ where $L$ is a lower-triangular matrix.\n * This is the [Cholesky decomposition](https://en.wikipedia.org/wiki/Cholesky_decomposition), more efficient than $LU$ decomposition for solving systems of linear equations.\n* $\\langle \\vec{v}, A \\vec{w} \\rangle = \\langle A\\vec{v}, \\vec{w} \\rangle$\n* With $A,B$ hermitian, $A+B$ is hermitian.\n* With $A,B$ hermitian, if $AB=BA$, then $AB$ is hermitian.\n* Given $n$ integer, $A^n$ is hermitian.\n* $A$ can be diagonalized: $A= Q\\Lambda Q^T$, where $Q$ is a unitary matrix.\n * $Q$ is composed of orthonormal eigenvectors of $A$ and $\\Lambda$ is diagonal, having the eigenvalues of $A$.\n * It holds that $$\n A = \\sum_j \\lambda_j u_j u_j^* \\,,\n $$ where the $u_j$'s are the orthonormal eigenvectors and the $\\lambda_j$'s are the eigenvalues.\n * This is the [eigendecomposition](https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix) of $A$.\n* $B + B^*$ is Hermitian, for a square matrix $B$.\n\n### e) Skew-hermitian matrix\n\nA square matrix $A$ so that $A^* = -A$, where $A^* = \\overline{A^T}$.\n\nThe following conditions are equivalent:\n* The real part $\\mathfrak{R}(A)$ is skew-symmetric and the imaginary part $\\mathfrak{I}(A)$ is symmetric.\n* $iA$ is Hermitian.\n* $-iA$ is Hermitian.\n* $x^*Ay=-y^*Ax$ for all vectors $x,y$.\n\nProperties:\n* $a_{ij} = -\\overline{a_{ji}}$\n* All the eigenvalues of a $A$ are purely imaginary (possibly zero).\n* It is normal (i.e. $A^*A = AA^*$).\n * $\\Rightarrow$ it is diagonalizable ($A = VDV^*$ with $V$ unitary and $D$ diagonal).\n * Its eigenvectors for distinct eigenvalues are orthogonal.\n* All $a_{ii}$ (values in the diagonal) have to be purely imaginary (possibly zero).\n* With $A,B$ skew-Hermitian, $A+B$ is skew-hermitian.\n* $A^k$ is Hermitian if $k$ is even and skew-Hermitian if $k$ is odd.\n* $B - B^*$ is skew-Hermitian, for a square matrix $B$.\n* An arbitrary square matrix $X$ can be writeen as the sum of a Hermitian matrix $H$ and a skew-Hermitian matrix $S$:\n$$\nX = H + S \\quad \\text{with} \\quad H = \\tfrac{1}{2}(X+X^*) \\quad \\text{and} \\quad S = \\tfrac{1}{2}(X-X^*)\n$$\n\n### f) Unitary matrix\n\nA square matrix $U$ is unitary if $U^*$ is also its inverse $U^{-1}$:\n$$\nU^* U = U U^* = I\n$$\n\nThe following conditions for $U$ are equivalent:\n* $U^*$ is unitary.\n* $U^{-1} = U^*$\n* $U$ is normal and their eigenvalues are in the unit circle.\n* The columns of $U$ form an orthonormal basis of $\\mathbb{C}^n$.\n* The rows of $U$ form an orthonormal basis of $\\mathbb{C}^n$.\n\nProperties:\n* By definition, it is normal (i.e. $U^*U = UU^*$).\n * $\\Rightarrow$ it is diagonalizable ($A = VDV^*$ with $V$ unitary and $D$ diagonal).\n * Its eigenvectors for distinct eigenvalues are orthogonal (orthonormal in this case).\n* $|\\text{det}(U)| = 1$\n* Vector norms are preserved on multiplication.\n\n### g) Jacobian matrix\n\nA matrix $J$ that contains all the first-order partial derivates of a vector-valued function $\\mathbf{f}:\\mathbb{R}^n \\rightarrow \\mathbb{R}^m$ :\n\n$$\nJ(x_1,\\dots,x_n) = \\left[\n\\begin{matrix}\n\\frac{\\partial \\mathbf{f}}{\\partial x_1}\n& \\cdots\n& \\frac{\\partial \\mathbf{f}}{\\partial x_n}\n\\end{matrix} \\right]\n= \\left[\n\\begin{matrix}\n\\frac{\\partial f_1}{\\partial x_1} & \\cdots & \\frac{\\partial f_1}{\\partial x_n}\n\\\\ \\vdots & \\ddots & \\vdots\n\\\\ \\frac{\\partial f_m}{\\partial x_1} & \\cdots & \\frac{\\partial f_m}{\\partial x_n}\n\\end{matrix} \\right]\n$$\n\n* The best linear approximation of $\\mathbf{f}$ near a point $\\mathbf{p}$ is:\n$$\n\\mathbf{f}(\\mathbf{x})-\\mathbf{f}(\\mathbf{p}) = J(\\mathbf{p})(\\mathbf{x}-\\mathbf{p})\n$$\n* If $J(\\mathbf{x})$ is non-singular, $\\mathbf{f}$ is locally invertible near $\\mathbf{x}$.\n* The inverse of the Jacobian matrix $J$ of $\\mathbf{f}$ is the Jacobian matrix of $\\mathbf{f}^{-1}$.\n* It satiesfies the chain rule:\n$$\nJ_{\\mathbf{g} \\circ \\mathbf{f}}(\\mathbf{x}) = J_{\\mathbf{g}}(\\mathbf{f}(\\mathbf{x})) J_{\\mathbf{f}}(\\mathbf{x}) \n$$\n\n### h) Projection matrix\n\nA matrix $P$ such that $P^2 = P$ (idempotent), that defines a transformation between the vector space $W$ to itself.\n\n* Its eigenvalues are $0$ or $1$.\n* Being $U = \\text{Rank}(P)$ and $V = \\text{Kern}(P)$:\n * $\\forall x \\in U : Px = x$, i.e. $P$ is equivalent to the identity on the subspace $U$.\n * Every vector $x \\in W$ may be decomposed uniquely as $x = u + v$, with $u = Px$ and $v = x - Px = (I-P) x$, where $u \\in U, v \\in V$.\n* If two projections commute, their product is a projection.\n* If $P$ projects onto a line with unit vector $u$, then $P=uu^T$.\n* If $P$ projects onto a subspace $U$ with $u_1,\\dots,u_k$ an arthonormal basis, then\n $P = AA^T$, where $A$ is the $n \\times k$ matrix whose columns are $u_1,\\dots,u_k$.\n\n### i) Companion matrix\n\nA square matrix defined for the polinomial:\n$$\np(t) = c_0 + c_1 t + \\cdots + c_{n-1} t^{n-1} + t^n\n$$\nas\n$$\nC(p) = \\left[\n\\begin{matrix}\n0 & 0 & \\cdots & 0 & -c_0 \\\\\n1 & 0 & \\cdots & 0 & -c_1 \\\\\n0 & 1 & \\cdots & 0 & -c_2 \\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & 0 & \\cdots & 1 & -c_{n-1}\n\\end{matrix}\n\\right]\n$$\n\n* A matrix $A$ is similar to the companion matrix $C$ of its characteristic polynomial (i.e. $\\exists P: C=P^{-1}AP$).\n * Similar matrices share several properties, in that sense, analyzing $C$ could be more easy that analyzing $B$.\n * Rank\n * Characteristic polynomial\n * Determinant\n * Trace\n * Eigenvalues\n\n### j) Jacobi matrix\n\nA square tridiagonal matrix:\n$$\nA = \\left[\\begin{matrix}\na_1 & b_1 & 0 & \\cdots & 0 & 0 \\\\\nc_1 & a_2 & b_2 & \\cdots & 0 & 0 \\\\\n0 & c_2 & a_3 & \\cdots & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\cdots & a_{n-1} & b_{n-1} \\\\\n0 & 0 & 0 & \\cdots & c_{n-1} & a_{n} \n\\end{matrix}\\right]\n$$\nso that $a_i \\neq 0 , \\forall i$.\n\n* The determinant can be computed from a three-term recurrence relation:\n \\begin{align}\n f_m &= a_m f_{m-1} - c_{m-1}b_{m-1}f_{m-2} \\\\\n f_{-1} &= 0 \\\\\n f_{0} &= 1\n \\end{align}\n where each $f_m$ is the determinant of the top-left $m\\times m$ submatrix and, thus, $\\text{det}(A) = f_n$.\n* The inverse can be obtained by a [known recurrence](https://en.wikipedia.org/w/index.php?title=Tridiagonal_matrix&oldid=905913546#Inversion).\n* If it is also Toeplitz (i.e. all values in the same diagonal are equal), which means $a_i =a \\, \\forall i$ ; $b_i =b \\, \\forall i$ ; $c_i =c \\, \\forall i$; the eigenvalues are:\n$$\n\\lambda_k = a+2\\sqrt{bc} \\cos\\left(\\frac{k\\pi}{n+1}\\right), \\quad k=1,\\dots,n\n$$\n* If $A$ is real and symmetric, then its eigenvalues are real. If all offdiagonal elements are nonzero, then they also are distinct.\n* [Numerous methods](https://www.sciencedirect.com/science/article/pii/S1063520312001042?via%3Dihub) exist for the numerical computation of the eigenvalues of a real symmetric tridiagonal matrix.\n* With [Lanczos algorithm](https://en.wikipedia.org/wiki/Lanczos_algorithm) it is possible to transform a Hermitian matrix to tridiagonal (and compute its eigenvalues).\n\n### k) Defective matrix\n\nA $n \\times n$ matrix $A$ that doesn't have $n$ linearly independent eigenvectors.\n\n* $A$ has fewer than $n$ distinct eigenvalues. Repeated eigenvalues are called *defective*.\n* $A$ cannot be diagonalized.\n* Normal matrices are never defective.\n\n### l) Toeplitz matrix\n\nA matrix $A$ of size $n \\times n$ in which each descending diagonal from left to right is constant.\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_{-1} & a_{-2} & \\cdots & a_{-(n-1)} \\\\\na_{1} & a_0 & a_{-1} & \\ddots & \\vdots \\\\\na_{2} & a_{1} & a_0 & \\ddots & a_{-2} \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & a_{-1} \\\\\na_{n-1} & \\cdots & a_2 & a_1 & a_0\n\\end{matrix}\\right]\n$$\ni.e. it is determined by the constants $c_{-(n{-}1)},\\dots,c_{n-1}$, so that\n$$\na_{i,j} = c_{i-j}\n$$\n\n* The system $Ax = b$ (called Toeplitz system) can be solved using the [Levinson algorithm](https://en.wikipedia.org/wiki/Levinson_recursion) on $\\Theta(n^2)$ time.\n* $A$ can be decomposed ($LU$) in $O(n^2)$ time.\n* If $A$ is symmetric, it can be decomposed as:\n$$\n\\tfrac{1}{a_0} A = G G^T - (G-I) (G-I)^T\n$$\nwhere $G$ is the lower triangular part of $\\tfrac{1}{a_0}A$.\n* If $A$ is nonsingular and symmetric, we have that:\n$$\nA^{-1} = \\tfrac{1}{a_0}(B B^T - C C^T)\n$$\nwhere $B$ and $C$ are lower triangular Toeplitz matrices and $C$ is strictly lower.\n* It can be used to express a [discrete convolution](https://en.wikipedia.org/wiki/Toeplitz_matrix#Discrete_convolution) as matrix multiplication.\n\nNote: The definition sometimes is extended to include $n \\times m$ matrices but most properties don't apply.\n\n### m) Circulant matrix\n\nA Toeplitz matrix with the aditional condition that $a_i = a_{i+m}$.\n\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_{n-1} & a_{n-2} & \\cdots & a_{1} \\\\\na_1 & a_0 & a_{n-1} & \\ddots & \\vdots \\\\\na_2 & a_{1} & a_0 & \\ddots & a_{n-2} \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & a_{n-1} \\\\\na_{n-1} & \\cdots & a_2 & a_1 & a_0\n\\end{matrix}\\right]\n$$\n\nThe polynomial $f(x) = a_0 + a_1 x + a_2 x^2 + \\dots + a_{n-1}x^{n-1}$ is called the *asociated polynomial* of $A$.\n\n* It is fully specified by a vector $\\mathbf{a} = a_0,\\dots,a_{n-1}$.\n* They are diagonalized by a discrete Fourier transform.\n * Equations that contain them may be quickly solved useing a FFT.\n * The following matrix $U_n$ is composed of the eigenvectors of $A$:\n $$\n U_n^* = \\tfrac{1}{\\sqrt{n}}F_n \\quad \\text{and} \\quad U_n = \\sqrt{n}F_n^{-1} \\,,\n $$\n where $F_n = [f_{jk}]$ with $f_{jk} = e^{-2jk\\pi i/n},\\quad 0\\leq j,k < n$.\n * $A = U_n \\text{diag}(F_n \\mathbf{a}) U_n^* = F_n^{-1} \\text{diag}(F_n \\mathbf{a})F_n.$\n The eigenvalues of $A$ are given by $F_n \\mathbf{a}$ which can be calculated using a FFT.\n* The normalized eigenvectors are given by:\n$$\nv_j = \\tfrac{1}{\\sqrt{n}}(1,\\omega_j,\\omega_j^2,\\dots,\\omega_j^{n-1}), \\qquad \\forall j \\in [0,n{-}1] \\,,\n$$\nwhere $\\omega_j = \\text{exp}\\left( i \\tfrac{2 \\pi j}{n} \\right)$ (the $n$-th roots of unity).\n* The eigenvalues are given by:\n$$\n\\lambda_j = f(w_j), \\qquad \\forall j \\in [0,n{-}1] \\,.\n$$\n* $\\text{Rank}(A) = n-d$, where $d$ is the degree of the $\\text{gcd}(f(x),x^n-1)$.\n* If $A$ and $B$ are circulant, $A+B$ is circulant, $AB=BA$ is also circulant.\n* Given an equation $A\\mathbf{x} = \\mathbf{b}$, it can be written as a circular convolution:\n $$\n \\mathbf{a} \\star \\mathbf{x} = \\mathbf{b}\n $$\n Then $F_n(\\mathbf{a} \\star \\mathbf{x}) = F_n(\\mathbf{a})F_n(\\mathbf{x}) = F_n(\\mathbf{b})$ and then\n $$\n \\mathbf{x} = F_n^{-1}\\left[ \\left(\\frac{(F_n(\\mathbf{b}))_v}{(F_n(\\mathbf{a}))_v} \\right)_{v \\in Z} \\right]^T\n $$\n\n### n) Hankel matrix\n\nA matrix $A$ of size $n \\times n$ in which each **ascending** diagonal from left to right is constant.\n$$\nA = \\left[ \\begin{matrix}\na_0 & a_1 & a_2 & \\cdots & a_{n-1} \\\\\na_1 & a_2 & a_3 & \\cdots & a_n \\\\\na_2 & a_3 & a_4 & \\cdots & a_{n+1} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\na_{n-1} & a_{n} & a_{n+1} & \\cdots & a_{2n-2}\n\\end{matrix}\\right]\n$$\nin other words\n$$\nA = [A_{ij} = a_{i+j-2}]\n$$\n\n* It is symmetric.\n* The determinant of the particular Hankel matrix:\n$$\nH_n = \\left[h_{ij} = \\begin{cases}\n0 & \\text{ if } i+j-1 > n \\\\\ni+j-1 & \\text{otherwise}\n\\end{cases}\\right] = \\left[\n\\begin{matrix}\n1 & 2 & 3 & \\cdots & n{-}2 & n{-}1 & n \\\\\n2 & 3 & 4 & \\cdots & n{-}1 & n & 0 \\\\\n3 & 4 & 5 & \\cdots & n & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots & \\vdots \\\\\nn{-}2 & n{-}1 & n & \\cdots & 0 & 0 & 0\\\\\nn{-}1 & n & 0 & \\cdots & 0 & 0 & 0 \\\\\nn & 0 & 0 & \\cdots & 0 & 0 & 0 \\\\\n\\end{matrix}\n\\right]\n$$\nis given by $\\text{det}(H_n) = (-1)^{\\lfloor n/2 \\rfloor} n^n$.\n\n### o) Hilbert matrix\n\nThe Hilbert matrix is an specific $n \\times n$ matrix with the following form:\n$$\nH = \\left[h_{ij} = \\frac{1}{i+j-1}\\right] = \\left[\\begin{matrix}\n1 & \\tfrac{1}{2} & \\tfrac{1}{3} & \\cdots & \\tfrac{1}{n} \\\\\n\\tfrac{1}{2} & \\tfrac{1}{3} & \\tfrac{1}{4} & \\cdots & \\tfrac{1}{n{+}1} \\\\\n\\tfrac{1}{3} & \\tfrac{1}{4} & \\tfrac{1}{5} & \\cdots & \\tfrac{1}{n{+}2} \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n\\tfrac{1}{n} & \\tfrac{1}{n{+}1} & \\tfrac{1}{n{+}2} & \\cdots & \\tfrac{1}{2n{-}1}\n\\end{matrix}\\right]\n$$\n\n* They are canonical examples of ill-conditioned matrices.\n* It is a Hankel matrix.\n * It is symmetric.\n* The determinant is:\n$$\n\\text{det}(H) = \\frac{c_n^4}{c_{2n}} \\,,\n$$\nwhere\n$$\nc_n = \\prod_{i=1}^{n-1} i^{n-i} = \\prod_{i=1}^{n-1} i! \\, . \n$$\n* The inverse is given by:\n$$\nH^{-1} = \\left[h'_{ij} = (-1)^{i+j}(i+j-1)\\binom{n+i-1}{n-j} \\binom{n+j-1}{n-i} \\binom{i+j-2}{i-1}^2 \\right]\n$$\n * All entries are integers.\n * The signs form a checkerboard matrix, with the principal diagonal positive.\n* The condition number grows as $O\\left((1+\\sqrt{2})^{4n}\\middle/\\sqrt{n}\\right)$.\n\n### p) Markov matrix\n\nA matrix that describes the transitions of a Markov chain, where each entry represents a probability (non-negative), there are 3 kinds:\n* **right stochastic matrix**: each rows sums 1.\n* **left stochastic matrix**: each column sums 1.\n* **doubly stochastic matrix**: the whole matrix sums 1.\n\nFor the first one we have that\n$$\nP = [p_{ij}] \\, ,\n$$\nwith the condition that $\\sum_{j=1}^{n} p_{ij} = 1$, which is equivalent to:\n$$\nP \\mathbf{1} = \\mathbf{1}\n$$\n\n* The entry $p_{ij}$ represents the probability of transitioning from state $i$ to state $j$, where there are $n$ possible states. State probabilities should be multiplied by the left in order to advance the system.\n* The product of two right stochastic matrices is also stochastic: $P' P'' \\mathbf{1} = \\mathbf{1}$.\n* A probability vector $\\mathbf{\\pi}$ that's also a row eigenvector asociated to the eigenvalue $1$ represents a stationary distribution (that doesn't change under the application of the transition matrix):\n$$\n\\mathbf{\\pi} P = \\mathbf{\\pi} \\,.\n$$\n * The system evolves over time to a static state:\n $$\n \\lim_{k \\rightarrow \\infty} P^k = \\Pi,\n $$\n where al $\\Pi$ rows are equal, and coincide with the vector $\\mathbf{\\pi}$. \n* The vector $\\mathbf{1}$ is a column eigenvector of $P$.\n* The spectral radius is at most $1$, moreover:\n$$\n|\\lambda - \\omega| \\leq 1-\\omega, \\quad \\text{where } \\omega = \\min_{1\\leq i \\leq n} p_{ii}.\n$$\n\n### q) Differentiation matrices\n\nIts a matrix that when multiplied with a discrete approximation for a function $y(x)$, at some fixed points $x_j, j \\in 0,\\dots,n$ retrieves a numerical discrete approximation a derivate of $y$.\n\nThese matrices are equivalent to fiting a function $p$ to the data, differentiating this approximation and evaluating this differentiation.\n\nFor instance:\n$$\nD = \\frac{1}{h^2}\\left[\\begin{matrix}\n1 & -1 \\\\\n-1 & 2 & -1 \\\\\n& -1 & 2 & -1 \\\\\n& & \\ddots & \\ddots & \\ddots \\\\\n& & & -1 & 2 & -1 \\\\\n& & & & -1 & 2 & -1 \\\\\n& & & & & -1 & 1 \\\\\n\\end{matrix}\\right]\n$$\nperforms an approximation of $y''(x)$ using second-order central difference.\n\nThe approximation is performed:\n$$\nD \\mathbf{y} = \\mathbf{y''}\n$$\nwhere $\\mathbf{y} = [y(x_j)]$ and $\\mathbf{y''}$ is the approximation of $[y''(x_j)]$.\n\n* Spectral methods use basis functions that are nonzero over the whole domain (they are **global**), for instance, $p(x)$ being a polynomial of degree $n$. Differentiation matrices are dense.\n* Finite element methods use basis functions that are nonzero only on small subdomains (they are **local**), for instance, using $p(x)$ as splines. Differentiation matrices are sparse.\n* The spectral element method chooses high degree piecewise polynomials as basis functions, also achieving a very high order of accuracy. Such polynomials are usually orthogonal Chebyshev polynomials or very high order Legendre polynomials over non-uniformly spaced nodes.\n\nThese matrices are used to represent the differentiation operator in order to solve differential equations.\n\nPowers $D^n$ can be used to represent the $(n)$ derivate of a function discretization.\n\n### r) Spectral differentiation matrices\n\nDifferentiation matrices that get better global approximations for derivates. These approximations have \"*spectral accuracy*\", i.e. error diminises exponentially with $n$.\n\nOn multiplication, retrieves a vector of points $p'(x_j)$ (or a higher order derivate) where $p$ is a single function so that $p(x_j)=y_j$ and this function $p$ is (generally) nonzero over the domain.\n\n* For periodic grids: Fourier methods can be used, $p$ is chosen to be a sum of trigonometric functions.\n* For non periodic grids: Chebyshev methods can be used, $p$ is chosen to be a polynomial.\n\n### s) Chebyshev differentiation matrices\n\nA $(n{+}1) \\times (n{+}1)$ spectral differentiation matrix that evaluates the function at the Chebyshev points:\n$$\nx_j = \\cos(j\\pi/N),\\quad j = 0,\\dots,N\n$$\n\nOn multiplication, retrieves a vector of the points $p'(x_j)$ where $p(x)$ is the unique polynomial of degree $N$ that interpolates the input points.\n\nFor instance, for $n=2$:\n$$\nD = \\left[\n\\begin{matrix}\n\\tfrac{3}{2} & -2 & \\tfrac{1}{2} \\\\\n\\tfrac{1}{2} & 0 & -\\tfrac{1}{2} \\\\\n-\\tfrac{1}{2} & 2 & -\\tfrac{3}{2}\n\\end{matrix}\n\\right]\n$$\n\n---\n\n# Item II\n\nLet $H_n$ be the $n\\times n$ Hilbert matrix whose $ij$-th entry is defined as $1/(i+j-1)$, also, let $\\mathbf{1}_n$ be the vector of ones of dimension $n$. *Discuss the following questions.*\n1. Find, as accurate as possible, the approximate solution $\\hat{\\mathbf{x}}$ of the linear system $A\\mathbf{x}=\\mathbf{b}$, where $A=H_n$ and $\\mathbf{b}= H_n\\mathbf{1}_n$ for $n=3\\dots 20$. Notice that we know a priori that the exact solution is just $\\mathbf{x} = \\mathbf{1}_n$, but (un)fortunately the computer can only give you $\\tilde{\\mathbf{x}}$.\n2. What is the relation between $\\mathbf{x}$ and $\\tilde{\\mathbf{x}}$?\n3. What can we do now?\n\n---\n\n\n```python\ndef hilbert(n):\n v = np.arange(1,n+1,dtype='float')\n iis = v.reshape((1,n))\n jjs = v.reshape((n,1))\n return (iis+jjs-1)**-1\n```\n\n\n```python\nNS = np.arange(3,20+1)\nerrors = []\n\nfor n in NS:\n H = hilbert(n)\n real_x = np.ones(n)\n b = np.dot(H,real_x)\n x = np.linalg.solve(H,b)# We use np.linalg.solve\n err = np.mean(np.abs((x-real_x)/real_x))\n errors.append(err)\n \nerrors = np.array(errors)\n```\n\n\n```python\n# Plot errors\nplt.plot(NS,errors)\nplt.grid()\nplt.title(\"Mean relative error between $\\\\tilde{x}$ and $x$ vs. $n$\")\nplt.plot()\npass\n```\n\nWe see that as $n$ grows, the relative error between $\\tilde{\\mathbf{x}}$ and $\\mathbf{x}$ grows fast.\n\nThis is because $\\text{cond}(H_n) = O\\left( \\left(1+\\sqrt{2}\\right)^{4n}/\\sqrt{n}\\right)$, so, given small perturbations on the operations required to solve the problem, the error on the solution grows considerably with $n$.\n\n---\n\nTo solve the problem we can try to minimize instead of finding the exact solution\n\n\n```python\nlstsq_errors = []\n\nfor n in NS:\n H = hilbert(n)\n real_x = np.ones(n)\n b = np.dot(H,real_x)\n x,_,_,_ = np.linalg.lstsq(H,b,rcond=None)\n err = np.mean(np.abs((x-real_x)/real_x))\n lstsq_errors.append(err)\n\nlstsq_errors = np.array(lstsq_errors)\n```\n\n\n```python\n# Plot errors\nplt.plot(NS,lstsq_errors,c=\"#ff0000\")\nplt.grid()\nplt.title(\"Mean relative error between $\\\\tilde{x}$ and $x$ vs. $n$ with lstsq\")\nplt.plot()\npass\n```\n\nWe can see that approaching the problem like a minimization gives far better results, because it can perform more iterations to correct numerical errors.\n\n\n# Item III\n\n*Solving a very (un)known problem*\n\n1. Implement a function that finds the two roots of the quadratic equation $a x^2 + b x + c = 0$ given $a$,$b$, and $c$, i.e. implement $x_{\\pm} = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}$.\n2. What are the roots of $2x^2+10^9+1 = 0$? How many digits of significance can you get for the two roots? Is there any problem?\n3. Design a code that finds the correct roots for $x^2+Bx+C=0$, given $B \\gg C$ to at least 2 digits of significance.\n4. Solve the previous equation using this new code and find the new roots. *I hope it works!*\n5. From the well-known solution $x_{\\pm}$ of the quadratic equation design an algorithm that approximates the two roots of $x^2+Bx+C = 0$, given $B \\gg C$. Hint: *A Taylor expansion may work*.\n---\n\n## Part 1\n\n\n```python\ndef solve_quadratic(a,b,c):\n assert(a!=0)\n disc = (b**2-4*a*c+0j)**0.5\n x1 = (-b-disc)/(2*a)\n x2 = (-b+disc)/(2*a)\n return (x1,x2)\n```\n\n## Part 2\n\nThe analytical solution is:\n$$\nx_{\\pm} = \\frac{-10^{9}\\pm\\sqrt{10^{18}-8}}{4}\n$$\n\n\n```python\n# if we use the solver\nx1,x2 = solve_quadratic(2,1e9,1)\nprint(\"x-:\",x1)\nprint(\"x+:\",x2)\n```\n\n x-: (-500000000+0j)\n x+: 0j\n\n\nThe approximation given for $x_{-}$ is good since the relative error is very little (the approximation $\\sqrt{10^{18}-8} \\approx 10^{9}$ that the computer does because of the *absorption* of the much smaller $-8$ doesn't affect the relative error too much).\n\n\nFor $x_{+}$ however, the error is equal to the value of the root, since \n\n## Part 3\n\nWe make the following change to the equation:\n\\begin{align}\nx_{\\pm} = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a} &= \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a} \\cdot \\frac{-b \\mp \\sqrt{b^2-4ac}}{-b \\mp \\sqrt{b^2-4ac}}\n\\\\ &= \\frac{4ac}{2a \\left(-b \\mp \\sqrt{b^2-4ac}\\right)}\n\\\\ &= \\frac{-2c}{\\left(b \\pm \\sqrt{b^2-4ac}\\right)}\n\\end{align}\nwe can use it for $x_{+}$ if $b>0$ or $x_{-}$ otherwise.\n\n\n```python\ndef solve_quadratic_2(a,b,c):\n assert(a!=0)\n disc = (b**2-4*a*c+0j)**0.5\n if b>0:\n x1 = (-b-disc)/(2*a)\n x2 = -2*c/(b+disc)\n else:\n x1 = -2*c/(b-disc)\n x2 = (-b+disc)/(2*a)\n return (x1,x2)\n```\n\n## Part 4\n\nWe solve using the new method and see that it works.\n\n\n```python\nx1,x2 = solve_quadratic_2(2,1e9,1)\nprint(\"x-:\",x1)\nprint(\"x+:\",x2)\n```\n\n x-: (-500000000+0j)\n x+: (-1e-09+0j)\n\n\n## Part 5\n\nIf $C$ is small, we can approximate the solution:\n$$\nx = x_0 + C x_1 + C^2 x_2 + ...\n$$\n\nThen\n$$\n\\begin{align}\nx^2 + B x + C &= 0\n\\\\ (x_0^2 + C (2x_0x_1) + C^2 (x_1^2 + 2x_0x_2) + \\dots) + (Bx_0 + C B x_1 + C^2 B x_2 + \\dots) + C &= 0\n\\end{align}\n$$\nAnd we have the following equations:\n\\begin{align}\nO(C^0) : &\\qquad x_0^2 + B x_0 = 0 \n\\\\ O(C^1) : &\\qquad 2x_0x_1 + B x_1 +1 = 0 \n\\\\ O(C^2) : &\\qquad x_1^2 + 2 x_0x_2 + B x_2 = 0 \n\\end{align}\nwhich have the following solutions:\n$$\n(x_0,x_1,x_2)_1 = \\left(0,\\frac{-1}{B},\\frac{-1}{B^3}\\right)\n$$\n$$\n(x_0,x_1,x_2)_2 = \\left(-B,\\frac{1}{B},\\frac{1}{B^3}\\right)\n$$\nwhich result in the following approximations for $x$:\n$$\n\\begin{align}\nx_{1} &= 0 + C \\frac{-1}{B} + C^2 \\frac{-1}{B^3} + \\cdots\n\\\\ x_{2} &= -B + C \\frac{1}{B} + C^2 \\frac{1}{B^3} + \\cdots\n\\end{align}\n$$\n\n\n```python\ndef solve_quadratic_3(a,b,c):\n # In case a!=1 we just have to scale the equation:\n b /= a\n c /= a\n # Approximations:\n x1 = 0+c*(-1/b)+c**2*(-1/b**3)\n x2 = -b+c*(1/b)+c**2*(1/b**3)\n return (x1,x2)\n```\n\n\n```python\nx1,x2 = solve_quadratic_3(2,1e9,1)\nprint(\"x1:\",x1)\nprint(\"x2:\",x2)\n```\n\n x1: -1e-09\n x2: -500000000.0\n\n\n---\n\n# Item IV\n\nA *fix-point-iteration review*. See Numerical Analysis, 2nd edition by Timothy Sauer.\n\n* Definition 1: The real number $r$ is a fix-point of the function $g(x)$ if $g(r)=r$.\n* Algorithm 1: Fixed-Point-Iteration: Let $x_0$ be the initial guess. Compute $x_{i+1} = g(x_i)$, for $i=0,1,2,3,\\dots$. Notice that this fixed-point-iteration may or may not converge to $r$.\n* Definition 2: Let $e=|r-x_i|$ be the error at iteration $i$. If $0 < \\lim_{i \\rightarrow \\infty} \\frac{e_{i+1}}{e_i} = S < 1$, the fixed-point-iteration $x_{i+1} = g(x_i)$ is said to obey linear convergence with rate $S$.\n* Theorem 1: Assume that $g(x)$ is continuously differentiable and that $S=|g'(x)|<1$. Then the fixed-point-iteration $x_{i+1}=g(x_i)$ converges at least linearly with rate $S$ to the fixed point $r$ for the initial guesses sufficiently close to $r$.\n\n---\n\n* **Question 1**: Prove that a continuously differentiable function $g(x)$ satisfying $|g'(x)|<1$ on a closed interval cannot have two fixed points on that interval.\n\n__Dem__:\n\nBy contradiction, let's asume that $g(x)$ has two fixed points, $x_1$ and $x_2$, with $x_1 \\neq x_2$ on the interval $[a,b]$, and that $|g'(x)|< 1 \\, \\forall (x \\in [a,b])$, then we have that:\n$$\ng(x_1) = x_1 \\qquad g(x_2) = x_2 \\,.\n$$\n\nGiven, this two points, by the [mean value theorem](https://en.wikipedia.org/wiki/Mean_value_theorem), there should exist a point $c \\in [x_1,x_2]$ so that:\n$$\ng'(c) = \\frac{g(x_1)-g(x_2)}{x_1-x_2} = \\frac{x_1-x_2}{x_1-x_2} = 1\n$$\nas $c \\in [x_1,x_2] \\Rightarrow c \\in [a,b]$, we have a contradiction, since we said that $|g'(x)|<1 \\, \\forall (x \\in [a,b])$.\n\n---\n\n* **Question 2**: Given that $f(x)$ has a root near $x_0$. Derive three different fix-point-iterations that may converge to $f(r)=0$ and state the restrictions of $f(x)$ needed, if any. Assume that $f(x)$ has as many derivatives as you may need.\n\n(1) We have the trivial options (as $x \\rightarrow r$):\n\\begin{align}\n0 &= f(x)\n\\\\ x &= \\underbrace{\\pm f(x) + x}_{g(x)} \n\\end{align}\nit requires that $|g'(r)| = |\\pm f'(r) + 1| \\leq 1$, we may choose the sign of $\\pm$.\n\n(2) We expand the Taylor series arround $x_0$:\n\\begin{align}\nf(x) &= f(x_0) + f'(x_0)(x-x_0) + \\dots\n\\\\ 0 &= f(x_0) + f'(x_0)(x-x_0) \\qquad \\qquad \\text{as $x\\rightarrow r$}\n\\\\ f'(x_0)x &= -f(x_0) + f'(x_0) x_0 \n\\\\ x &= -\\frac{f(x_0)}{f'(x_0)} + x_0\n\\\\ x &= \\underbrace{x_0 - \\frac{f(x_0)}{f'(x_0)}}_{g(x_0)} \n\\end{align}\nWhich corresponds to the Newton's method. It doens't have restrictions.\n\n(2) We expand the Taylor series arround $x_0$:\n\\begin{align}\nf(x) &= f(x_0) + f'(x_0)(x-x_0) + \\frac{1}{2}f''(x_0)(x-x_0)^2\n\\\\ 0 &= f(x_0) + f'(x_0)(x-x_0) + \\frac{1}{2}f''(x_0)(x-x_0)^2 &\\text{as $x\\rightarrow r$}\n\\\\ 0 &= f'(x_0) + f''(x_0)x - f''(x_0)x_0 &\\text{after $\\frac{d(\\cdot)}{dx}$}\n\\\\ f''(x_0)x &= f''(x_0)x_0 - f'(x_0)\n\\\\ x &= \\underbrace{x_0 - \\frac{f'(x_0)}{f''(x_0)}}_{g(x_0)}\n\\end{align}\nWhich is the [Newton's method in optimization](https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization).\n\nIt requires $f''(r)$ to exist, and if we make $|g'(r)| <1$ that results in:\n$$\n|f'(r) f'''(r)| < |f''(r)|\n$$\n\n---\n\n* **Question 3**: Derive a unsuccessful and a successful fix-point-iteration for finding the root of $x^3+x=1$ near $x_0=1$.\n\nOur unsuccessful fix-point-iteration would be:\n\\begin{align}\nx^3+x &= 1\n\\\\ x &= 1-x^3\n\\\\ \\text{we make } g(x) &= 1-x^3\n\\end{align}\nit won't converge as $g'(x) = -3x^2$ and $g'(1) = -3$.\n\nOur successful one:\n\\begin{align}\nx^3+x &= 1\n\\\\ x(x^2+1) &= 1\n\\\\ x^2+1 &= \\frac{1}{x}\n\\\\ x^2 &= \\frac{1}{x}-1\n\\\\ x &= \\sqrt{\\frac{1}{x}-1}\n\\\\ \\text{we make } g(x) &= \\sqrt{\\frac{1}{x}-1}\n\\end{align}\nit will converge as $g'(x) = -\\frac{1}{2} \\left( x^{-1}-1 \\right)^{-\\frac{1}{2}}x^{-2}$ and $g'(1) = 0$.\n\n---\n\n* Algorithm 2: Newton's method: Let $x_0$ be the initial guess. Compute $x_{i+1} = \\hat{g}(x_i)$, for $i=0,1,2,3,\\dots$, where $\\hat{g}=x-(f'(x))^{-1}f(x)$ and $(f'(x))^{-1}$ is the inverse of $f'(x)$, i.e. $(f'(x))^{-1} = 1/f'(x)$.\n* Definition 3: Let $e = |r-x_i|$ be the error at iteration $i$. If $\\lim_{i \\rightarrow \\infty} \\frac{e_{i+1}}{e_i^2} = M < \\infty$, the method is said to be quadratically convergent.\n\n---\n\n* **Question 4**: Prove that Newton's method is quadratically convergent as long as $f'(r) \\neq 0$.\n\n**Dem**:\n\nWe have that $g(x) = x - \\frac{f(x)}{f'(x)}$. Expanding a Taylor's series around $r$:\n\\begin{align}\ng(x_i) &= g(r) + g'(r)(x_i-r) + \\frac{1}{2}g''(r)(x_i-r)^2 + \\dots \n\\\\ x_{i+1} &= r + g'(r)(x_i-r) + \\frac{1}{2}g''(r)(x_i-r)^2 + \\dots\n\\end{align}\n\nWe can see that:\n\\begin{align}\ng'(x) &= 1 - \\frac{f'(x)f'(x)-f(x)f''(x)}{(f'(x))^2}\n\\\\ g'(r) &= 1 - \\frac{f'(r)f'(r)-f(r)f''(r)}{(f'(r))^2}\n\\\\ &= 1 - \\frac{f'(r)f'(r)}{(f'(r))^2} = 1-1 = 0\n\\end{align}\n\nSo, retaking the previous equation:\n\\begin{align}\ng(x_i) &= g(r) + g'(r)(x_i-r) + \\frac{1}{2}g''(r)(x_i-r)^2 + \\dots \n\\\\ x_{i+1} &= r \\frac{1}{2}g''(r)(x_i-r)^2 + \\dots\n\\\\ x_{i+1}-r &= \\frac{1}{2}g''(r)(x_i-r)^2 + \\dots\n\\\\ \\frac{x_{i+1}-r}{(x_i-r)^2} &= \\frac{1}{2}g''(r) + \\dots\n\\\\ \\frac{e_{i+1}}{e_i^2} &= \\frac{1}{2}g''(r) + \\dots\n\\end{align}\n\nAnd the method has quadratic convergence at rate $M = \\frac{1}{2}g''(r)$.\n\n---\n\n* **Question 5**: Explain when Newton's method show linear convergence and also explain how it can be fixed.\n\nWhen $f'(r)=0$ we have that:\n\\begin{align}\ng'(x) &= 1 - \\frac{f'(x)f'(x)-f(x)f''(x)}{(f'(x))^2}\n\\\\ &= 1-\\frac{{(f'(x))^2}}{{(f'(x))^2}}+\\frac{f(x)f''(x)}{(f'(x))^2}\n\\\\ &= 1-1+\\frac{f(x)f''(x)}{(f'(x))^2}\n\\\\ &= \\frac{f(x)f''(x)}{(f'(x))^2}\n\\end{align}\nusing L'Hopital (because $f(r)=0$ too).\n\\begin{align}\ng(r) &= \\frac{f'(r)f''(r)+f(r)f'''(r)}{2f'(r)f''(r)} \n\\\\ &= \\frac{1}{2}+\\frac{f(r)f'''(r)}{2f'(r)f''(r)}\n\\\\ &= \\frac{1}{2}+\\frac{f(r)f'''(r)}{2f'(r)f''(r)}\n\\\\ &= \\frac{1}{2}+\\frac{f'(r)f'''(r)+f(r)f^{(4)}(r)}{2f''(r)f''(r)+2f'(r)f'''(r)}\n\\\\ &= \\frac{1}{2}+' \\qquad \\text{as long as $f''(x)\\neq 0$}\n\\end{align}\nwe see that the method has linear convergence because $|g'(r)|=\\frac{1}{2} \\neq 0$.\n\nIf we make our $g(x)= x - \\alpha \\frac{f'(x)}{f''(x)}$, we will see that the derivate will be:\n\\begin{align}\ng'(x) &= 1 - \\alpha\\frac{f'(x)f'(x)-f(x)f''(x)}{(f'(x))^2}\n\\\\g'(r) &= 1 - \\alpha \\left(1-\\frac{1}{2} \\right)\n\\end{align}\nand we just have to make $\\alpha = 2$ so that $g'(x)=0$. In general, we have to make $a$ equal to the multiplicity of the root \n\n---\n\n# Item V\n\nImplement in Jupyter Notebook the Lagrange Interpolation method with *sympy*.\nThen, find the interpolation polynomial for the following points:\n* $(0,1),(1,2),(2,4)$. Is a second degree polynomial? If not, why is this?\n* $(0,1),(1,2),(2,3)$. Is a second degree polynomial? If not, why is this?\n---\n\n\n```python\ndef lagrange(xs,ys):\n assert(len(xs)==len(ys))\n n = len(xs)\n x = sympy.Symbol('x')\n \n poly = 0\n for j in range(0,n):\n lag = ys[j]\n for m in range(0,n):\n if j!=m:\n lag *= (x-xs[m])/(xs[j]-xs[m])\n poly += lag\n return sympy.simplify(poly)\n```\n\n\n```python\nlagrange([0,1,2],[1,2,4])\n```\n\n\n\n\n$\\displaystyle \\frac{x^{2}}{2} + \\frac{x}{2} + 1$\n\n\n\n\n```python\nlagrange([0,1,2],[1,2,3])\n```\n\n\n\n\n$\\displaystyle x + 1$\n\n\n\n* The first points have to be interpolated by a second degree polynomial as they are not collinear, so they cannot be interpolated by a line.\n* The second set of points are collinear, so they are interpolated by a polynomial of degree 1.\n\n---\n# Item VI\n\nA *simple ODE*\n* Design a numerical method to approximate the following Boundary Value Problem:\n$$\n\\epsilon y''(x) + (1+\\epsilon) y'(x) + y(x) = 0 \\qquad \\text{for $0yp_precision:\n # Couldn't find root\n if np.isnan(yf_ypa) or np.isnan(yf_ypb) or (yf_ypa-yf)*(yf_ypb-yf)>0:\n return None\n # print(\"y'_a(0)=%f y'_b(0)=%f\"%(ypa,ypb))\n ypc = (ypa+ypb)/2.0\n ys = euler(shooteval,yi=np.array([yi,ypc]),\n tmin=tmin,tmax=tmax,steps=steps)\n yf_ypc = ys[-1][0]\n if (yf_ypc-yf)==0:\n return ys\n elif (yf_ypa-yf)*(yf_ypc-yf)<0:\n yf_ypb = yf_ypc\n ypb = ypc\n else:\n yf_ypa = yf_ypc\n ypa = ypc\n return ys\n```\n\n\n```python\ndef problem_ode(e):\n fn = lambda y,yp,t: -(1.0+e)/e*yp-1.0/e*y\n return fn\n```\n\n\n```python\nSTEPS = 400\nE = [1,0.2,0.1,0.01,1e-3,1e-8,1e-14]\n\nxs = np.linspace(0,1,num=STEPS+1)\n\nyss_numerical = {}\nfor e in E:\n print(\"Computing epsilon=%s.\"%e)\n ys = shooting(problem_ode(e),yi=0,yf=1,ypa=1.0,ypb=50.0,steps=STEPS)\n if ys is not None:\n yss_numerical[str(e)] = [y[0] for y in ys]\n else:\n print(\" Couldn't find y'(0) for epsilon=%s\"%e)\n```\n\n Computing epsilon=1.\n Computing epsilon=0.2.\n Computing epsilon=0.1.\n Computing epsilon=0.01.\n Couldn't find y'(0) for epsilon=0.01\n Computing epsilon=0.001.\n Couldn't find y'(0) for epsilon=0.001\n Computing epsilon=1e-08.\n Couldn't find y'(0) for epsilon=1e-08\n Computing epsilon=1e-14.\n Couldn't find y'(0) for epsilon=1e-14\n\n\n /home/fcasas/Music/p36cpu/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: overflow encountered in double_scalars\n \n /home/fcasas/Music/p36cpu/lib/python3.6/site-packages/ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in add\n if __name__ == '__main__':\n /home/fcasas/Music/p36cpu/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in double_scalars\n \n\n\nWith the coded method the solution couldn't be found once $\\epsilon$ became small enough.\n\n\n```python\nfor name,ys in yss_numerical.items():\n plt.plot(xs,ys,label=\"$y(t|e=%s)$\"%name)\nplt.legend()\nplt.ylim((0,2))\nplt.grid()\nplt.show()\n```\n\nWe find the analytical solution now:\n\n\n```python\ndef get_analytical_solution(ee,xs,n=200):\n x = sympy.Symbol(\"x\")\n y = sympy.Function(\"y\")(x)\n y_ = sympy.Derivative(y,x)\n y__ = sympy.Derivative(y_,x)\n sol = sympy.dsolve( # note: requires updated version of sympy.\n ee * y__ + (1+ee) * y_ + y, y, ics={y.subs(x,0):0,y.subs(x,1):1})\n sol = sol.rhs\n print(sol)\n return [float(sol.subs(x,xx)) for xx in np.linspace(0,1,num=n+1)]\n #constants = sympy.solve([sol.subs(x,0),sol.subs(x,1)-1])\n #for key in constants:\n # constants[key] = sympy.N(key)\n #print(constants)\n #sol = sol.subs(constants)\n #print(sol)\n \n```\n\n\n```python\nyss_analytical = {}\nfor e in E:\n if e<1e-6: continue # Smaller values take forever.\n print(\"computing for epsilon=%s\"%e)\n ys = get_analytical_solution(e,xs,n=STEPS)\n yss_analytical[str(e)] = ys\n plt.plot(xs,ys,label=\"analytic $y$ for $\\epsilon=%s$\"%e)\nplt.legend()\nplt.ylim((0,3))\nplt.grid()\nplt.show()\n```\n\n\n```python\n# Plot the analytic solution and the numerical one for the cases when we have both.\nfor ee_name in yss_numerical:\n if ee_name in yss_analytical:\n plt.plot(xs,yss_numerical[ee_name],label=\"numerical $y$ for $\\epsilon=%s$\"%ee_name)\n plt.plot(xs,yss_analytical[ee_name],label=\"analytic $y$ for $\\epsilon=%s$\"%ee_name)\n plt.legend()\n plt.ylim((0,3))\n plt.grid()\n plt.show()\n```\n\nThe approximation seems almost identical for all $0\n\n---\n\n# Item VII\n\nLet $X \\in \\mathbb{R}^{m \\times n}$ with $m \\gg n$. Its reduced singular value decomposition is $U \\Sigma V^*$ ($X = U \\Sigma V^*$). Compute the reduced singular value decomposition of the following matrix $U \\Sigma V^* (I - \\vec{v}_1 \\vec{v}_1^*)$, where $v_1$ is the first column of $V$ and $I$ is the identity matrix. In summary, you need to find $\\tilde{U}\\tilde{\\Sigma}\\tilde{V}^*$ such that its product give you $U \\Sigma V^* (I - \\vec{v}_1 \\vec{v}_1^*)$. \n\n*Hint: This new SVD dependes on the original SVD!*\n\n---\n\nWe make\n$$\nU \\Sigma V^* (I - \\vec{v}_1 \\vec{v}_1^*) = U \\Sigma (V^* - V^*\\vec{v}_1 \\vec{v}_1^*) \\,.\n$$\nThen, we see that\n$$\n\\vec{v}_1 \\vec{v}_1^* = \\begin{bmatrix}\nv_{1,1} \\vec{v}_1 \\, | \\, v_{2,1} \\vec{v}_1 | \\dots | \\, v_{n,1} \\vec{v}_1\n\\end{bmatrix}\n$$\nand then\n$$\nV^* \\vec{v}_1 \\vec{v}_1^* = \\begin{bmatrix}\n\\vec{v}_1^*\n\\\\ \\hline \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{v}_n^*\n\\end{bmatrix} \\begin{bmatrix}\nv_{1,1} \\vec{v}_1 \\, | \\, v_{2,1} \\vec{v}_1 | \\dots | \\, v_{n,1} \\vec{v}_1\n\\end{bmatrix}\n$$\nBecause the $\\vec{v}_i$ are orthonormal, this results in:\n$$\nV^* \\vec{v}_1 \\vec{v}_1^* = \\begin{bmatrix}\nv_{1,1} & v_{2,1} & \\dots & v_{n,1}\n\\\\ 0 & 0 & \\dots & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots\n\\\\ 0 & 0 & \\dots & 0\n\\end{bmatrix} = \\begin{bmatrix}\n\\vec{v}_1\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n$$\nand\n$$\nV^* - V^*\\vec{v}_1 \\vec{v}_1^* =\n\\begin{bmatrix}\n\\vec{0}\n\\\\ \\hline \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{v}_n^*\n\\end{bmatrix}\n$$\n\n---\n\nLet's define the operator $E$ of dimensions $m\\times m$ that raises the columns of a matrix 1 position and sends the first one to the last position (let's call that a *circulation*):\n$$\nE = \\begin{bmatrix}\n0 & 1 & 0 & \\dots & 0 & 0\n\\\\ 0 & 0 & 1 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & 0 & \\dots & 0 & 1\n\\\\ 1 & 0 & 0 & \\dots & 0 & 0\n\\end{bmatrix}\n$$\nWe can see that:\n$$\nE^{-1} = \\begin{bmatrix}\n 0 & 0 & \\dots & 0 & 1\n\\\\ 1 & 0 & \\dots & 0 & 0\n\\\\ 0 & 1 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & 1 & 0\n\\\\ 0 & 0 & \\dots & 0 & 1\n\\end{bmatrix}\n$$\nNotice that multiplying by $E^{-1}$ on the right is equivalent to circulate the **columns** of a matrix.\n\n---\n\nIf we multiply $(V^* - V^*\\vec{v}_1 \\vec{v}_1^*)$ by $U \\Sigma$ on the left to get our matrix:\n$$\nU\\Sigma(V^* - V^*\\vec{v}_1 \\vec{v}_1^*) =\nU \\begin{bmatrix}\n\\Sigma_1 \\vec{0}\n\\\\ \\hline \\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix} =\nU \\begin{bmatrix}\n0 \\cdot \\vec{v}_1^*\n\\\\ \\hline \\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n$$\n$$\n= U E^{-1} E\\begin{bmatrix}\n0 \\cdot \\vec{v}_1^*\n\\\\ \\hline \\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n= U E^{-1}\n\\begin{bmatrix}\n\\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\\\ \\hline 0 \\cdot \\vec{v}_1^*\n\\end{bmatrix}\n$$\n$$\n= U E^{-1} \\begin{bmatrix}\n\\Sigma_2 & 0 & \\dots & 0 & 0\n\\\\ 0 & \\Sigma_3 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & \\Sigma_n & 0\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\end{bmatrix}\n\\begin{bmatrix}\n\\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{v}_n^*\n\\\\ \\hline \\vec{v}_1^*\n\\end{bmatrix}\n$$\n$$\n= \\underbrace{\\begin{bmatrix}\n\\vec{u}_2 | \\cdots | \\vec{u}_m | \\vec{u}_1 \n\\end{bmatrix}}_{\\tilde{U}}\n\\underbrace{\\begin{bmatrix}\n\\Sigma_2 & 0 & \\dots & 0 & 0\n\\\\ 0 & \\Sigma_3 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & \\Sigma_n & 0\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\end{bmatrix}}_{\\tilde{E}}\n\\underbrace{\\begin{bmatrix}\n\\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{v}_n^*\n\\\\ \\hline \\vec{v}_1^*\n\\end{bmatrix}}_{\\tilde{V}^*}\n$$\nWhich is equivalent to the SVD of $U\\Sigma V(I-\\vec{v}_1\\vec{v}_1^*)$.\n\n---\n\n# Item VIII\n\nLet $X \\in \\mathbb{R}^{m \\times n}$ with $m \\gg n$, prove that maximum of the following maximization problem:\n\\begin{align}\n\\max_{w \\in \\mathbb{R}^n} &\\qquad ||X \\vec{w} ||^2_2\n\\\\ \\text{subject to} &\\qquad ||\\vec{w}||^2_2 = 1\n\\end{align}\nis obtained for $\\vec{w} = \\vec{v}_1$, where $\\vec{v}_1$ is the first column of $V$ matrix from the singular value decomposition of $X$, i.e. $X = U \\Sigma V^*$.\n\n---\n\nWe can write\n$$\n\\vec{w} = \\sum_{i=1}^n \\alpha_i \\vec{v}_i\n$$\n\nWe have that\n$$\n\\begin{align}\nX\\vec{w} &= U \\Sigma V^* \\vec{w}\n\\\\ &= U\n\\begin{bmatrix}\n\\Sigma_1 \\vec{v}_1^*\n\\\\ \\hline \\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix} \\vec{w}\n= U\n\\begin{bmatrix}\n\\Sigma_1 \\alpha_1 \\vec{v}_1^*\\vec{v}_1\n\\\\ \\hline \\Sigma_2 \\alpha_2 \\vec{v}_2^* \\vec{v}_2\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\alpha_n \\vec{v}_n^* \\vec{v}_n\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n= U\n\\begin{bmatrix}\n\\Sigma_1 \\alpha_1\n\\\\ \\hline \\Sigma_2 \\alpha_2\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\alpha_n\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n\\end{align}\n$$\nU doens't change the norm 2 of this vector, since it is unitary.\n$$\n||X \\vec{w}||_2^2 = \\sum_{i=1}^{n} \\Sigma_{i}^2 \\alpha_i^2\n$$\nsince there's the restriction that\n$$\n||\\vec{w}||_2^2 = \\sum_{i=1}^{n} \\alpha_i^2 \\quad \\leq 1\n$$\nis clear that the previous expression is maximized when\n$$\na_i^2 = \\begin{cases}\n1 & i=1\n\\\\ 0 & i\\neq 1\n\\end{cases}\n$$\nas $\\Sigma_1^2 \\geq \\Sigma_i^2 \\,\\forall i$.\n\nSo $\\vec{w} = 1 \\cdot \\vec{v}_1$ maximizes $||X \\vec{w}||_2^2$. $\\, \\square$\n\n---\n\n# Item IX\n\nRepeat the same procedure from the previous questions but for the following maximization problem:\n\\begin{align}\n\\max_{w \\in \\mathbb{R}^n} &\\qquad ||X (I - \\vec{v}_1 \\vec{v}_1^*) \\vec{w} ||^2_2\n\\\\ \\text{subject to} &\\qquad ||\\vec{w}||^2_2 = 1\n\\end{align}\n\n---\n\n\nWe use the SVD for $X (I - \\vec{v}_1 \\vec{v}_1^*)$ that we found on Item VII:\n\n$$\nX (I - \\vec{v}_1 \\vec{v}_1^*) \\vec{w} = \\underbrace{\\begin{bmatrix}\n\\vec{u}_2 | \\cdots | \\vec{u}_m | \\vec{u}_1 \n\\end{bmatrix}}_{\\tilde{U}}\n\\underbrace{\\begin{bmatrix}\n\\Sigma_2 & 0 & \\dots & 0 & 0\n\\\\ 0 & \\Sigma_3 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & \\Sigma_n & 0\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\\\ \\vdots & \\vdots & \\ddots & \\vdots & \\vdots\n\\\\ 0 & 0 & \\dots & 0 & 0\n\\end{bmatrix}}_{\\tilde{E}}\n\\underbrace{\\begin{bmatrix}\n\\vec{v}_2^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{v}_n^*\n\\\\ \\hline \\vec{v}_1^*\n\\end{bmatrix}}_{\\tilde{V}^*} \\vec{w}\n$$\nIf we write\n$$\n\\vec{w} = \\sum_{i=1}^n \\alpha_i \\vec{v}_i\n$$\nagain, we have that\n$$\n\\begin{align}\nX (I - \\vec{v}_1 \\vec{v}_1^*) \\vec{w} &= \\tilde{U} \\tilde{\\Sigma} \\tilde{V}^* \\vec{w}\n\\\\ &= \\tilde{U}\n\\begin{bmatrix}\n\\Sigma_2 \\vec{v}_2^*\n\\\\ \\hline \\Sigma_3 \\vec{v}_3^*\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\vec{v}_n^*\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix} \\vec{w}\n= \\tilde{U}\n\\begin{bmatrix}\n\\Sigma_2 \\alpha_2 \\vec{v}_2^* \\vec{v}_2\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\alpha_n \\vec{v}_n^* \\vec{v}_n\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n= \\tilde{U}\n\\begin{bmatrix}\n\\Sigma_2 \\alpha_2\n\\\\ \\hline \\vdots\n\\\\ \\hline \\Sigma_n \\alpha_n\n\\\\ \\hline \\vec{0}\n\\\\ \\hline \\vdots\n\\\\ \\hline \\vec{0}\n\\end{bmatrix}\n\\end{align}\n$$\nThe norm of this vector is just\n$$\n\\sum_{i=2}^{n} \\Sigma_{i}^2 \\alpha_i^2 \n$$\nas $\\tilde{U}$ is unitary.\n\nAgain, under the restriction that\n$$\n||\\vec{w}||_2^2 = \\sum_{i=1}^{n} \\alpha_i^2 \\quad \\leq 1\n$$\nwe can see that the previous value is maximized when $\\alpha_2= 1$ and thus, the other $\\alpha_i$ are $0$. Since $\\Sigma_{2} \\geq \\Sigma_{i} \\, \\forall (i>2)$, and $\\Sigma_1$ doesn't add to the norm.\n\nWe have So $\\vec{w} = 1 \\cdot \\vec{v}_2$ maximizes the given norm. $\\, \\square$\n\n---\n\n# Item X\n\nLet\n$$\nH(x) = \\begin{cases}\n 1 & \\text{if} -0.5 \\leq x \\leq 0.5\n \\\\ 0 & \\text{otherwise}\n\\end{cases} \\, .\n$$\n\nCompute $F(x) = \\int_{-\\infty}^{\\infty} \\tilde{H}_a(y) \\tilde{H}_b(x-y) \\, dx$ where $\\tilde{H}_a(x) = \\frac{1}{a} H\\left( \\frac{x}{a} \\right)$.\n\n---\n\nWe can work with the definition:\n\\begin{align}\n\\int_{-\\infty}^{\\infty} \\tilde{H}_a(y) \\tilde{H}_b(x-y) \\, dx\n&= \\frac{1}{a} \\int_{-\\infty}^{\\infty} H\\left(\\frac{y}{a}\\right) \\tilde{H}_b(x-y) \\, dx\n\\\\ &= \\frac{1}{a} \\int_{-a/2}^{a/2} \\tilde{H}_b(x-y) \\, dx\n\\\\ &= \\frac{1}{ab} \\int_{-a/2}^{a/2} H\\left(\\frac{x-y}{b}\\right) \\, dx\n\\\\ &= \\frac{1}{ab} \\int_{-a/2}^{a/2} H\\left(\\frac{y-x}{b}\\right) \\, dx\n\\\\ &= \\frac{1}{ab} \\max\\left( R-L, 0 \\right)\n\\end{align}\n\nwhere\n$$\nL = \\max\\left(-\\frac{a}{2}, x-\\frac{b}{2} \\right)\n$$\n$$\nR = \\min\\left(\\frac{a}{2}, x+\\frac{b}{2} \\right)\n$$\n\n\n```python\ndef convolution(a,b):\n return lambda x: (a*b)**-1 * max(min(a/2.0,x+b/2.0)-max(-a/2.0,x-b/2.0),0)\n```\n\n\n```python\nconv = convolution(4,3)\nconv(-1.5)\n```\n\n\n\n\n 0.16666666666666666\n\n\n\n---\n\n# Item XI\n\n$%\\newcommand{\\fou}[2]{\\widehat{#1}^{(#2)}}$\n$\\newcommand{\\fou}[2]{\\widehat{#1}}$\nUse the Fourier transfrom to solve the following PDE:\n\n\\begin{align}\nu_t - k u_{xx} &= 0 \\text{ and } t>0\n\\\\u(x,0) &= f(x) \\, , \\, x \\in \\mathbb{R}\n\\end{align}\nAssume $f$ and $u \\in L^{2}(\\mathbb{R})$.\n\n\n---\n\n$$\n\\newcommand{2}{\\fou}{}\n$$\n\nWe apply the Fourier transform with respect to the variable $x$ on both equations.\n\nIn the first one:\n\\begin{align}\n\\fou{u_t}{x} - k \\fou{u_{xx}}{x} &= 0\n\\\\ \\fou{u_t}{x} - k(2\\pi i \\xi)^2 \\fou{u}{x} &= 0\n\\\\ \\fou{u_t}{x} + k(2\\pi \\xi)^2 \\fou{u}{x} &= 0 \\, .\n\\end{align}\nWe now use the following property (see this [link](https://www.math.ubc.ca/~feldman/m267/pdeft.pdf)):\n$$\n\\fou{\\frac{\\partial u}{\\partial t}}{x}(\\xi,t) = \\frac{\\partial \\fou{u}{x}(\\xi,t)}{\\partial t} \\,.\n$$ and\n\\begin{align}\n\\\\ \\left(\\fou{u}{x}\\right)_t + k(2\\pi \\xi)^2 \\fou{u}{x} &= 0 \n\\\\ \\left(\\fou{u}{x}\\right)_t &= -k(2\\pi \\xi)^2 \\fou{u}{x} \\, .\n\\end{align}\nThe solution to this ordinary PDE is:\n\\begin{align}\n\\fou{u}{x}(\\xi,t) = c(\\xi)e^{-k(2\\pi \\xi)^2 t} \n\\end{align}\n\nWe can see that at $t=0$:\n\\begin{align}\n\\fou{u}{x}(\\xi,0) &= c(\\xi)\n\\\\ \\fou{f}{x}(\\xi) &= c(\\xi)\n\\end{align}\n\nFinally, the solution is:\n\\begin{align}\n\\fou{u}{x}(\\xi,t) &= \\fou{f}{x}(\\xi)e^{-k(2\\pi \\xi)^2 t} \n\\\\ u(x,t) &= \\int_{-\\infty}^{\\infty} \\fou{f}{x}(\\xi)e^{-k(2\\pi \\xi)^2 t} e^{2\\pi i \\xi x} d\\xi\n\\\\ &= \\int_{-\\infty}^{\\infty} \\fou{f}{x}(\\xi)e^{-k(2\\pi \\xi)^2 t} e^{2\\pi i \\xi x} d\\xi\n\\end{align}\n\n\n```python\ndef discretize(fn,xi,xf,N=101):\n xs = np.linspace(xi,xf,num=N)\n fs = fn(xs)\n return fs\n\n# The discrete fourier transform\ndef discrete_fourier_transform(fs,derivate=0,inverse=False):\n N = fs.shape[0]\n ns = np.arange(N)\n if inverse:\n ts = [(1.0/N)*np.sum(fs*np.exp(1j*2*np.pi*k/N*ns)) for k in range(N)]\n else:\n ts = [np.sum(fs*np.exp(-1j*2*np.pi*k/N*ns)) for k in range(N)]\n return np.array(ts)\n```\n\n\n```python\ndef solve_pde(f,K,xi,xf,tf,N=300,M=50):\n fx = discretize(f,xi,xf,N=N) # u(x,0)\n ees = np.arange(N)/(xf-xi)\n fxt = discrete_fourier_transform(fx)\n ts = np.linspace(0,tf,num=M)\n funct = lambda t: fxt*np.exp(-K*(2*np.pi*ees)**2*t)\n uts = [discrete_fourier_transform(funct(t),inverse=True) for t in ts]\n return uts\n```\n\n\n```python\nX_I = -4\nX_F = 4\nKK = 0.2\nT_F = 10.0\n\n# We test with a function, say:\nF_MAX = 1\nfn = lambda x: np.exp(-x**2.0)\nus = solve_pde(fn,K=KK,xi=X_I,xf=X_F,tf=T_F)\nxs = np.linspace(X_I,X_F,num=us[0].shape[0])\n\ndef plot_at_time(i=0):\n plt.plot(xs,us[i],'-')\n plt.ylim((0,F_MAX))\n plt.grid()\n plt.title(\"$u(x,t=%f)$\"%(T_F*i/(len(us)-1.0)))\n plt.show()\n\ninteract(plot_at_time,i=(0,len(us)-1),continuous_update=False)\n```\n\n\n interactive(children=(IntSlider(value=0, description='i', max=49), Output()), _dom_classes=('widget-interact',…\n\n\n\n\n\n \n\n\n\n---\n\n# Item XII\n\nLet $\\ddot{y}(t)-\\mu (1-y^2(t)) \\dot{y}(t) + y(t) = 0$, with $y(0)=2$ , $\\dot{y}(0)=0$, and $\\mu = 1234$.\n1. Approximate the solution by means of a Taylor series expansion about $t=0$.\n2. Implement a numerical solver for it. *You may not use scipy but you can use numpy*.\n3. Compare both solutions and comment on the comparison.\n---\n\n## Part 1\n\nWe do the approximation:\n\\begin{align}\ny(t) &= y(0) + t \\dot{y}(0) + \\frac{1}{2} t^2 \\ddot{y}(0)\n\\\\ &= 2 + \\frac{1}{2}t^2\\ddot{y}(0) \\,.\n\\end{align}\n\nIn order to compute $\\ddot{y}(0)$ we use the equation given, at $t=0$:\n\\begin{align}\n\\ddot{y}(0) - \\mu(1-y^2(0)) \\dot{y}(0) + y(0) &= 0\n\\\\ \\ddot{y}(0) &= -y(0)\n\\\\ &= -2 \\, .\n\\end{align}\n\nAnd the approximation is $$y(t) = 2-t^2 \\,.$$\n\n## Part 2\n\n\n```python\n# Euler's method as a higher order function:\ndef euler(yp=lambda y,t:1,yi=0,tmin=0,tmax=1.0,steps=400):\n delta = (tmax-tmin)/float(steps)\n t = tmin\n ys = []\n ys.append(yi)\n for i in range(steps):\n t = tmin+delta*i\n yp_next = yp(ys[-1],t)\n y_next = ys[-1]+delta*yp_next\n ys.append(y_next)\n return ys\n```\n\nWe use it in the following way:\n\n$$\n\\begin{bmatrix} y_{t+1} \\\\ \\dot{y}_{y+1} \\end{bmatrix}\n=\n\\begin{bmatrix} \\dot{y}_{t} \\\\ \\ddot{y}(t) \\end{bmatrix} \\Delta t\n+ \n\\begin{bmatrix} y_{t} \\\\ \\dot{y}_t \\end{bmatrix} \\Delta t\n$$\n\nremembering that\n$$\n\\ddot{y}(t) = \\mu (1-y^2(t)) \\dot{y}(t) - y(t) = 0\n$$\n\n\n```python\nmu = 1234\nN = 40000\nYF = 4.0\nxs = np.linspace(0,YF,num=N+1)\n# --- Approximation with Taylor\ny_tay = 2-xs**2.0\n# --- Solution:\nfn = lambda ys,t: np.array([ys[1], mu*(1-ys[0]**2)*ys[1] - ys[0]])\nyini = np.array([2,0])\nresult = euler(fn,yini,tmin=0,tmax=YF,steps=N)\ny_sol = [a[0] for a in result]\nyp_sol = [a[1] for a in result]\n# --- Print values at some points:\nNS = (N//4,N//2,N*3//4,N)\nprint(\"Taylor:\")\nfor i in NS:\n print(\"\\ty(%f) = %f\"%(xs[i],y_tay[i]))\nprint(\"Euler's:\")\nfor i in NS:\n print(\"\\ty(%f) = %f\"%(xs[i],y_sol[i]))\n```\n\n Taylor:\n \ty(1.000000) = 1.000000\n \ty(2.000000) = -2.000000\n \ty(3.000000) = -7.000000\n \ty(4.000000) = -14.000000\n Euler's:\n \ty(1.000000) = 1.999460\n \ty(2.000000) = 1.998919\n \ty(3.000000) = 1.998378\n \ty(4.000000) = 1.997837\n\n\n## Part 3\n\nPlot both solutions:\n\n\n```python\nplt.plot(xs,y_tay,label=\"Taylor approx.\")\nplt.plot(xs,y_sol,label=\"Euler's method\")\nplt.grid()\nplt.legend()\nplt.show()\n```\n\nIt can be seen that the Taylor's approximation is bad as it doens't consider that $y''(t)$ is really small except on $t=0$ (due the large value of $\\mu$).\n\n\n```python\nplt.plot(xs,yp_sol,label=\"Euler's y'(t)\")\nplt.grid()\nplt.legend()\nplt.show()\n```\n\n# Item XIII\nLet $\\gamma$ be a positively oriented circular path with center $0$ at radious $\\alpha >2$, compute the following:\n* $\\int_{\\gamma} \\frac{\\exp(z)}{z} \\partial z = 2\\pi i$\n* $\\int_{\\gamma} \\frac{\\exp(z)}{z(z-1)} \\partial z = 2\\pi i (e-1)$\n* $\\int_{\\gamma} \\frac{\\exp(z)}{z^3} \\partial z = \\pi i$\n\n\\* **Note**: It seems that the exercises aren't correct.\n\n---\n\nWe make use of the definition of the line integral:\n$$\n\\int_{\\mathcal {C}}f(\\mathbf {r} )\\,ds=\\int _{a}^{b}f\\left(\\mathbf {r} (t)\\right) \\mathbf {r} '(t)\\,dt.\n$$\nIn particular, if the curve is a circunference of radious $r$ we can parametrize over the angle $\\theta$:\n$$\n\\int_{0}^{2\\pi} f\\left(\\, (r \\cos(\\theta), r \\sin(\\theta))\\, \\right) \\, (\\cos(\\theta)+i \\sin(\\theta))'r \\, \\partial \\theta\n$$\nIn particular, if the axis $Y$ is for imaginary numbers:\n$$\n\\int_{0}^{2\\pi} f\\left( r \\cos(\\theta) + r \\sin(\\theta) i \\right) \\, (-\\sin(\\theta)+ i\\cos(\\theta))r \\, \\partial \\theta\n$$\nUsing cuadrature:\n$$\n \\frac{2 \\pi}{n} \\sum_{i=0}^{n-1} f (r \\cos(\\theta_i)+ r \\sin(\\theta_i) i ) \\, (-r \\sin(\\theta_i)+ r i\\cos(\\theta_i))\n$$\n\n\n```python\n# Define the integral approximated as a Riemman sum (not the best way but the easiest).\ndef circle_integral(fn,rad,imaginary_y=False,vectorized=False,n=300):\n ts = np.linspace(0,2*np.pi,num=n,endpoint=False)\n \n xs = rad*np.cos(ts)\n ys = rad*np.sin(ts)\n \n if imaginary_y:\n if vectorized:\n fs = fn(xs+ys*1j)*(-ys+xs*1j)\n else:\n fs = [fn(x+y*1j)*(-y+x*1j) for x,y in zip(xs,ys)]\n else:\n if vectorized:\n fs = fn(xs,ys)*(-ys+xs*1j)\n else:\n fs = [fn(x,y)*(-y+x*1j) for x,y in zip(xs,ys)]\n \n return (2*np.pi/n)*np.sum(fs)\n```\n\nWe compute the intergrals. In order to get the asked results we should consider circular paths where the component Y is imaginary:\n\n\n```python\nfunctions = [\n (\"item1\", lambda z: np.exp(z)/z, lambda a: 2*np.pi*1j),\n (\"item2\", lambda z: np.exp(z)/(z*(z-1)), lambda a: 2*np.pi*1j*(np.e-1)),\n (\"item3\", lambda z: np.exp(z)/z**3, lambda a: np.pi*1j),\n]\n\nfor name,fun,val in functions:\n print(name+\":\")\n for alpha in np.arange(2.5,5.01,0.5):\n fun_eval = circle_integral(fun,alpha,imaginary_y=True,vectorized=True)\n fun_eval = round(fun_eval,6)\n val_eval = val(alpha)\n print(\"\\talpha=%4.2f:\"%alpha)\n print(\"\\t\\tfun_eval:%s\"%fun_eval)\n print(\"\\t\\tval_eval:%s\"%val_eval)\n```\n\n item1:\n \talpha=2.50:\n \t\tfun_eval:(-0+6.283185j)\n \t\tval_eval:6.283185307179586j\n \talpha=3.00:\n \t\tfun_eval:6.283185j\n \t\tval_eval:6.283185307179586j\n \talpha=3.50:\n \t\tfun_eval:(-0+6.283185j)\n \t\tval_eval:6.283185307179586j\n \talpha=4.00:\n \t\tfun_eval:(-0+6.283185j)\n \t\tval_eval:6.283185307179586j\n \talpha=4.50:\n \t\tfun_eval:(-0+6.283185j)\n \t\tval_eval:6.283185307179586j\n \talpha=5.00:\n \t\tfun_eval:(-0+6.283185j)\n \t\tval_eval:6.283185307179586j\n item2:\n \talpha=2.50:\n \t\tfun_eval:(-0+10.796283j)\n \t\tval_eval:10.796283138167546j\n \talpha=3.00:\n \t\tfun_eval:10.796283j\n \t\tval_eval:10.796283138167546j\n \talpha=3.50:\n \t\tfun_eval:10.796283j\n \t\tval_eval:10.796283138167546j\n \talpha=4.00:\n \t\tfun_eval:(-0+10.796283j)\n \t\tval_eval:10.796283138167546j\n \talpha=4.50:\n \t\tfun_eval:(-0+10.796283j)\n \t\tval_eval:10.796283138167546j\n \talpha=5.00:\n \t\tfun_eval:(-0+10.796283j)\n \t\tval_eval:10.796283138167546j\n item3:\n \talpha=2.50:\n \t\tfun_eval:3.141593j\n \t\tval_eval:3.141592653589793j\n \talpha=3.00:\n \t\tfun_eval:3.141593j\n \t\tval_eval:3.141592653589793j\n \talpha=3.50:\n \t\tfun_eval:(-0+3.141593j)\n \t\tval_eval:3.141592653589793j\n \talpha=4.00:\n \t\tfun_eval:(-0+3.141593j)\n \t\tval_eval:3.141592653589793j\n \talpha=4.50:\n \t\tfun_eval:(-0+3.141593j)\n \t\tval_eval:3.141592653589793j\n \talpha=5.00:\n \t\tfun_eval:3.141593j\n \t\tval_eval:3.141592653589793j\n\n\nIt can be seen that the results aren't the same.\n\n# Item XIV\n\nShow that the following Laurent expansion is valid in $1 < |z| < 2$:\n$$\n\\frac{-1}{(z-1)(z-2)} = \\sum_{n=0}^\\infty \\frac{z^n}{2^{n+1}} + \\sum_{n=1}^\\infty \\frac{1}{z^n} \\,,\n$$\nand draw an sketch of the region. Does it exist an expansion when $|z|>2$? If so, please compute it.\n\n\\* **Note**: I had to change the $1$ with $-1$, for the exercise to be correct.\n\n---\n\nWe have that:\n\\begin{align*}\n\\sum_{n=0}^{\\infty} \\frac{z^n}{2^{n+1}} &= \\frac{1}{2} \\sum_{n=0}^{\\infty} \\frac{z^n}{2^n}\n\\\\ &= \\frac{1}{2} \\sum_{n=0}^{\\infty} \\left( z/2 \\right)^n\n\\\\ &= \\frac{1}{2} \\frac{1}{1-z/2} \\quad \\text{as long as $|z/2|<1$.}\n\\\\ &= \\frac{1}{2-z}\n\\end{align*}\nAnd for the other sum:\n\\begin{align*}\n\\sum_{n=1}^{\\infty} \\frac{1}{z^n}\n&= -1 + \\sum_{n=0}^{\\infty} \\frac{1}{z^n}\n\\\\ &= -1 + \\sum_{n=0}^{\\infty} (1/z)^n\n\\\\ &= -1 + \\frac{1}{1-(1/z)} \\quad \\text{as long as $(|1/z|<1) \\Leftrightarrow (z<-1) \\vee (z>1)$.}\n\\\\ &= \\frac{1}{z-1}\n\\end{align*}\nAdding both results:\n\\begin{align}\n\\frac{1}{2-z} + \\frac{1}{z-1} &= \\frac{-1}{(z-1)(z-2)}\n\\end{align}\n\n\n```python\n# Function to plot a function\ndef plot_fun(fn,xi,xf,vectorized=False,n=101,**args):\n xs = np.linspace(xi,xf,num=n)\n if vectorized:\n ys = fn(xs)\n else:\n ys = [fn(x) for x in xs]\n plt.plot(xs,ys,'-',**args)\n```\n\n\n```python\n# The sums, limiting n:\ndef sums(z,n_max):\n ns = np.arange(n_max+1)\n sum1 = np.sum(z**ns/2**(ns+1))\n sum2 = np.sum(1/z**ns[1:])\n return sum1+sum2\n```\n\n\n```python\n# We plot the region\nplt.figure(figsize=(8,6))\nplot_fun(lambda x: -1/((x-1)*(x-2)),0,3,vectorized=True,label=\"$\\\\frac{1}{(1-z)(2-z)}$\")\nplot_fun(lambda x: sums(x,2),0,3,label=\"sums up to $n=2$\",c=(.6,.6,.6))\nplot_fun(lambda x: sums(x,4),0,3,label=\"sums up to $n=4$\",c=(.4,.4,.4))\nplot_fun(lambda x: sums(x,8),0,3,label=\"sums up to $n=8$\",c=(.2,.2,.2))\nplot_fun(lambda x: sums(x,16),0,3,label=\"sums up to $n=16$\",c=(.0,.0,.0))\nplt.ylim((-20,20))\nplt.legend()\nplt.grid()\nplt.show()\n```\n\nWe can see that it converges in $1<|z|<2$ as $n \\rightarrow \\infty$.\n\n---\n\nWe can get the Laurent expansion of the series when $|z|>2$, if we make use of:\n$$\n\\frac{1}{1-z} = \\sum_{n=1}^\\infty \\frac{1}{z^n} \\quad \\text{if $|z|>1$} \\,.\n$$\nWe proceed:\n\\begin{align*}\n\\frac{1}{(z-1)(z-2)} &= \\frac{1}{2-z} + \\frac{1}{z-1}\n\\\\ &= \\frac{1}{2} \\cdot \\frac{1}{1-\\frac{z}{2}} - 1 \\cdot \\frac{1}{1-z}\n\\\\ &= \\frac{-1}{2} \\sum_{n=1}^\\infty \\frac{1}{(z/2)^n} + 1 \\sum_{n=1}^\\infty \\frac{1}{z^n}\n\\\\ &= \\frac{-1}{2} \\sum_{n=1}^\\infty \\frac{2^n}{z^n} + 1 \\sum_{n=1}^\\infty \\frac{1}{z^n}\n\\end{align*}\n\n\n\n```python\n# The new sums, limiting n:\ndef sums2(z,n_max):\n ns = np.arange(n_max+1)\n sum1 = -0.5*np.sum(2**ns[1:]/z**ns[1:])\n sum2 = np.sum(1/z**ns[1:])\n return sum1+sum2\n```\n\n\n```python\n# We plot the region, again\nplt.figure(figsize=(8,6))\nplot_fun(lambda x: -1/((x-1)*(x-2)),0,3,vectorized=True,label=\"$\\\\frac{1}{(1-z)(2-z)}$\")\nplot_fun(lambda x: sums2(x,2),0,3,label=\"sums up to $n=2$\",c=(.6,.6,.6))\nplot_fun(lambda x: sums2(x,4),0,3,label=\"sums up to $n=4$\",c=(.4,.4,.4))\nplot_fun(lambda x: sums2(x,8),0,3,label=\"sums up to $n=8$\",c=(.2,.2,.2))\nplot_fun(lambda x: sums2(x,16),0,3,label=\"sums up to $n=16$\",c=(.0,.0,.0))\nplt.ylim((-20,20))\nplt.legend()\nplt.grid()\nplt.show()\n```\n\nWe can see that it converges to the function when $|z|>2$ as $n \\rightarrow \\infty$.\n\n## References\n* http://sym.lboro.ac.uk/resources/Handout-Laurent.pdf\n\n---\n\n# Item XV\n\nConsidering the following inner product:\n$$\n\\langle p(x),q(x) \\rangle =\\int_{-1}^{1} \\overline{p(x)}q(x) dx\n$$\n\n* Let $A= [1|x|x^2|...|x^{n-1}]$ be the \"matrix\" whose \"columns\" are the monomials $x^j$, for $j=0,...,n-1$. Each column is a function in $L^2[-1,1]$. compute the $QR$ decomposition of $A$.\n* Let $A=[1|\\sin(2\\pi x)|\\sin(4\\pi x)|...|x^{n-1}]$ be the \"matrix\" whose \"columns\" are the functions $1$ and $\\sin(2\\pi x)$, for $j=1,...,n-1$. Each column is a function in $L^2[-1,1]$. Compute the $QR$ decomposition of $A$. \n* Do part (a) numerically. Make sure you understand what you are doing since this is a important concept that links symbolic computing with numerical computing.\n\n---\n\n\n```python\n# This is a generic version of Gram-Schmidt, by default it works on matrices.\n# For other uses, replace default argument functions.\ndef generic_gs(\n elems,\n scalar = lambda a,x : a*x,\n prod = lambda x,y : np.sum(x*y),\n neg = lambda x,y : x-y,\n ):\n \"\"\"\n elems = [T]\n scalar :: T -> Float -> T\n prod :: T -> T -> Float\n neg :: T -> T -> T\n NOTE: if is used for a regular matrix, elems must be row-wise.\n \"\"\"\n n = len(elems)\n r = np.zeros((n,n))\n for i in range(n):\n for j in range(i):\n projection = prod(elems[j],elems[i])/prod(elems[j],elems[j])\n r[j,i] = projection\n elems[i] = neg(elems[i],scalar(projection,elems[j]))\n norm2 = prod(elems[i],elems[i])\n if norm2<0:\n print(\"Warning: negative norm2=%f at i=%d!\"%(norm2,i))\n return None\n norm = norm2**0.5\n r[i,i] = norm\n elems[i] = scalar(norm**-1,elems[i])\n return r\n```\n\n\n```python\ndef symbolic_inner_product(f,q):\n x = sympy.Symbol('x')\n v = sympy.integrate(f*q,(x,-1,1))\n # We evaluate the expresion as a number because we can't afford the whole symbolic\n # expression...\n return float(v)\n```\n\n\n```python\n# We define the list of functions for part a\ndef part_a_funcs(n):\n x = sympy.Symbol('x')\n part = [x**i for i in range(n)]\n return part\n```\n\n\n```python\ndef part_b_funcs(n):\n x = sympy.Symbol('x')\n part = [x**0] + [sympy.sin(2*i*sympy.pi*x) for i in range(1,n)]\n return part\n```\n\n\n```python\n# We can print an array of functions:\nprint(part_a_funcs(10))\nprint(part_b_funcs(10))\n```\n\n [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9]\n [1, sin(2*pi*x), sin(4*pi*x), sin(6*pi*x), sin(8*pi*x), sin(10*pi*x), sin(12*pi*x), sin(14*pi*x), sin(16*pi*x), sin(18*pi*x)]\n\n\n\n```python\n# We compute the decompositions\nFUNCS = [part_a_funcs(5),part_b_funcs(5),\n part_a_funcs(20),part_b_funcs(20),\n part_a_funcs(100),part_b_funcs(100)]\nfor funcs in FUNCS:\n # Print Original matrix\n print(\"-\"*20+\"Functions:\")\n print(funcs)\n # Perform QR decomposition using generic G-S\n r = generic_gs(funcs,prod=symbolic_inner_product)\n if r is None:\n print(\"Couldn't compute R!!!:\")\n else:\n # Print Q\n print(\"Q:\")\n print(funcs)\n # Print R\n print(\"R:\")\n print(r)\n```\n\n --------------------Functions:\n [1, x, x**2, x**3, x**4]\n Q:\n [0.707106781186547, 1.22474487139159*x, 2.37170824512628*x**2 - 0.790569415042095, 4.67707173346743*x**3 - 2.80624304008046*x, 9.28077650307342*x**4 - 7.95495128834865*x**2 + 0.795495128834865]\n R:\n [[1.41421356 0. 0.47140452 0. 0.28284271]\n [0. 0.81649658 0. 0.48989795 0. ]\n [0. 0. 0.42163702 0. 0.36140316]\n [0. 0. 0. 0.21380899 0. ]\n [0. 0. 0. 0. 0.1077496 ]]\n --------------------Functions:\n [1, sin(2*pi*x), sin(4*pi*x), sin(6*pi*x), sin(8*pi*x)]\n Q:\n [0.707106781186547, 1.0*sin(2*pi*x), 1.0*sin(4*pi*x), 1.0*sin(6*pi*x), 1.0*sin(8*pi*x)]\n R:\n [[1.41421356 0. 0. 0. 0. ]\n [0. 1. 0. 0. 0. ]\n [0. 0. 1. 0. 0. ]\n [0. 0. 0. 1. 0. ]\n [0. 0. 0. 0. 1. ]]\n --------------------Functions:\n [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11, x**12, x**13, x**14, x**15, x**16, x**17, x**18, x**19]\n Q:\n [0.707106781186547, 1.22474487139159*x, 2.37170824512628*x**2 - 0.790569415042095, 4.67707173346743*x**3 - 2.80624304008046*x, 9.28077650307342*x**4 - 7.95495128834865*x**2 + 0.795495128834865, 18.4685120543046*x**5 - 20.5205689492274*x**3 + 4.39726477483447*x, 36.8085471137496*x**6 - 50.1934733369312*x**4 + 16.731157778977*x**2 - 0.796721798998903, 73.4290553655101*x**7 - 118.616166359671*x**5 + 53.9164392543961*x**3 - 5.9907154727108*x, 146.570997825597*x**8 - 273.599195941143*x**6 + 157.845689966067*x**4 - 28.6992163574728*x**2 + 0.797200454374528, 292.689266429782*x**9 - 619.812564204472*x**7 + 433.868794943332*x**5 - 111.248408959896*x**3 + 7.58511879272651*x, 584.646351835467*x**10 - 1384.68872802706*x**8 + 1140.33189366472*x**6 - 380.110631219486*x**4 + 43.8589189865218*x**2 - 0.79743489065461, 1168.08413179724*x**11 - 3059.26796431391*x**9 + 2898.25386102658*x**7 - 1193.39864870916*x**5 + 198.899774796064*x**3 - 9.17998960667973*x, 2334.1394542848*x**12 - 6697.96538974081*x**10 + 7176.39148793533*x**8 - 3525.24494077784*x**6 + 777.627560274535*x**4 - 62.2102048010054*x**2 + 0.797566727821615, 4664.8247961001*x**13 - 14554.2533510225*x**11 + 17401.824641446*x**9 - 9943.89978380936*x**7 + 2747.65651566431*x**5 - 323.25370725723*x**3 + 10.7751235584056*x, 9323.69774897047*x**14 - 31424.3145392121*x**12 + 41480.0950357262*x**10 - 27052.2357651977*x**8 + 9017.41186696691*x**6 - 1423.8018622434*x**4 + 83.7530497845978*x**2 - 0.797648080132224, 18637.0288570101*x**15 - 67478.8968030333*x**13 + 97469.5161890552*x**11 - 71477.643886015*x**9 + 27969.5121573176*x**7 - 5593.90225536597*x**5 + 490.69315947496*x**3 - 12.3704150610011*x, 37255.8196048632*x**16 - 144216.132304494*x**14 + 226270.239829557*x**12 - 184368.438761031*x**10 + 82965.8474262938*x**8 - 20200.3946203341*x**6 + 2404.8109348184*x**4 - 108.487824155802*x**2 + 0.797705620723317, 74479.6642568353*x**17 - 306946.405948985*x**15 + 519828.403493602*x**13 - 466052.839993619*x**11 + 237341.58597819*x**9 - 68354.3246558744*x**7 + 10401.73440399*x**5 - 707.59997666341*x**3 + 13.9657605808844*x, 148890.480388317*x**18 - 650867.820226831*x**16 + 1183404.11036741*x**14 - 1157964.1066223*x**12 + 658848.305301026*x**10 - 219618.867623267*x**8 + 40996.1779316701*x**6 - 3819.59915037231*x**4 + 136.418051302983*x**2 - 0.797797143973976, 297830.260121396*x**19 - 1376466.304985*x**17 + 2674292.07935306*x**15 - 2836385.47335974*x**13 + 1784186.56529593*x**11 - 676762.982328085*x**9 + 150392.04700999*x**7 - 18047.0137902493*x**5 + 980.807898993961*x**3 - 15.5680677297265*x]\n R:\n [[1.41421356e+00 0.00000000e+00 4.71404521e-01 0.00000000e+00\n 2.82842712e-01 0.00000000e+00 2.02030509e-01 0.00000000e+00\n 1.57134840e-01 0.00000000e+00 1.28564869e-01 0.00000000e+00\n 1.08785659e-01 0.00000000e+00 9.42809042e-02 0.00000000e+00\n 8.31890331e-02 0.00000000e+00 7.44322928e-02 0.00000000e+00]\n [0.00000000e+00 8.16496581e-01 0.00000000e+00 4.89897949e-01\n 0.00000000e+00 3.49927106e-01 0.00000000e+00 2.72165527e-01\n 0.00000000e+00 2.22680886e-01 0.00000000e+00 1.88422288e-01\n 0.00000000e+00 1.63299316e-01 0.00000000e+00 1.44087632e-01\n 0.00000000e+00 1.28920513e-01 0.00000000e+00 1.16642369e-01]\n [0.00000000e+00 0.00000000e+00 4.21637021e-01 0.00000000e+00\n 3.61403161e-01 0.00000000e+00 3.01169301e-01 0.00000000e+00\n 2.55537589e-01 0.00000000e+00 2.21138298e-01 0.00000000e+00\n 1.94601702e-01 0.00000000e+00 1.73615244e-01 0.00000000e+00\n 1.56645333e-01 0.00000000e+00 1.42659143e-01 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 2.13808994e-01\n 0.00000000e+00 2.37565548e-01 0.00000000e+00 2.26767114e-01\n 0.00000000e+00 2.09323490e-01 0.00000000e+00 1.91879866e-01\n 0.00000000e+00 1.76077995e-01 0.00000000e+00 1.62177100e-01\n 0.00000000e+00 1.50041399e-01 0.00000000e+00 1.39440648e-01]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 1.07749605e-01 0.00000000e+00 1.46931279e-01 0.00000000e+00\n 1.58233685e-01 0.00000000e+00 1.58233685e-01 0.00000000e+00\n 1.53579753e-01 0.00000000e+00 1.47113237e-01 0.00000000e+00\n 1.40107845e-01 0.00000000e+00 1.33145965e-01 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 5.41462137e-02 0.00000000e+00 8.74669606e-02\n 0.00000000e+00 1.04960353e-01 0.00000000e+00 1.13192537e-01\n 0.00000000e+00 1.16171288e-01 0.00000000e+00 1.16171288e-01\n 0.00000000e+00 1.14487646e-01 0.00000000e+00 1.11870786e-01]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 2.71676031e-02 0.00000000e+00\n 5.07128592e-02 0.00000000e+00 6.71199607e-02 0.00000000e+00\n 7.77178492e-02 0.00000000e+00 8.41943367e-02 0.00000000e+00\n 8.78549600e-02 0.00000000e+00 8.96120592e-02 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.36185873e-02\n 0.00000000e+00 2.88393613e-02 0.00000000e+00 4.17411809e-02\n 0.00000000e+00 5.16795572e-02 0.00000000e+00 5.89821034e-02\n 0.00000000e+00 6.41725285e-02 0.00000000e+00 6.77376689e-02]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 6.82263214e-03 0.00000000e+00 1.61588656e-02 0.00000000e+00\n 2.53925031e-02 0.00000000e+00 3.34886635e-02 0.00000000e+00\n 4.01863962e-02 0.00000000e+00 4.55445823e-02 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 3.41659266e-03 0.00000000e+00 8.94821888e-03\n 0.00000000e+00 1.51730668e-02 0.00000000e+00 2.12422935e-02\n 0.00000000e+00 2.67495548e-02 0.00000000e+00 3.15460267e-02]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 1.71043571e-03 0.00000000e+00\n 4.90820683e-03 0.00000000e+00 8.93293643e-03 0.00000000e+00\n 1.32339799e-02 0.00000000e+00 1.74551631e-02 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 8.56102718e-04\n 0.00000000e+00 2.67104048e-03 0.00000000e+00 5.19368982e-03\n 0.00000000e+00 8.11887144e-03 0.00000000e+00 1.11961856e-02]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 4.28423417e-04 0.00000000e+00 1.44394559e-03 0.00000000e+00\n 2.98747362e-03 0.00000000e+00 4.91487596e-03 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 2.14370323e-04 0.00000000e+00 7.76168403e-04\n 0.00000000e+00 1.70256298e-03 0.00000000e+00 2.94079059e-03]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 1.07253584e-04 0.00000000e+00\n 4.15175326e-04 0.00000000e+00 9.62451912e-04 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 5.36566213e-05\n 0.00000000e+00 2.21130254e-04 0.00000000e+00 5.40189792e-04]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 2.68414441e-05 0.00000000e+00 1.17336126e-04 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 1.34264837e-05 0.00000000e+00 6.20524672e-05]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 6.71634612e-06 0.00000000e+00]\n [0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 0.00000000e+00 3.35761719e-06]]\n --------------------Functions:\n [1, sin(2*pi*x), sin(4*pi*x), sin(6*pi*x), sin(8*pi*x), sin(10*pi*x), sin(12*pi*x), sin(14*pi*x), sin(16*pi*x), sin(18*pi*x), sin(20*pi*x), sin(22*pi*x), sin(24*pi*x), sin(26*pi*x), sin(28*pi*x), sin(30*pi*x), sin(32*pi*x), sin(34*pi*x), sin(36*pi*x), sin(38*pi*x)]\n Q:\n [0.707106781186547, 1.0*sin(2*pi*x), 1.0*sin(4*pi*x), 1.0*sin(6*pi*x), 1.0*sin(8*pi*x), 1.0*sin(10*pi*x), 1.0*sin(12*pi*x), 1.0*sin(14*pi*x), 1.0*sin(16*pi*x), 1.0*sin(18*pi*x), 1.0*sin(20*pi*x), 1.0*sin(22*pi*x), 1.0*sin(24*pi*x), 1.0*sin(26*pi*x), 1.0*sin(28*pi*x), 1.0*sin(30*pi*x), 1.0*sin(32*pi*x), 1.0*sin(34*pi*x), 1.0*sin(36*pi*x), 1.0*sin(38*pi*x)]\n R:\n [[1.41421356 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 1. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 1. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 1.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 1. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 1. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 1. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 1. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 1.\n 0. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 1. 0. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 1. 0. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 1. 0. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 1. 0. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 1. 0.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 1.\n 0. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 1. 0. ]\n [0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0.\n 0. 1. ]]\n --------------------Functions:\n [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11, x**12, x**13, x**14, x**15, x**16, x**17, x**18, x**19, x**20, x**21, x**22, x**23, x**24, x**25, x**26, x**27, x**28, x**29, x**30, x**31, x**32, x**33, x**34, x**35, x**36, x**37, x**38, x**39, x**40, x**41, x**42, x**43, x**44, x**45, x**46, x**47, x**48, x**49, x**50, x**51, x**52, x**53, x**54, x**55, x**56, x**57, x**58, x**59, x**60, x**61, x**62, x**63, x**64, x**65, x**66, x**67, x**68, x**69, x**70, x**71, x**72, x**73, x**74, x**75, x**76, x**77, x**78, x**79, x**80, x**81, x**82, x**83, x**84, x**85, x**86, x**87, x**88, x**89, x**90, x**91, x**92, x**93, x**94, x**95, x**96, x**97, x**98, x**99]\n Warning: negative norm2=-0.000000 at i=24!\n Couldn't compute R!!!:\n --------------------Functions:\n [1, sin(2*pi*x), sin(4*pi*x), sin(6*pi*x), sin(8*pi*x), sin(10*pi*x), sin(12*pi*x), sin(14*pi*x), sin(16*pi*x), sin(18*pi*x), sin(20*pi*x), sin(22*pi*x), sin(24*pi*x), sin(26*pi*x), sin(28*pi*x), sin(30*pi*x), sin(32*pi*x), sin(34*pi*x), sin(36*pi*x), sin(38*pi*x), sin(40*pi*x), sin(42*pi*x), sin(44*pi*x), sin(46*pi*x), sin(48*pi*x), sin(50*pi*x), sin(52*pi*x), sin(54*pi*x), sin(56*pi*x), sin(58*pi*x), sin(60*pi*x), sin(62*pi*x), sin(64*pi*x), sin(66*pi*x), sin(68*pi*x), sin(70*pi*x), sin(72*pi*x), sin(74*pi*x), sin(76*pi*x), sin(78*pi*x), sin(80*pi*x), sin(82*pi*x), sin(84*pi*x), sin(86*pi*x), sin(88*pi*x), sin(90*pi*x), sin(92*pi*x), sin(94*pi*x), sin(96*pi*x), sin(98*pi*x), sin(100*pi*x), sin(102*pi*x), sin(104*pi*x), sin(106*pi*x), sin(108*pi*x), sin(110*pi*x), sin(112*pi*x), sin(114*pi*x), sin(116*pi*x), sin(118*pi*x), sin(120*pi*x), sin(122*pi*x), sin(124*pi*x), sin(126*pi*x), sin(128*pi*x), sin(130*pi*x), sin(132*pi*x), sin(134*pi*x), sin(136*pi*x), sin(138*pi*x), sin(140*pi*x), sin(142*pi*x), sin(144*pi*x), sin(146*pi*x), sin(148*pi*x), sin(150*pi*x), sin(152*pi*x), sin(154*pi*x), sin(156*pi*x), sin(158*pi*x), sin(160*pi*x), sin(162*pi*x), sin(164*pi*x), sin(166*pi*x), sin(168*pi*x), sin(170*pi*x), sin(172*pi*x), sin(174*pi*x), sin(176*pi*x), sin(178*pi*x), sin(180*pi*x), sin(182*pi*x), sin(184*pi*x), sin(186*pi*x), sin(188*pi*x), sin(190*pi*x), sin(192*pi*x), sin(194*pi*x), sin(196*pi*x), sin(198*pi*x)]\n Q:\n [0.707106781186547, 1.0*sin(2*pi*x), 1.0*sin(4*pi*x), 1.0*sin(6*pi*x), 1.0*sin(8*pi*x), 1.0*sin(10*pi*x), 1.0*sin(12*pi*x), 1.0*sin(14*pi*x), 1.0*sin(16*pi*x), 1.0*sin(18*pi*x), 1.0*sin(20*pi*x), 1.0*sin(22*pi*x), 1.0*sin(24*pi*x), 1.0*sin(26*pi*x), 1.0*sin(28*pi*x), 1.0*sin(30*pi*x), 1.0*sin(32*pi*x), 1.0*sin(34*pi*x), 1.0*sin(36*pi*x), 1.0*sin(38*pi*x), 1.0*sin(40*pi*x), 1.0*sin(42*pi*x), 1.0*sin(44*pi*x), 1.0*sin(46*pi*x), 1.0*sin(48*pi*x), 1.0*sin(50*pi*x), 1.0*sin(52*pi*x), 1.0*sin(54*pi*x), 1.0*sin(56*pi*x), 1.0*sin(58*pi*x), 1.0*sin(60*pi*x), 1.0*sin(62*pi*x), 1.0*sin(64*pi*x), 1.0*sin(66*pi*x), 1.0*sin(68*pi*x), 1.0*sin(70*pi*x), 1.0*sin(72*pi*x), 1.0*sin(74*pi*x), 1.0*sin(76*pi*x), 1.0*sin(78*pi*x), 1.0*sin(80*pi*x), 1.0*sin(82*pi*x), 1.0*sin(84*pi*x), 1.0*sin(86*pi*x), 1.0*sin(88*pi*x), 1.0*sin(90*pi*x), 1.0*sin(92*pi*x), 1.0*sin(94*pi*x), 1.0*sin(96*pi*x), 1.0*sin(98*pi*x), 1.0*sin(100*pi*x), 1.0*sin(102*pi*x), 1.0*sin(104*pi*x), 1.0*sin(106*pi*x), 1.0*sin(108*pi*x), 1.0*sin(110*pi*x), 1.0*sin(112*pi*x), 1.0*sin(114*pi*x), 1.0*sin(116*pi*x), 1.0*sin(118*pi*x), 1.0*sin(120*pi*x), 1.0*sin(122*pi*x), 1.0*sin(124*pi*x), 1.0*sin(126*pi*x), 1.0*sin(128*pi*x), 1.0*sin(130*pi*x), 1.0*sin(132*pi*x), 1.0*sin(134*pi*x), 1.0*sin(136*pi*x), 1.0*sin(138*pi*x), 1.0*sin(140*pi*x), 1.0*sin(142*pi*x), 1.0*sin(144*pi*x), 1.0*sin(146*pi*x), 1.0*sin(148*pi*x), 1.0*sin(150*pi*x), 1.0*sin(152*pi*x), 1.0*sin(154*pi*x), 1.0*sin(156*pi*x), 1.0*sin(158*pi*x), 1.0*sin(160*pi*x), 1.0*sin(162*pi*x), 1.0*sin(164*pi*x), 1.0*sin(166*pi*x), 1.0*sin(168*pi*x), 1.0*sin(170*pi*x), 1.0*sin(172*pi*x), 1.0*sin(174*pi*x), 1.0*sin(176*pi*x), 1.0*sin(178*pi*x), 1.0*sin(180*pi*x), 1.0*sin(182*pi*x), 1.0*sin(184*pi*x), 1.0*sin(186*pi*x), 1.0*sin(188*pi*x), 1.0*sin(190*pi*x), 1.0*sin(192*pi*x), 1.0*sin(194*pi*x), 1.0*sin(196*pi*x), 1.0*sin(198*pi*x)]\n R:\n [[1.41421356 0. 0. ... 0. 0. 0. ]\n [0. 1. 0. ... 0. 0. 0. ]\n [0. 0. 1. ... 0. 0. 0. ]\n ...\n [0. 0. 0. ... 1. 0. 0. ]\n [0. 0. 0. ... 0. 1. 0. ]\n [0. 0. 0. ... 0. 0. 1. ]]\n\n\nWe can see that the functions of the second item are ortogonal, so the $QR$ decomposition gives the indentity (besides the first function $y(x)=1$ that has to be normalized).\n\nAround $i=25$ the function coeficients become too small to handle. The norm (inner product with itself) of the functions after substracting the projections becomes small, and negative.\n\n\n```python\nFUNCS = [part_a_funcs(100),part_b_funcs(100)]\nfor funcs in FUNCS:\n # Print Original matrix\n print(\"-\"*20+\"Functions:\")\n print(funcs)\n # Perform QR decomposition using generic G-S\n r = generic_gs(funcs,prod=symbolic_inner_product)\n if r is None:\n print(\"Couldn't compute R!!!:\")\n else:\n # Print Q\n print(\"Q:\")\n print(funcs)\n # Print R\n print(\"R:\")\n print(r)\n```\n\n --------------------Functions:\n [1, x, x**2, x**3, x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11, x**12, x**13, x**14, x**15, x**16, x**17, x**18, x**19, x**20, x**21, x**22, x**23, x**24, x**25, x**26, x**27, x**28, x**29, x**30, x**31, x**32, x**33, x**34, x**35, x**36, x**37, x**38, x**39, x**40, x**41, x**42, x**43, x**44, x**45, x**46, x**47, x**48, x**49, x**50, x**51, x**52, x**53, x**54, x**55, x**56, x**57, x**58, x**59, x**60, x**61, x**62, x**63, x**64, x**65, x**66, x**67, x**68, x**69, x**70, x**71, x**72, x**73, x**74, x**75, x**76, x**77, x**78, x**79, x**80, x**81, x**82, x**83, x**84, x**85, x**86, x**87, x**88, x**89, x**90, x**91, x**92, x**93, x**94, x**95, x**96, x**97, x**98, x**99]\n Warning: negative norm2=-0.000000 at i=24!\n Couldn't compute R!!!:\n --------------------Functions:\n [1, sin(2*pi*x), sin(4*pi*x), sin(6*pi*x), sin(8*pi*x), sin(10*pi*x), sin(12*pi*x), sin(14*pi*x), sin(16*pi*x), sin(18*pi*x), sin(20*pi*x), sin(22*pi*x), sin(24*pi*x), sin(26*pi*x), sin(28*pi*x), sin(30*pi*x), sin(32*pi*x), sin(34*pi*x), sin(36*pi*x), sin(38*pi*x), sin(40*pi*x), sin(42*pi*x), sin(44*pi*x), sin(46*pi*x), sin(48*pi*x), sin(50*pi*x), sin(52*pi*x), sin(54*pi*x), sin(56*pi*x), sin(58*pi*x), sin(60*pi*x), sin(62*pi*x), sin(64*pi*x), sin(66*pi*x), sin(68*pi*x), sin(70*pi*x), sin(72*pi*x), sin(74*pi*x), sin(76*pi*x), sin(78*pi*x), sin(80*pi*x), sin(82*pi*x), sin(84*pi*x), sin(86*pi*x), sin(88*pi*x), sin(90*pi*x), sin(92*pi*x), sin(94*pi*x), sin(96*pi*x), sin(98*pi*x), sin(100*pi*x), sin(102*pi*x), sin(104*pi*x), sin(106*pi*x), sin(108*pi*x), sin(110*pi*x), sin(112*pi*x), sin(114*pi*x), sin(116*pi*x), sin(118*pi*x), sin(120*pi*x), sin(122*pi*x), sin(124*pi*x), sin(126*pi*x), sin(128*pi*x), sin(130*pi*x), sin(132*pi*x), sin(134*pi*x), sin(136*pi*x), sin(138*pi*x), sin(140*pi*x), sin(142*pi*x), sin(144*pi*x), sin(146*pi*x), sin(148*pi*x), sin(150*pi*x), sin(152*pi*x), sin(154*pi*x), sin(156*pi*x), sin(158*pi*x), sin(160*pi*x), sin(162*pi*x), sin(164*pi*x), sin(166*pi*x), sin(168*pi*x), sin(170*pi*x), sin(172*pi*x), sin(174*pi*x), sin(176*pi*x), sin(178*pi*x), sin(180*pi*x), sin(182*pi*x), sin(184*pi*x), sin(186*pi*x), sin(188*pi*x), sin(190*pi*x), sin(192*pi*x), sin(194*pi*x), sin(196*pi*x), sin(198*pi*x)]\n Q:\n [0.707106781186547, 1.0*sin(2*pi*x), 1.0*sin(4*pi*x), 1.0*sin(6*pi*x), 1.0*sin(8*pi*x), 1.0*sin(10*pi*x), 1.0*sin(12*pi*x), 1.0*sin(14*pi*x), 1.0*sin(16*pi*x), 1.0*sin(18*pi*x), 1.0*sin(20*pi*x), 1.0*sin(22*pi*x), 1.0*sin(24*pi*x), 1.0*sin(26*pi*x), 1.0*sin(28*pi*x), 1.0*sin(30*pi*x), 1.0*sin(32*pi*x), 1.0*sin(34*pi*x), 1.0*sin(36*pi*x), 1.0*sin(38*pi*x), 1.0*sin(40*pi*x), 1.0*sin(42*pi*x), 1.0*sin(44*pi*x), 1.0*sin(46*pi*x), 1.0*sin(48*pi*x), 1.0*sin(50*pi*x), 1.0*sin(52*pi*x), 1.0*sin(54*pi*x), 1.0*sin(56*pi*x), 1.0*sin(58*pi*x), 1.0*sin(60*pi*x), 1.0*sin(62*pi*x), 1.0*sin(64*pi*x), 1.0*sin(66*pi*x), 1.0*sin(68*pi*x), 1.0*sin(70*pi*x), 1.0*sin(72*pi*x), 1.0*sin(74*pi*x), 1.0*sin(76*pi*x), 1.0*sin(78*pi*x), 1.0*sin(80*pi*x), 1.0*sin(82*pi*x), 1.0*sin(84*pi*x), 1.0*sin(86*pi*x), 1.0*sin(88*pi*x), 1.0*sin(90*pi*x), 1.0*sin(92*pi*x), 1.0*sin(94*pi*x), 1.0*sin(96*pi*x), 1.0*sin(98*pi*x), 1.0*sin(100*pi*x), 1.0*sin(102*pi*x), 1.0*sin(104*pi*x), 1.0*sin(106*pi*x), 1.0*sin(108*pi*x), 1.0*sin(110*pi*x), 1.0*sin(112*pi*x), 1.0*sin(114*pi*x), 1.0*sin(116*pi*x), 1.0*sin(118*pi*x), 1.0*sin(120*pi*x), 1.0*sin(122*pi*x), 1.0*sin(124*pi*x), 1.0*sin(126*pi*x), 1.0*sin(128*pi*x), 1.0*sin(130*pi*x), 1.0*sin(132*pi*x), 1.0*sin(134*pi*x), 1.0*sin(136*pi*x), 1.0*sin(138*pi*x), 1.0*sin(140*pi*x), 1.0*sin(142*pi*x), 1.0*sin(144*pi*x), 1.0*sin(146*pi*x), 1.0*sin(148*pi*x), 1.0*sin(150*pi*x), 1.0*sin(152*pi*x), 1.0*sin(154*pi*x), 1.0*sin(156*pi*x), 1.0*sin(158*pi*x), 1.0*sin(160*pi*x), 1.0*sin(162*pi*x), 1.0*sin(164*pi*x), 1.0*sin(166*pi*x), 1.0*sin(168*pi*x), 1.0*sin(170*pi*x), 1.0*sin(172*pi*x), 1.0*sin(174*pi*x), 1.0*sin(176*pi*x), 1.0*sin(178*pi*x), 1.0*sin(180*pi*x), 1.0*sin(182*pi*x), 1.0*sin(184*pi*x), 1.0*sin(186*pi*x), 1.0*sin(188*pi*x), 1.0*sin(190*pi*x), 1.0*sin(192*pi*x), 1.0*sin(194*pi*x), 1.0*sin(196*pi*x), 1.0*sin(198*pi*x)]\n R:\n [[1.41421356 0. 0. ... 0. 0. 0. ]\n [0. 1. 0. ... 0. 0. 0. ]\n [0. 0. 1. ... 0. 0. 0. ]\n ...\n [0. 0. 0. ... 1. 0. 0. ]\n [0. 0. 0. ... 0. 1. 0. ]\n [0. 0. 0. ... 0. 0. 1. ]]\n\n\n---\nTo do it numerically, let's define a polynomial\n$$\np(x) = \\sum_{i=0}^{n-1} p_i x^i\n$$\nas the array of the $p_i$'s.\n\nThen the multiplication becomes:\n$$\np(x)q(x) = \\sum_{i=0}^{2n-2} \\left( \\sum_{k=0}^{i} p_k q_{i-k} \\right) x^{i} \\,,\n$$\nthen the inner product becomes:\n\\begin{align*}\n\\int_{-1}^{1} p(x)q(x) \\, dx &= \\sum_{i=0}^{2n-2} \\left( \\sum_{k=0}^{i} p_k q_{i-k} \\right) \\frac{x^{i+1}}{i+1} |_{x=-1}^{1}\n\\\\ &= \\sum_{i=0}^{2n-2} [i \\, \\text{mod} \\, 2= 0] \\left( \\sum_{k=0}^{i} p_k q_{i-k} \\right) \\frac{2}{i+1}\n\\end{align*}\n\n\n```python\n@jit(nopython=True)\ndef poly_mult(a,b):\n assert(len(a)==len(b))\n n = len(a)\n total = 0\n for i in range(0,2*n-1,2):\n term = 0\n for k in range(0,i+1):\n if k>=0 and i-k>=0 and k0 and poly[0] != 0: stri.append(\"%.3f\"%poly[0])\n if len(poly)>1 and poly[1] != 0: stri.append(\"%.3fx\"%poly[1])\n for i in range(2,len(poly)):\n if poly[i]!=0:\n stri.append(\"%+.3fx%d\"%(poly[i],i))\n if len(stri)==0: return \"0\"\n return \" \".join(stri)\n\ndef poly_matrix_print(polys,limit=10):\n print(\"[\")\n if len(polys)>2*limit:\n for poly in polys[:limit]:\n print(\" \"+poly_print(poly)+\" |\")\n print(\" ...\")\n for poly in polys[-limit:]:\n print(\" \"+poly_print(poly)+\" |\")\n else:\n for poly in polys:\n print(\" \"+poly_print(poly)+\" |\")\n print(\"]\")\n```\n\n\n```python\npoly_mult([1,2,3],[2,5,1])\n```\n\n\n\n\n 16.53333333333333\n\n\n\n\n```python\nfor N in (5,10,100):\n # Print Original matrix\n polys = np.eye(N)\n print(\"-\"*20+\" Original (N=%d):\"%N)\n poly_matrix_print(polys)\n # Perform QR decomposition using generic G-S\n r = generic_gs(polys,prod=poly_mult)\n # Print Q\n print(\"Q:\")\n poly_matrix_print(polys)\n # Assert that Q is orthonormal\n for i in range(N):\n for j in range(N):\n if i==j:\n assert(np.abs(poly_mult(polys[i],polys[j])-1)<1e-5)\n else:\n assert(np.abs(poly_mult(polys[i],polys[j]))<1e-5)\n # Print R\n print(\"R:\")\n print(r)\n```\n\nWe can see that the numerical method fails for $N=100$. After a closer inspection, this was because, after substracting the projection with the previous functions, the remaining polynomial had very small coefficients, around $i=25$ too.\n\n---\n\n# Item XVI\n\nLet $f(x) = \\sum_{i=1}^n \\alpha_i \\text{sinc}(x-x_i)$ where $\\text{sinc}(x) = \\frac{\\sin(x)}{x}$. Compute the total number of operations needed for evaluation of $f(x)$ at $x_j$, for $j=1 \\dots n$. Also implement this algorithm and validate your estimation.\n\n---\n\nThe first observation is that $\\text{sinc}(x-x_i)$ should be defined as $\\text{sinc}(0)=1$ when $x=x_i$. In this case, it's not necessary to compute one of the $\\sin$'s nor the division.\n\nSo, for evaluating the function on a particular point $x$, the amount of $\\sin$ that have to be calculated is $n$, but if $x=x_j$ for some $j$, then $n{-}1$ $\\sin$ have to be calculated. The same goes for the amount of divisions by $x-x_j$, substractions to get $x-x_j$, multiplications by $a_j$ and $n-1$ sums to get the final amount.\n\n| Operation | Times performed | Total ops. |\n|:------| -----:| ---: |\n| compute $x-x_j$ | $n$ | $n$ |\n| compute $\\sin(x-x_j)$ | $n-1$ | $(n-1)C$ |\n| divide $\\sin(x-x_j)$ by $x-x_j$ | $n-1$ | $n-1$ |\n| multiply by $a_i$ | $n-1$ | $n-1$ |\n| sum over $i$ | $n-1$ | $n-1$ |\n\nThis results in $4n-3+C(n-1)$ operations for each $f(x_j)$, if we compute add the operations required to compute all of them, we will end with $n(4n-3+C(n-1)) = O(n^2)$ where $C$ is the cost of computing a $\\sin$.\n\nOf course, additional optimizations could be done if some relations between the $x_j$ hold.\n\n\n```python\ndef sinc_sum(xs,alphas):\n n = len(xs)\n def loc_func(x):\n delta_xs = x-xs\n sinc = np.ones(n)\n sinc[delta_xs!=0] = np.sin(delta_xs[delta_xs!=0])/delta_xs[delta_xs!=0]\n return np.sum(alphas*sinc)\n return loc_func\n```\n\n\n```python\nN = np.logspace(1,4.4,num=30,dtype='int') # from 10 to ~25000\nts = []\nfor n in N:\n xsi = np.random.random(n)\n asi = np.random.random(n)\n f = sinc_sum(xsi,asi)\n start = time.time()\n f_evals = [f(x) for x in xsi]\n end = time.time()\n ts.append(end-start)\nts = np.array(ts)\n```\n\n\n```python\nplt.plot(N,ts,'o-')\nplt.grid(True)\nplt.show()\n```\n\nWe perform a linear regression with the last points, in logarithmic scale\n\n\n```python\nregr = linear_model.LinearRegression()\nstart = len(N)//2\nlogN = np.log(N.reshape((-1,1)))\nlogt = np.log(ts.reshape((-1,1)))\nregr.fit(logN[start:],logt[start:])\n# Check predictions:\nres = np.exp(regr.predict(logN))\nplt.loglog(N,res,label=\"fit\")\nplt.loglog(N,ts,label=\"real times\")\nplt.legend()\n```\n\n\n```python\nprint(\"regr. coef : %f\"%regr.coef_)\nprint(\"regr. intercept: %f\"%regr.intercept_)\n```\n\n regr. coef : 1.746347\n regr. intercept: -15.099626\n\n\nWe can see that the resulting fit was:\n\n\\begin{align}\n\\log(t) &= 1.794841 \\log(n) -15.550982 \\\\\nt &= e^{1.794841 \\log(n) -15.550982} \\\\\nt &= 1.76\\cdot10^{-7} n^{1.794841} \n\\end{align}\n\nWhich is somewhat near the $O(n^2)$ expected.\n\n---\n\n# Item XVII\n\nLet $x_i= \\langle x_i,y_i \\rangle$, for $i=1:n$, a set of points that describe a simple polygon. Derive an algorithm that computes the area enclosed by it exactly.\n\n---\n\n$$\n\\newcommand{\\pa}{\\partial}\n$$ \nWe consider the Green's theorem, that says:\n\n> Let $C$ be a positively oriented, piecewise smooth, simple closed curve in a plane, and let $D$ be the region bounded by $C$. If $L$ and $M$ are functions of $(x, y)$ defined on an open region containing $D$ and have continuous partial derivatives there, then: $$\n\\oint_C(L \\, \\pa x + M \\, \\pa y) = \\iint_D\\left(\\frac{\\pa M}{\\pa x}-\\frac{\\pa L}{\\pa y}\\right) \\pa x \\pa y\n$$\n\nIf we make\n$$\n\\frac{\\pa M}{\\pa x}-\\frac{\\pa L}{\\pa y} = 1 \\,,\n$$ e.g. by defining:\n$$\nM(x,y) = 0 \\qquad L(x,y) = -y\n$$\nthis results in:\n$$\n-\\oint_C( y \\, \\pa x) = \\iint_D \\pa x \\pa y = \\text{Area.}\n$$\n\n$$\n-\\oint_C( y(x) \\, \\pa x) = - \\sum_{i=0}^{n-1} \\int_{x_{i-1}}^{x_i} y(x) \\pa x = \n- \\sum_{i=0}^{n-1} \\frac{1}{2} (y_{i}+y_{i-1})(x_i-x_{i-1})\n$$\nwhere we define $x_{-1}=x_{n-1}$.\n\nSo, with the previous formula we can compute the area of the polygon.\n\n\n```python\ndef area(ps):\n ps = np.array(ps)\n assert(len(ps.shape)==2)\n assert(ps.shape[1]==2)\n n = ps.shape[0]\n # get the points (add the first ones at the end again).\n xs = ps[:,0]+ps[-1:,0]\n ys = ps[:,1]+ps[-1:,1]\n # for each segment, compute the integral\n areas = (xs[1:]-xs[:-1])*(ys[1:]+ys[:-1])/2.0\n # sum areas, retrieve abs (in case points are in inverse order).\n return np.abs(np.sum(areas))\n```\n\n\n```python\narea([[1,1],[3,1],[5,2],[3,4],[1,3]])\n```\n\n\n\n\n 8.0\n\n\n\n\n```python\narea([[-3,3],[2,3],[2,-1],[-3,-1]])\n```\n\n\n\n\n 20.0\n\n\n\n---\n\n# Item XVIII\n\nLet $A_n$:\n$$\nA_n = \n\\begin{bmatrix}\n1 & -2 & 0 & \\dots & 0 \\\\\n0 & 1 & -2 & 0 & \\dots \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & \\vdots \\\\\n\\vdots & \\ddots & 0 & 1 & -2 \\\\\n0 & \\dots & \\dots & 0 & 1\n\\end{bmatrix} \\in \\mathbb{R}^{n \\times n}\n$$\n* Determine $A_n^{-1}$\n* Determine $\\kappa_\\infty(A_n) = ||A_n||_\\infty ||A_n^{-1}||_\\infty$.\n* Solve the largest linear system of equations you can solve in 1 minute with the solution $x$ equal to $-1_n + U (-\\delta,\\delta)$ using Backward Substitution for $\\delta =10^{-14}$. Notice, after you generate $x$ you need to find the RHS and then solve it, hopefully, coming back to the solution you defined previously. Did you recover the solution? \n---\n\n### Item A\nWe can write $A_n = I + R$ where \n$$\nR = [r_{ij}]_{i \\in \\{1..n\\}\\\\j \\in \\{1..n\\}} \\text{ where } r_{ij} =\n\\begin{cases}\n-2 & \\text{if $j=i+1$} \\\\\n0 & \\text{otherwise}\n\\end{cases}\n$$\nWe can see that:\n$$\nR^k = \\left[r^{(k)}_{ij}\\right]_{i \\in \\{1..n\\} \\\\ j \\in \\{1..n\\}} \\text{ where } r_{ij} =\n\\begin{cases}\n(-2)^k & \\text{if $j=i+k$} \\\\\n0 & \\text{otherwise}\n\\end{cases}\n$$\n\nAnd we make use of the identity [1]:\n$$\n(I + R)^{-1} = I + \\sum_{k=1}^{n-1} (-1)^k R^{k}\n$$\n\nAnd thus we have:\n\\begin{align}\nA_n^{-1} &= \\begin{bmatrix}\n1 & 2 & 4 & 8 & 16 & \\dots & \\\\\n0 & 1 & 2 & 4 & 8 & \\dots & \\\\\n\\vdots & \\ddots & \\ddots & \\ddots & \\ddots \\\\\n0 & \\dots & \\dots & \\dots & \\dots & 1 \\\\\n\\end{bmatrix}\n\\\\&= [a^{(-1)}_{ij}]_{i \\in \\{1..n\\}\\\\ j \\in \\{1..n\\}} \\text{ where } a^{(-1)}_{ij} =\n\\begin{cases}\n2^{j-i} & \\text{if $j \\geq i$} \\\\\n0 & \\text{otherwise}\n\\end{cases}\n\\end{align}\n\n### Item B\n\nThe definition of the norm $||A||_\\infty$ is:\n$$\n\\sup_x \\frac{||Ax||_\\infty}{||x||_\\infty}\n$$\nIn order to calculate $||A||_\\infty$, let $w$ be the vector so that:\n$$\n\\sup_x \\frac{||Ax||_\\infty}{||x||_\\infty} = \\frac{||Aw||_\\infty}{||w||_\\infty} \\quad \\wedge \\quad ||w||_\\infty=1\n$$\nWe have that\n$$\n||Aw||_\\infty = \\max\\left(\\max(w_i -2 w_{i+1} )_{i \\in \\{1..n{-}1\\}},w_{n}\\right)\n$$\nthis can be maximized when $w_i=1$ and $w_{i+1}=-1$ for any $i You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n\n\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\n# import json\n# s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n# plt.rcParams.update(s)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\n WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (3 chains in 3 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n 100.00% [45000/45000 00:04<00:00 Sampling 3 chains, 0 divergences]\n
\n\n\n\n Sampling 3 chains for 5_000 tune and 10_000 draw iterations (15_000 + 30_000 draws total) took 6 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nnp.mean(lambda_1_samples)\n```\n\n\n\n\n 17.766832462411024\n\n\n\n\n```python\nnp.mean(lambda_2_samples)\n```\n\n\n\n\n 22.707328037819437\n\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\nnp.mean(lambda_1_samples/lambda_2_samples)\n```\n\n\n\n\n 0.7836437705265591\n\n\n\n\n```python\nlambda_1_samples.mean()/lambda_2_samples.mean()\n```\n\n\n\n\n 0.7824272601699357\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nlambda_1_samples[:45].mean()\n```\n\n\n\n\n 17.741154502671343\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "737d3fe93d399e2b6bd6f48cbd62ee04a92a2c0f", "size": 306842, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "jfyu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "c4c673130e10e2c610536b46114c05489a6da74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "jfyu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "c4c673130e10e2c610536b46114c05489a6da74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "jfyu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "c4c673130e10e2c610536b46114c05489a6da74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 223.8088986142, "max_line_length": 88776, "alphanum_fraction": 0.8922702889, "converted": true, "num_tokens": 11501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.15999499366138215}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\n\n```python\n#import pymc3 as pm\n# weird theano issues\nimport os\nos.environ[\"MKL_THREADING_LAYER\"] = \"GNU\"\nimport theano.tensor as tt\n```\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\n /home/g/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2_log__]\n >Metropolis: [lambda_1_log__]\n 100%|██████████| 15000/15000 [00:03<00:00, 4287.81it/s]\n INFO (theano.gof.compilelock): Waiting for existing lock by process '22681' (I am process '22682')\n INFO (theano.gof.compilelock): To manually release the lock, delete /home/g/.theano/compiledir_Linux-4.15--generic-x86_64-with-debian-buster-sid-x86_64-3.6.4-64/lock_dir\n INFO (theano.gof.compilelock): Waiting for existing lock by process '22681' (I am process '22683')\n INFO (theano.gof.compilelock): To manually release the lock, delete /home/g/.theano/compiledir_Linux-4.15--generic-x86_64-with-debian-buster-sid-x86_64-3.6.4-64/lock_dir\n INFO (theano.gof.compilelock): Waiting for existing lock by process '22682' (I am process '22683')\n INFO (theano.gof.compilelock): To manually release the lock, delete /home/g/.theano/compiledir_Linux-4.15--generic-x86_64-with-debian-buster-sid-x86_64-3.6.4-64/lock_dir\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nprint(lambda_1_samples.mean(), lambda_2_samples.mean(),lambda_1_samples.mean()/lambda_2_samples.mean())\n```\n\n 17.75790033523039 22.723489513504365 0.781477700626791\n\n\n__Note__ below question is either misleading or wrong. Really should be compute the mean of `(lambda_2_samples-lambda_1_samples)/lambda_1_samples` which is very different than `(lambda_2_samples.mean()-lambda_1_samples.mean())/lambda_1_samples.mean()`. It is different but only kind of\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\nprint((lambda_2_samples.mean()-lambda_1_samples.mean())/lambda_1_samples.mean())\nrel_increase=(lambda_2_samples/lambda_1_samples) - 1\nprint(rel_increase.mean())\n```\n\n 0.27962704399363064\n 0.28120340380283726\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nlambda_1_samples[tau_samples<45].mean()\n```\n\n\n\n\n 17.753719646331216\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "2fbc88a42aa0e58a1b7e2768fd4c9605216c9c36", "size": 299657, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "newtux/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "646a5735de343f6fb1491874ff27a16d5b729cba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "newtux/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "646a5735de343f6fb1491874ff27a16d5b729cba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "newtux/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "646a5735de343f6fb1491874ff27a16d5b729cba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T18:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T18:22:32.000Z", "avg_line_length": 265.8890860692, "max_line_length": 89136, "alphanum_fraction": 0.900025696, "converted": true, "num_tokens": 11786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1590959779439536}} {"text": "```python\nimport numpy as np\nimport pyemma as pm\nimport mdshare\nimport matplotlib.pyplot as plt\n%matplotlib inline\n```\n\n# Information, entropy and caliber\n\n**warning inconsistent nomenclature ahead (sorry, no time to tidy up)**\n\n## Information:\n\n1 Bit = reduce uncertainty by factor of 2 (Shannon definition). \n\n$$\nh(x)=\\log_{2} \\frac{1}{P(x)}\n$$\n\nif we observe $x$ when the probability is $P(x)$ then we reduce our uncertainty by $2^{h(x)}$. e.g., if weather is 75% *rain*, 25% *sun*, and we observe *sun* our uncertainty has been reduced by a factor of $4$ or $\\log_{2}(4) = 2$ bits. If we observe *rain*, intuitively we have learned *less*, our uncertainty has been reduced by a smaller amount ($4/3$) or $\\log_{2}(4/3) = 0.42$ bits. **The less likely something is, the more suprising it is when we observe it/the more information we gained**. \n\n## Entropy\n\nEntropy is the **average information** content of a distribution: \n\n$$\nH(X) \\equiv \\sum_{x \\in \\mathcal{A}_{X}} P(x) \\log \\frac{1}{P(x)}\n$$\n\n### Joint entropy\nMany extensions, e.g., joint entropy = average information gained when observing $x, y$ from a joint distribution: \n\n$$\nH(X, Y)=\\sum_{x y \\in \\mathcal{A}_{X} \\mathcal{A}_{Y}} P(x, y) \\log \\frac{1}{P(x, y)}\n$$\n\n### Conditional entropy\n\nAverage information from $Y$ conditional on a specific value of $X$ occuring, then averaged over all possible values of $X$: \n\n$$\n\\begin{aligned}\n\\mathrm{H}(Y \\mid X) & \\equiv \\sum_{x \\in \\mathcal{X}} p(x) \\mathrm{H}(Y \\mid X=x) \\\\\n& [\\mathrm{some\\ algebra}]\\\\\n&=\\sum_{x \\in \\mathcal{X}, y \\in \\mathcal{Y}} p(x, y) \\log \\frac{p(x)}{p(x, y)}\n\\end{aligned}\n$$\n\nMany interesting properties of conditional entropy used in derivations below (not shown, please use [Wikipedia](https://en.wikipedia.org/wiki/Conditional_entropy))\n\n\n\n\n## Entropy *rate*\n\n### Definition\nThis is taken from [](https://homepages.cwi.nl/~schaffne/courses/infcom/2014/reports/EntropyRate_Mulder_Peters.pdf)\n\n\nWe can talk about the entropy of a stochastic process, $X_{1}, X_{2}, ..., X_{n} = \\{X_{i}\\}$. \n\nIf $X_{i}$ are identically and *indepedently* distributed then $H(\\{X_{i}\\}) = n \\times H(X_{1})$ (use formula for joint entropy and the fact that for i.i.d., we have $P(x, y) = P(x)P(y)$). \n\nHowever, in general (e.g., Markov process) $X_{i}$ are not independent so we define **entropy rate**: \n\n$$\nH\\left(\\left\\{X_{i}\\right\\}\\right) \\triangleq \\lim _{n \\rightarrow \\infty} \\frac{H\\left(X_{1}, X_{2}, \\ldots, X_{n}\\right)}{n}\n$$\n\n### Conditional entropy rate\n\nWe can also define the **conditional entropy rate**: \n\n$$\n\\mathrm{H}^{\\prime}\\left(\\left\\{X_{i}\\right\\}\\right) \\triangleq \\lim _{n \\rightarrow \\infty} \\mathrm{H}\\left(X_{n} \\mid X_{n-1}, \\ldots, X_{1}\\right)\n$$\n\n\n## Entropy rate and conditional entropy rate are the same \n\nFor *stationary* stochastic process we have: \n\n$$\n\\mathrm{H}\\left(\\left\\{X_{i}\\right\\}\\right)=\\lim _{n \\rightarrow \\infty} \\frac{\\mathrm{H}\\left(\\mathrm{X}_{1}, \\ldots, \\mathrm{X}_{\\mathrm{n}}\\right)}{\\mathrm{n}}=\\lim _{n \\rightarrow \\infty} \\mathrm{H}\\left(\\mathrm{X}_{\\mathrm{n}} \\mid \\mathrm{X}_{\\mathrm{n}-1}, \\ldots, \\mathrm{X}_{1}\\right)=\\mathrm{H}^{\\prime}\\left(\\left\\{\\mathrm{X}_{\\mathrm{i}}\\right\\}\\right)\n$$\n\nProof: [see here](https://homepages.cwi.nl/~schaffne/courses/infcom/2014/reports/EntropyRate_Mulder_Peters.pdf)\n\n### Some facts: \n\n1. Both entropy rates **do not increase with $n$**. i.e., as we observe more of a stochastic process, the average information of the whole sequence **or** the information conditional on past sequence (which are the same in the limit of large $n$) decreases (or stays the same). \n2. For a finite $n$, the conditional entropy rate is always smaller (conditioning never increases the entropy as you're restricting the outcomes). \n\n\n\n## Entropy of Markov process\n\nFor a stationary Markov process we have: \n\n$$\n\\begin{aligned}\n\\mathrm{H}\\left(\\left\\{\\mathbf{Z}_{i}\\right\\}\\right) &=\\mathrm{H}^{\\prime}\\left(\\left\\{Z_{i}\\right\\}\\right) \\\\\n&=\\lim _{n \\rightarrow \\infty} \\mathrm{H}\\left(Z_{n} \\mid Z_{n-1}, \\ldots, Z_{1}\\right) \\\\\n&=\\lim _{n \\rightarrow \\infty} \\mathrm{H}\\left(Z_{n} \\mid Z_{n-1}\\right)\\quad \\mathrm{(Markov\\ property)} \\\\\n&=\\mathrm{H}\\left(Z_{2} \\mid Z_{1}\\right)\\quad \\mathrm{(Stationary\\ process)} \\\\\n&=-\\sum_{i=1}^{|Z|} \\mu_{i}\\left(\\sum_{j=1}^{|Z|} P_{i j} \\log P_{i j}\\right)\n\\end{aligned}\n$$\n\ni.e., Entropy rate of MP: \n\n1. **First (inner) summation**: consider single state, $i$, the distribution of transitions out of that state has some entropy, $h_i$ \n2. **Second (outer) summation**: Now we want average entropy over all states, so use stationary distribution $\\sum \\mu_i h_i$\n\n## Cross-entropy\n(original definition is in terms of message lengths - we'll use a different motivation)\n\nConsider estimating probability of an event/quantity etc., $q_i$. We observe it happening $Np_i$ times (i.e., empirical probability is $p_i$). The likelihood of the parameter $q_i$ is:\n\n$$\n\\mathcal{L} = \\prod_{i} q_{i}^{N p_{i}}\n$$\n\nnow take logs and divide by $N$ (yes, notation overloaded here)\n\n$$\n\\frac{1}{N} \\log \\prod_{i} q_{i}^{N p_{i}}=\\sum_{i} p_{i} \\log q_{i}=-H(p, q)\n$$\n\nthis is the cross-entropy. It measures the information content of a predicted distribution i.e., $q$ given the true distributon. If your guess about a distribution is not good, then you will have a high probability $p_i$ of of observing high information events $q_i$ which doesn't make sense - high information events have small probabilities! \n\nIt's always going to be greater than the entropy because this is actual average infomormation content. \n\n### KL divergence\nThe difference between the true average information content ($H(p)$) of the ditribution $p$, and the average information content ($H(p, q)$) from your best guess $q$ is the KL divergence: \n\n$$\n\\begin{align}\nD_{\\mathrm{KL}}(p \\| q) &= H(p) - H(p, q) \\\\\n& =\\sum_{i} p_i \\log \\frac{p_i}{q_i}\n\\end{align}\n$$\n\n\n\n### KL divergence of MP = - Caliber\n\nNow we get to formula:\n$$\n\\mathcal{D}=\\sum_{i, j} \\pi_{i} p_{i j} \\ln \\left(\\frac{p_{i j}}{p_{i j}^{*}}\\right)\n$$\n\nThis just the entropy of an MP with the cross entropy subtracted off. \n\n# Example - 2 state\n\n\n\n\n\n\n\n$$\nP=\\left[\\begin{array}{cc}\n1-\\alpha & \\alpha \\\\\n\\beta & 1-\\beta\n\\end{array}\\right]\n$$\n\nFor a two state process we don't really need MaxCal approach as we can always choose $\\alpha$ and $\\beta$ to match a given $\\mu$ but lets do it using the Hongbin approach. \n\n**Start with Markov process 1, (P1) with stationary distribution $\\pi_{1}$**\n\n\n```python\n\nimport scipy.stats as sp\n\nalpha1 = 0.1\nbeta1 = 0.2\n\nP1 = np.array([[1-alpha1, alpha1], [beta1, 1-beta1]])\nevals1, evecs1 = np.linalg.eig(P1.T)\npi1 = evecs1[:, evals1==1].flatten()\npi1 = pi1/np.sum(pi1)\nprint('Transition matrix:\\n{}\\n'.format(P1))\nprint('Stationary distribution:\\n{}\\n'.format(pi1))\nprint('Satisfies DB?\\n{}'.format(np.allclose(pi1[0]*P1[0, 1], pi1[1]*P1[1, 0])))\n```\n\n Transition matrix:\n [[0.9 0.1]\n [0.2 0.8]]\n \n Stationary distribution:\n [0.66666667 0.33333333]\n \n Satisfies DB?\n True\n\n\n**Now consider another MP (P2) where we only know $\\pi_2$ (but really we know P2 as well so that we can compare exact results with MaxCal approach)**\n\n\n```python\nalpha2 = alpha1/2\nbeta2 = 0.2\n\nP2 = np.array([[1-alpha2, alpha2], [beta2, 1-beta2]])\nevals2, evecs2 = np.linalg.eig(P2.T)\npi2 = evecs2[:, evals2==1].flatten()\npi2 = pi2/np.sum(pi2)\nprint('Transition matrix:\\n{}\\n'.format(P2))\nprint('Stationary distribution:\\n{}\\n'.format(pi2))\nprint('Satisfies DB?\\n{}'.format(np.allclose(pi2[0]*P2[0, 1], pi2[1]*P2[1, 0])))\n```\n\n Transition matrix:\n [[0.95 0.05]\n [0.2 0.8 ]]\n \n Stationary distribution:\n [0.8 0.2]\n \n Satisfies DB?\n True\n\n\n**Question: can we calculate P2 given $\\pi_2$ and P1?**\n\nAnswer: kind of - use iterative scheme in equations 13, 14\n\n\n```python\ndef update_pij(pi, p_star, w):\n n = pi.shape[0]\n p = np.empty((n, n))\n for i in range(n):\n for j in range(n):\n top = pi[j]*p_star[j, i]*w[j]\n bottom = pi[i]*p_star[i, j]*w[i]\n p[i, j] = p_star[i, j]*np.sqrt(top/bottom)*w[i]\n return p\n\ndef update_w(w, p):\n n = w.shape[0]\n w_new = np.empty(n)\n for i in range(n):\n w_new[i] = w[i]/np.sum(p[i, :])\n return w_new\n```\n\n\n```python\nmax_iter = 100\n\nn = P1.shape[0]\nw = np.ones(n)\nalpha_ests = []\nfor i in range(max_iter):\n P2_est = update_pij(pi2, P1, w)\n w = update_w(w, P2_est)\n \nevals, evecs = np.linalg.eig(P2_est.T)\n\npi2_est = evecs[:, np.argmin(np.abs(evals-1))] \npi2_est = pi2_est/np.sum(pi2_est)\n\n```\n\n\n```python\npi2_est\n```\n\n\n\n\n array([0.8, 0.2])\n\n\n\n\n```python\nP2_est\n```\n\n\n\n\n array([[0.93147581, 0.06852419],\n [0.27409676, 0.72590324]])\n\n\n\n**Why the difference?** \n\nStationary distribution of 2 x 2 is (some algebra): \n\n$$\n\\pi = \\left[\\begin{array}{cc}\n\\frac{\\beta}{\\alpha+\\beta} & \\frac{\\alpha}{\\alpha+\\beta}\n\\end{array}\\right]\n$$\n\nFixing the stationary distribution at $0.8, 0.2$ to solve for $\\alpha$ and $\\beta$\n\n$$\n\\left[\\begin{array}{cc}\n4 & -1 \\\\\n4 & -1\n\\end{array}\\right]\n\\left[\\begin{array}{c}\n\\alpha \\\\\n\\beta\n\\end{array}\\right] = \n\\left[\\begin{array}{c}\n0 \\\\\n0\n\\end{array}\\right]\n$$\n\nso all solutions have $4\\alpha = \\beta$. For stochastic matrices we have $0 < \\alpha, \\beta < 1$ then: \n\n\n```python\nalphas = np.linspace(0.01, 0.249, 100)\nbetas = alphas*4\n\nplt.plot(alphas, betas)\n```\n\nNow let's calculate the entropy of the all the potential solutions on this line. \n\n\n```python\ndef entropy_mp(alpha, beta):\n P = np.array([[1-alpha, alpha], [beta, 1-beta]])\n evals, evecs = np.linalg.eig(P.T)\n pi = evecs[:, np.argmin(np.abs(evals-1))]\n pi = pi/np.sum(pi)\n ent = np.dot(sp.entropy(P.T), pi)\n return ent\n \ndef kl_divergence(alpha, beta, alpha_star, beta_star):\n P = np.array([[1-alpha, alpha], [beta, 1-beta]])\n P_star = np.array([[1-alpha_star, alpha_star], [beta_star, 1-beta_star]])\n evals, evecs = np.linalg.eig(P.T)\n pi = evecs[:, np.argmin(np.abs(evals-1))]\n pi = pi/np.sum(pi)\n n = P.shape[0]\n ent = 0\n for i in range(n):\n for j in range(n):\n ent -= pi[i]*(P[i, j]*np.log2(P[i, j])-P[i, j]*np.log2(P_star[i, j]))\n\n return ent\n```\n\n\n```python\nentropies = np.array([entropy_mp(float(x), float(y)) for x, y in zip(alphas, betas)])\nkl_divs = np.array([kl_divergence(float(x), float(y), alpha1, beta1) for x, y in zip(alphas, betas)])\n```\n\n\n```python\nplt.plot(alphas, betas, label=r'$\\beta = 4\\alpha$')\nplt.plot(alphas, entropies, label='Entropy')\nplt.plot(alphas, kl_divs, label='KL divergence')\nplt.scatter(P2_est[0, 1], P2_est[1, 0], marker='x', s=100, label='Estimated MaxCal', color='k')\nplt.scatter(alphas[np.argmax(entropies)], betas[np.argmax(entropies)], label='True MaxEnt')\nplt.scatter(alphas[np.argmax(kl_divs)], betas[np.argmax(kl_divs)], label='True MaxCal')\nplt.legend(bbox_to_anchor=(1, 1))\n```\n\n\n```python\nprint('MaxEnt alpha: ', alphas[np.argmax(entropies)])\nprint('MaxEnt beta: ', betas[np.argmax(entropies)])\n\n```\n\n MaxEnt alpha: 0.20071717171717174\n MaxEnt beta: 0.802868686868687\n\n\n\n```python\nprint('MaxCal alpha: ', alphas[np.argmax(kl_divs)])\nprint('MaxCal beta: ', betas[np.argmax(kl_divs)])\n\n```\n\n MaxCal alpha: 0.06793939393939394\n MaxCal beta: 0.27175757575757575\n\n\n\n```python\nP2_est\n```\n\n\n\n\n array([[0.93147581, 0.06852419],\n [0.27409676, 0.72590324]])\n\n\n", "meta": {"hexsha": "75bf63abf6af77e4b2c32763a3234c30b0fa07fd", "size": 58265, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "MaxCal_Example.ipynb", "max_stars_repo_name": "RobertArbon/MaxCal_Explainer", "max_stars_repo_head_hexsha": "ae8d05cd7bd3b32de89b6eef61c0c240a2bd90a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MaxCal_Example.ipynb", "max_issues_repo_name": "RobertArbon/MaxCal_Explainer", "max_issues_repo_head_hexsha": "ae8d05cd7bd3b32de89b6eef61c0c240a2bd90a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MaxCal_Example.ipynb", "max_forks_repo_name": "RobertArbon/MaxCal_Explainer", "max_forks_repo_head_hexsha": "ae8d05cd7bd3b32de89b6eef61c0c240a2bd90a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 89.2266462481, "max_line_length": 27324, "alphanum_fraction": 0.8135072514, "converted": true, "num_tokens": 3764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.15880224074252314}} {"text": "\n\n\n# PHY321: Conservative Forces, Momentum and Angular Momentum conservation\n**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway\n\nDate: **Feb 11, 2022**\n\nCopyright 1999-2022, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license\n\n## Aims and Overarching Motivation\n\n### Monday 2/7\n\nShort repetition from last week. Discussion of momentum and angular momentum conservation.\nReading suggestion: Taylor sections 3.4 and 3.5 and chapter 4.\n\n### Wednesday 2/9\n\nExamples of application of conservations laws (see chapter 4 of Taylor) and exercises (see next slide).\n\n### Friday 2/11\n\nConservative forces and discussion of homework exercises. Problem solving. Deadline fourth homework.\n\n**Reading suggestions.**\n\nTaylor chapter 4 is the essential reading.\nSee also chapter 7 of Malthe-Sørenssen (in particular section 7.5) for exercise 6 in homework 4\n\n## Exercises for Wednesday after lecture part\n\n**Example 1.**\n\nWe study a classical electron which moves in the $x$-direction along a surface. The force from the surface is\n\n$$\n\\boldsymbol{F}(x)=-F_0\\sin{(\\frac{2\\pi x}{b})}\\boldsymbol{i}.\n$$\n\nShow that the force is conservative.\n\n**Example 2.**\n\nShow that the force\n\n$$\n\\boldsymbol{F}(\\boldsymbol{r})=\\gamma \\frac{\\boldsymbol{r}}{r^3},\n$$\n\nis a conservative force. Here $\\gamma$ is a constant and $r=\\sqrt{x^2+y^2+z^2}$ and $\\boldsymbol{r}=x\\boldsymbol{i}+y\\boldsymbol{j}+z\\boldsymbol{k}$.\n\n## One Figure to Rule All Forces (thx to Julie)\n\n\n\n\n

Figure 1:

\n\n\n## What is a Conservative Force?\n\nA conservative force is a force whose property is that the total work\ndone in moving an object between two points is independent of the\ntaken path. This means that the work on an object under the influence\nof a conservative force, is independent on the path of the object. It\ndepends only on the spatial degrees of freedom and it is possible to\nassign a numerical value for the potential at any point. It leads to\nconservation of energy. The gravitational force is an example of a\nconservative force.\n\n## Two important conditions\n\nFirst, a conservative force depends only on the spatial degrees of freedom. This is a necessary condition for obtaining a path integral which is independent of path.\nThe important condition for the final work to be independent of the path is that the **curl** of the force is zero, that\n\n$$\n\\boldsymbol{\\nabla} \\times \\boldsymbol{F}=0\n$$\n\n## The total Momentum\n\nThe total momentum $\\boldsymbol{P}$ is defined as the sum of the individual momenta, meaning that we can rewrite\n\n$$\n\\boldsymbol{F}_1^{\\mathrm{net}}+\\boldsymbol{F}_2^{\\mathrm{net}}=\\frac{d\\boldsymbol{p}_1}{dt}+\\frac{d\\boldsymbol{p}_2}{dt}=\\frac{d\\boldsymbol{P}}{dt},\n$$\n\nthat is the derivate with respect to time of the total momentum. If we now\nwrite the net forces as sums of the external plus internal forces\nbetween the objects we have\n\n$$\n\\frac{d\\boldsymbol{P}}{dt}=\\boldsymbol{F}_1^{\\mathrm{ext}}+\\boldsymbol{F}_{12}+\\boldsymbol{F}_2^{\\mathrm{ext}}+\\boldsymbol{F}_{21}=\\boldsymbol{F}_1^{\\mathrm{ext}}+\\boldsymbol{F}_2^{\\mathrm{ext}}.\n$$\n\nThe derivative of the total momentum is just **the sum of the external\nforces**. If we assume that the external forces are zero and that only\ninternal (here two-body forces) are at play, we obtain the important\nresult that the derivative of the total momentum is zero. This means\nagain that the total momentum is a constant of the motion and\nconserved quantity. This is a very important result that we will use\nin many applications to come.\n\n## Newton's Second Law\n\nLet us now general to several objects $N$ and let us also assume that there are no external forces. We will label such a system as **an isolated system**. \n\nNewton's second law, $\\boldsymbol{F}=m\\boldsymbol{a}$, can be written for a particle $i$ as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\sum_{j\\ne i}^N \\boldsymbol{F}_{ij}=m_i\\boldsymbol{a}_i,\n\\label{_auto1} \\tag{1}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{F}_i$ (a single subscript) denotes the net force acting on $i$ from the other objects/particles.\nBecause the mass of $i$ is fixed and we assume it does not change with time, one can see that\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}_i=\\frac{d}{dt}m_i\\boldsymbol{v}_i=\\sum_{j\\ne i}^N\\boldsymbol{F}_{ij}.\n\\label{_auto2} \\tag{2}\n\\end{equation}\n$$\n\n## Summing over all Objects/Particles\n\nNow, one can sum over all the objects/particles and obtain\n\n$$\n\\frac{d}{dt}\\sum_i m_iv_i=\\sum_{ij, i\\ne j}^N\\boldsymbol{F}_{ij}=0.\n$$\n\nHow did we arrive at the last step? We rewrote the double sum as\n\n$$\n\\sum_{ij, i\\ne j}^N\\boldsymbol{F}_{ij}=\\sum_i^N\\sum_{j>i}\\left(\\boldsymbol{F}_{ij}+\\boldsymbol{F}_{ji}\\right),\n$$\n\nand using Newton's third law which states that\n$\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}$, we obtain that the net sum over all the two-particle\nforces is zero when we only consider so-called **internal forces**.\nStated differently, the last step made use of the fact that for every\nterm $ij$, there is an equivalent term $ji$ with opposite\nforce. Because the momentum is defined as $m\\boldsymbol{v}$, for a system of\nparticles, we have thus\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d}{dt}\\sum_im_i\\boldsymbol{v}_i=0,~~{\\rm for~isolated~particles}.\n\\label{_auto3} \\tag{3}\n\\end{equation}\n$$\n\n## Conservation of total Momentum\n\nBy \"isolated\" one means that the only force acting on any particle $i$\nare those originating from other particles in the sum, i.e. \"no\nexternal\" forces. Thus, Newton's third law leads to the conservation\nof total momentum,\n\n$$\n\\boldsymbol{P}=\\sum_i m_i\\boldsymbol{v}_i,\n$$\n\nand we have\n\n$$\n\\frac{d}{dt}\\boldsymbol{P}=0.\n$$\n\n## Conservation of Angular Momentum\n\nThe angular momentum is defined as\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{L}=\\boldsymbol{r}\\times\\boldsymbol{p}=m\\boldsymbol{r}\\times\\boldsymbol{v}.\n\\label{_auto4} \\tag{4}\n\\end{equation}\n$$\n\nIt means that the angular momentum is perpendicular to the plane defined by position $\\boldsymbol{r}$ and the momentum $\\boldsymbol{p}$ via $\\boldsymbol{r}\\times \\boldsymbol{p}$.\n\n## Rate of Change of Angular Momentum\n\nThe rate of change of the angular momentum is\n\n$$\n\\frac{d\\boldsymbol{L}}{dt}=m\\boldsymbol{v}\\times\\boldsymbol{v}+m\\boldsymbol{r}\\times\\dot{\\boldsymbol{v}}=\\boldsymbol{r}\\times{\\boldsymbol{F}}\n$$\n\nThe first term is zero because $\\boldsymbol{v}$ is parallel to itself, and the\nsecond term defines the so-called torque. If $\\boldsymbol{F}$ is parallel to $\\boldsymbol{r}$ then the torque is zero and we say that angular momentum is conserved.\n\nIf the force is not radial, $\\boldsymbol{r}\\times\\boldsymbol{F}\\ne 0$ as above, and angular momentum is no longer conserved,\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d\\boldsymbol{L}}{dt}=\\boldsymbol{r}\\times\\boldsymbol{F}\\equiv\\boldsymbol{\\tau},\n\\label{_auto5} \\tag{5}\n\\end{equation}\n$$\n\nwhere $\\boldsymbol{\\tau}$ is the torque.\n\n## The Torque, Example 1 (hw 4, exercise 4)\n\nLet us assume we have an initial position $\\boldsymbol{r}_0=x_0\\boldsymbol{e}_1+y_0\\boldsymbol{e}_2$ at a time $t_0=0$.\nWe add now a force in the positive $x$-direction\n\n$$\n\\boldsymbol{F}=F_x\\boldsymbol{e}_1=\\frac{d\\boldsymbol{p}}{dt},\n$$\n\nwhere we used the force as defined by the time derivative of the momentum.\n\nWe can use this force (and its pertinent acceleration) to find the velocity via the relation\n\n$$\n\\boldsymbol{v}(t)=\\boldsymbol{v}_0+\\int_{t_0}^t\\boldsymbol{a}dt',\n$$\n\nand with $\\boldsymbol{v}_0=0$ we have\n\n$$\n\\boldsymbol{v}(t)=\\int_{t_0}^t\\frac{\\boldsymbol{F}}{m}dt',\n$$\n\nwhere $m$ is the mass of the object.\n\n## The Torque, Example 1 (hw 4, exercise 4)\n\nSince the force acts only in the $x$-direction, we have after integration\n\n$$\n\\boldsymbol{v}(t)=\\frac{\\boldsymbol{F}}{m}t=\\frac{F_x}{m}t\\boldsymbol{e}_1=v_x(t)\\boldsymbol{e}_1.\n$$\n\nThe momentum is in turn given by $\\boldsymbol{p}=p_x\\boldsymbol{e}_1=mv_x\\boldsymbol{e}_1=F_xt\\boldsymbol{e}_1$.\n\nIntegrating over time again we find the final position as (note the force depends only on the $x$-direction)\n\n$$\n\\boldsymbol{r}(t)=(x_0+\\frac{1}{2}\\frac{F_x}{m}t^2) \\boldsymbol{e}_1+y_0\\boldsymbol{e}_2.\n$$\n\nThere is no change in the position in the $y$-direction since the force acts only in the $x$-direction.\n\n## The Torque, Example 1 (hw 4, exercise 4)\n\nWe can now compute the angular momentum given by\n\n$$\n\\boldsymbol{l}=\\boldsymbol{r}\\times\\boldsymbol{p}=\\left[(x_0+\\frac{1}{2}\\frac{F_x}{m}t^2) \\boldsymbol{e}_1+y_0\\boldsymbol{e}_2\\right]\\times F_xt\\boldsymbol{e}_1.\n$$\n\nComputing the cross product we find\n\n$$\n\\boldsymbol{l}=-y_0F_xt\\boldsymbol{e}_3=-y_0F_xt\\boldsymbol{e}_z.\n$$\n\nThe torque is the time derivative of the angular momentum and we have\n\n$$\n\\boldsymbol{\\tau}=-y_0F_x\\boldsymbol{e}_3=-y_0F_x\\boldsymbol{e}_z.\n$$\n\nThe torque is non-zero and angular momentum is not conserved.\n\n## System of Isolated Particles\n\nFor a system of isolated particles, one can write\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\sum_i\\boldsymbol{L}_i&=&\\sum_{i\\ne j}\\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} \\boldsymbol{r}_i\\times \\boldsymbol{F}_{ij}+\\boldsymbol{r}_j\\times\\boldsymbol{F}_{ji}\\\\\n\\nonumber\n&=&\\frac{1}{2}\\sum_{i\\ne j} (\\boldsymbol{r}_i-\\boldsymbol{r}_j)\\times\\boldsymbol{F}_{ij}=0,\n\\end{eqnarray}\n$$\n\nwhere the last step used Newton's third law,\n$\\boldsymbol{F}_{ij}=-\\boldsymbol{F}_{ji}$. If the forces between the particles are\nradial, i.e. $\\boldsymbol{F}_{ij} ~||~ (\\boldsymbol{r}_i-\\boldsymbol{r}_j)$, then each term in\nthe sum is zero and the net angular momentum is fixed. Otherwise, you\ncould imagine an isolated system that would start spinning\nspontaneously.\n\n## Work, Energy, Momentum and Conservation laws\n\nEnergy conservation is most convenient as a strategy for addressing\nproblems where time does not appear. For example, a particle goes\nfrom position $x_0$ with speed $v_0$, to position $x_f$; what is its\nnew speed? However, it can also be applied to problems where time\ndoes appear, such as in solving for the trajectory $x(t)$, or\nequivalently $t(x)$.\n\n## Energy Conservation\nEnergy is conserved in the case where the potential energy, $V(\\boldsymbol{r})$, depends only on position, and not on time. The force is determined by $V$,\n\n\n
\n\n$$\n\\begin{equation}\n\\boldsymbol{F}(\\boldsymbol{r})=-\\boldsymbol{\\nabla} V(\\boldsymbol{r}).\n\\label{_auto6} \\tag{6}\n\\end{equation}\n$$\n\n## Conservative forces\n\nWe say a force is conservative if it satisfies the following conditions:\n1. The force $\\boldsymbol{F}$ acting on an object only depends on the position $\\boldsymbol{r}$, that is $\\boldsymbol{F}=\\boldsymbol{F}(\\boldsymbol{r})$.\n\n2. For any two points $\\boldsymbol{r}_1$ and $\\boldsymbol{r}_2$, the work done by the force $\\boldsymbol{F}$ on the displacement between these two points is independent of the path taken.\n\n3. Finally, the **curl** of the force is zero $\\boldsymbol{\\nabla}\\times\\boldsymbol{F}=0$.\n\n## Forces and Potentials\n\nThe energy $E$ of a given system is defined as the sum of kinetic and potential energies,\n\n$$\nE=K+V(\\boldsymbol{r}).\n$$\n\nWe define the potential energy at a point $\\boldsymbol{r}$ as the negative work done from a starting point $\\boldsymbol{r}_0$ to a final point $\\boldsymbol{r}$\n\n$$\nV(\\boldsymbol{r})=-W(\\boldsymbol{r}_0\\rightarrow\\boldsymbol{r})= -\\int_{\\boldsymbol{r}_0}^{\\boldsymbol{r}}d\\boldsymbol{r}'\\boldsymbol{F}(\\boldsymbol{r}').\n$$\n\nIf the potential depends on the path taken between these two points there is no unique potential.\n\n## Example (relevant for homework 5)\n\nWe study a classical electron which moves in the $x$-direction along a surface. The force from the surface is\n\n$$\n\\boldsymbol{F}(x)=-F_0\\sin{(\\frac{2\\pi x}{b})}\\boldsymbol{e}_1.\n$$\n\nThe constant $b$ represents the distance between atoms at the surface of the material, $F_0$ is a constant and $x$ is the position of the electron.\n\nThis is indeed a conservative force since it depends only on position\nand its **curl** is zero, that is $-\\boldsymbol{\\nabla}\\times \\boldsymbol{F}=0$. This means that energy is conserved and the\nintegral over the work done by the force is independent of the path\ntaken. We will come back to this in more detail next week.\n\n## Example Continues\n\nUsing the work-energy theorem we can find the work $W$ done when\nmoving an electron from a position $x_0$ to a final position $x$\nthrough the integral\n\n$$\nW=-\\int_{x_0}^x \\boldsymbol{F}(x')dx' = \\int_{x_0}^x F_0\\sin{(\\frac{2\\pi x'}{b})} dx',\n$$\n\nwhich results in\n\n$$\nW=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right].\n$$\n\nSince this is related to the change in kinetic energy we have, with $v_0$ being the initial velocity at a time $t_0$,\n\n$$\nv = \\pm\\sqrt{\\frac{2}{m}\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+v_0^2}.\n$$\n\n## The potential energy from this example\n\nThe potential energy, due to energy conservation is\n\n$$\nV(x)=V(x_0)+\\frac{1}{2}mv_0^2-\\frac{1}{2}mv^2,\n$$\n\nwith $v$ given by the velocity from above.\n\nWe can now, in order to find a more explicit expression for the\npotential energy at a given value $x$, define a zero level value for\nthe potential. The potential is defined, using the work-energy\ntheorem, as\n\n$$\nV(x)=V(x_0)+\\int_{x_0}^x (-F(x'))dx',\n$$\n\nand if you recall the definition of the indefinite integral, we can rewrite this as\n\n$$\nV(x)=\\int (-F(x'))dx'+C,\n$$\n\nwhere $C$ is an undefined constant. The force is defined as the\ngradient of the potential, and in that case the undefined constant\nvanishes. The constant does not affect the force we derive from the\npotential.\n\nWe have then\n\n$$\nV(x)=V(x_0)-\\int_{x_0}^x \\boldsymbol{F}(x')dx',\n$$\n\nwhich results in\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}-\\cos{(\\frac{2\\pi x_0}{b})}\\right]+V(x_0).\n$$\n\nWe can now define\n\n$$\n\\frac{F_0b}{2\\pi}\\cos{(\\frac{2\\pi x_0}{b})}=V(x_0),\n$$\n\nwhich gives\n\n$$\nV(x)=\\frac{F_0b}{2\\pi}\\left[\\cos{(\\frac{2\\pi x}{b})}\\right].\n$$\n\n## Force and Potential\n\nWe have defined work as the energy resulting from a net force acting\non an object (or sseveral objects), that is\n\n$$\nW(\\boldsymbol{r}\\rightarrow \\boldsymbol{r}+d\\boldsymbol{r})= \\boldsymbol{F}(\\boldsymbol{r})d\\boldsymbol{r}.\n$$\n\nIf we write out this for each component we have\n\n$$\nW(\\boldsymbol{r}\\rightarrow \\boldsymbol{r}+d\\boldsymbol{r})=\\boldsymbol{F}(\\boldsymbol{r})d\\boldsymbol{r}=F_xdx+F_ydy+F_zdz.\n$$\n\nThe work done from an initial position to a final one defines also the difference in potential energies\n\n$$\nW(\\boldsymbol{r}\\rightarrow \\boldsymbol{r}+d\\boldsymbol{r})=-\\left[V(\\boldsymbol{r}+d\\boldsymbol{r})-V(\\boldsymbol{r})\\right].\n$$\n\n## Getting to $\\boldsymbol{F}(\\boldsymbol{r})=-\\boldsymbol{\\nabla} V(\\boldsymbol{r})$\n\nWe can write out the differences in potential energies as\n\n$$\nV(\\boldsymbol{r}+d\\boldsymbol{r})-V(\\boldsymbol{r})=V(x+dx,y+dy,z+dz)-V(x,y,z)=dV,\n$$\n\nand using the expression the differential of a multi-variable function $f(x,y,z)$\n\n$$\ndf=\\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n$$\n\nwe can write the expression for the work done as\n\n$$\nW(\\boldsymbol{r}\\rightarrow \\boldsymbol{r}+d\\boldsymbol{r})=-dV=-\\left[\\frac{\\partial V}{\\partial x}dx+\\frac{\\partial V}{\\partial y}dy+\\frac{\\partial V}{\\partial z}dz \\right].\n$$\n\n## Final expression\n\nComparing the last equation with\n\n$$\nW(\\boldsymbol{r}\\rightarrow \\boldsymbol{r}+d\\boldsymbol{r})=F_xdx+F_ydy+F_zdz,\n$$\n\nwe have\n\n$$\nF_xdx+F_ydy+F_zdz=-\\left[\\frac{\\partial V}{\\partial x}dx+\\frac{\\partial V}{\\partial y}dy+\\frac{\\partial V}{\\partial z}dz \\right],\n$$\n\nleading to\n\n$$\nF_x=-\\frac{\\partial V}{\\partial x},\n$$\n\nand\n\n$$\nF_y=-\\frac{\\partial V}{\\partial y},\n$$\n\nand\n\n$$\nF_z=-\\frac{\\partial V}{\\partial z},\n$$\n\nor just\n\n$$\n\\boldsymbol{F}=-\\frac{\\partial V}{\\partial x}\\boldsymbol{e}_1-\\frac{\\partial V}{\\partial y}\\boldsymbol{e}_2-\\frac{\\partial V}{\\partial z}\\boldsymbol{e}_3=-\\boldsymbol{\\nabla}V(\\boldsymbol{r}).\n$$\n\nAnd this connection is the one we wanted to show.\n\n## Net Energy\n\nThe net energy, $E=V+K$ where $K$ is the kinetic energy, is then conserved,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}(K+V)&=&\\frac{d}{dt}\\left(\\frac{m}{2}(v_x^2+v_y^2+v_z^2)+V(\\boldsymbol{r})\\right)\\\\\n\\nonumber\n&=&m\\left(v_x\\frac{dv_x}{dt}+v_y\\frac{dv_y}{dt}+v_z\\frac{dv_z}{dt}\\right)\n+\\partial_xV\\frac{dx}{dt}+\\partial_yV\\frac{dy}{dt}+\\partial_zV\\frac{dz}{dt}\\\\\n\\nonumber\n&=&v_xF_x+v_yF_y+v_zF_z-F_xv_x-F_yv_y-F_zv_z=0.\n\\end{eqnarray}\n$$\n\n## In Vector Notation\n\nThe same proof can be written more compactly with vector notation,\n\n$$\n\\begin{eqnarray}\n\\frac{d}{dt}\\left(\\frac{m}{2}v^2+V(\\boldsymbol{r})\\right)\n&=&m\\boldsymbol{v}\\cdot\\dot{\\boldsymbol{v}}+\\boldsymbol{\\nabla} V(\\boldsymbol{r})\\cdot\\dot{\\boldsymbol{r}}\\\\\n\\nonumber\n&=&\\boldsymbol{v}\\cdot\\boldsymbol{F}-\\boldsymbol{F}\\cdot\\boldsymbol{v}=0.\n\\end{eqnarray}\n$$\n\nInverting the expression for kinetic energy,\n\n\n
\n\n$$\n\\begin{equation}\nv=\\sqrt{2K/m}=\\sqrt{2(E-V)/m},\n\\label{_auto7} \\tag{7}\n\\end{equation}\n$$\n\nallows one to solve for the one-dimensional trajectory $x(t)$, by finding $t(x)$,\n\n\n
\n\n$$\n\\begin{equation}\nt=\\int_{x_0}^x \\frac{dx'}{v(x')}=\\int_{x_0}^x\\frac{dx'}{\\sqrt{2(E-V(x'))/m}}.\n\\label{_auto8} \\tag{8}\n\\end{equation}\n$$\n\nNote this would be much more difficult in higher dimensions, because\nyou would have to determine which points, $x,y,z$, the particles might\nreach in the trajectory, whereas in one dimension you can typically\ntell by simply seeing whether the kinetic energy is positive at every\npoint between the old position and the new position.\n\n## The Torque, Example 2\n\nOne can write the torque about a given axis, which we will denote as $\\hat{z}$, in polar coordinates, where\n\n$$\n\\begin{eqnarray}\nx&=&r\\sin\\theta\\cos\\phi,~~y=r\\sin\\theta\\sin\\phi,~~z=r\\cos\\theta,\n\\end{eqnarray}\n$$\n\nto find the $z$ component of the torque,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&xF_y-yF_x\\\\\n\\nonumber\n&=&-r\\sin\\theta\\left\\{\\cos\\phi \\partial_y-\\sin\\phi \\partial_x\\right\\}V(x,y,z).\n\\end{eqnarray}\n$$\n\n## Chain Rule and Partial Derivatives\n\nOne can use the chain rule to write the partial derivative w.r.t. $\\phi$ (keeping $r$ and $\\theta$ fixed),\n\n$$\n\\begin{eqnarray}\n\\partial_\\phi&=&\\frac{\\partial x}{\\partial\\phi}\\partial_x+\\frac{\\partial_y}{\\partial\\phi}\\partial_y\n+\\frac{\\partial z}{\\partial\\phi}\\partial_z\\\\\n\\nonumber\n&=&-r\\sin\\theta\\sin\\phi\\partial_x+\\sin\\theta\\cos\\phi\\partial_y.\n\\end{eqnarray}\n$$\n\nCombining the two equations,\n\n$$\n\\begin{eqnarray}\n\\tau_z&=&-\\partial_\\phi V(r,\\theta,\\phi).\n\\end{eqnarray}\n$$\n\nThus, if the potential is independent of the azimuthal angle $\\phi$,\nthere is no torque about the $z$ axis and $L_z$ is conserved.\n\n## The Earth-Sun system\n\nWe will now venture into a study of a system which is energy\nconserving. The aim is to see if we (since it is not possible to solve\nthe general equations analytically) we can develop stable numerical\nalgorithms whose results we can trust!\n\nWe solve the equations of motion numerically. We will also compute\nquantities like the energy numerically.\n\nWe start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is\n\n$$\n\\boldsymbol{F}_G=-\\frac{GM_{\\odot}M_E}{r^3}\\boldsymbol{r},\n$$\n\nwhere $G$ is the gravitational constant,\n\n$$\nM_E=6\\times 10^{24}\\mathrm{Kg},\n$$\n\nthe mass of Earth,\n\n$$\nM_{\\odot}=2\\times 10^{30}\\mathrm{Kg},\n$$\n\nthe mass of the Sun and\n\n$$\nr=1.5\\times 10^{11}\\mathrm{m},\n$$\n\nis the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**.\n\n## The Earth-Sun system, Newton's Laws\n\nFrom Newton's second law we have then for the $x$ direction\n\n$$\n\\frac{d^2x}{dt^2}=-\\frac{F_{x}}{M_E},\n$$\n\nand\n\n$$\n\\frac{d^2y}{dt^2}=-\\frac{F_{y}}{M_E},\n$$\n\nfor the $y$ direction.\n\nHere we will use that $x=r\\cos{(\\theta)}$, $y=r\\sin{(\\theta)}$ and\n\n$$\nr = \\sqrt{x^2+y^2}.\n$$\n\nWe can rewrite\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nfor the $y$ direction.\n\n## The Earth-Sun system, rewriting the Equations\n\nWe can rewrite these two equations\n\n$$\nF_{x}=-\\frac{GM_{\\odot}M_E}{r^2}\\cos{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}x,\n$$\n\nand\n\n$$\nF_{y}=-\\frac{GM_{\\odot}M_E}{r^2}\\sin{(\\theta)}=-\\frac{GM_{\\odot}M_E}{r^3}y,\n$$\n\nas four first-order coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\n$$\n\\frac{dy}{dt}=v_y.\n$$\n\n## Building a code for the solar system, final coupled equations\n\nThe four coupled differential equations\n\n$$\n\\frac{dv_x}{dt}=-\\frac{GM_{\\odot}}{r^3}x,\n$$\n\n$$\n\\frac{dx}{dt}=v_x,\n$$\n\n$$\n\\frac{dv_y}{dt}=-\\frac{GM_{\\odot}}{r^3}y,\n$$\n\n$$\n\\frac{dy}{dt}=v_y,\n$$\n\ncan be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\\times 10^{11}$. \n\nUsing the equations from circular motion (with $r =1\\mathrm{AU}$)\n\n$$\n\\frac{M_E v^2}{r} = F = \\frac{GM_{\\odot}M_E}{r^2},\n$$\n\nwe have\n\n$$\nGM_{\\odot}=v^2r,\n$$\n\nand using that the velocity of Earth (assuming circular motion) is\n$v = 2\\pi r/\\mathrm{yr}=2\\pi\\mathrm{AU}/\\mathrm{yr}$, we have\n\n$$\nGM_{\\odot}= v^2r = 4\\pi^2 \\frac{(\\mathrm{AU})^3}{\\mathrm{yr}^2}.\n$$\n\n## Building a code for the solar system, discretized equations\n\nThe four coupled differential equations can then be discretized using Euler's method as (with step length $h$)\n\n$$\nv_{x,i+1}=v_{x,i}-h\\frac{4\\pi^2}{r_i^3}x_i,\n$$\n\n$$\nx_{i+1}=x_i+hv_{x,i},\n$$\n\n$$\nv_{y,i+1}=v_{y,i}-h\\frac{4\\pi^2}{r_i^3}y_i,\n$$\n\n$$\ny_{i+1}=y_i+hv_{y,i},\n$$\n\n## Code Example with Euler's Method\n\nThe code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays.\n\n\n```\n%matplotlib inline\n\n# Common imports\nimport numpy as np\nimport pandas as pd\nfrom math import *\nimport matplotlib.pyplot as plt\nimport os\n\n# Where to save the figures and data files\nPROJECT_ROOT_DIR = \"Results\"\nFIGURE_ID = \"Results/FigureFiles\"\nDATA_ID = \"DataFiles/\"\n\nif not os.path.exists(PROJECT_ROOT_DIR):\n os.mkdir(PROJECT_ROOT_DIR)\n\nif not os.path.exists(FIGURE_ID):\n os.makedirs(FIGURE_ID)\n\nif not os.path.exists(DATA_ID):\n os.makedirs(DATA_ID)\n\ndef image_path(fig_id):\n return os.path.join(FIGURE_ID, fig_id)\n\ndef data_path(dat_id):\n return os.path.join(DATA_ID, dat_id)\n\ndef save_fig(fig_id):\n plt.savefig(image_path(fig_id) + \".png\", format='png')\n\n\nDeltaT = 0.001\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using Euler's method\nfor i in range(n-1):\n # Set up the acceleration\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using Euler's forward method\n v[i+1] = v[i] + DeltaT*a\n r[i+1] = r[i] + DeltaT*v[i]\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\n#ax.set_xlim(0, tfinal)\nax.set_ylabel('y[AU]')\nax.set_xlabel('x[AU]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunEuler\")\nplt.show()\n```\n\n## Problems with Euler's Method\n\nWe notice here that Euler's method doesn't give a stable orbit. It\nmeans that we cannot trust Euler's method. In a deeper way, as we will\nsee in homework 5, Euler's method does not conserve energy. It is an\nexample of an integrator which is not\n[symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator).\n\nHere we present thus two methods, which with simple changes allow us to avoid these pitfalls. The simplest possible extension is the so-called Euler-Cromer method.\nThe changes we need to make to our code are indeed marginal here.\nWe need simply to replace\n\n\n```\n r[i+1] = r[i] + DeltaT*v[i]\n```\n\nin the above code with the velocity at the new time $t_{i+1}$\n\n\n```\n r[i+1] = r[i] + DeltaT*v[i+1]\n```\n\nBy this simple caveat we get stable orbits.\nBelow we derive the Euler-Cromer method as well as one of the most utlized algorithms for sovling the above type of problems, the so-called Velocity-Verlet method.\n\n## Deriving the Euler-Cromer Method\n\nLet us repeat Euler's method.\nWe have a differential equation\n\n\n
\n\n$$\n\\begin{equation}\ny'(t_i)=f(t_i,y_i) \n\\label{_auto9} \\tag{9}\n\\end{equation}\n$$\n\nand if we truncate at the first derivative, we have from the Taylor expansion\n\n\n
\n\n$$\n\\begin{equation}\ny_{i+1}=y(t_i) + (\\Delta t) f(t_i,y_i) + O(\\Delta t^2), \\label{eq:euler} \\tag{10}\n\\end{equation}\n$$\n\nwhich when complemented with $t_{i+1}=t_i+\\Delta t$ forms\nthe algorithm for the well-known Euler method. \nNote that at every step we make an approximation error\nof the order of $O(\\Delta t^2)$, however the total error is the sum over all\nsteps $N=(b-a)/(\\Delta t)$ for $t\\in [a,b]$, yielding thus a global error which goes like\n$NO(\\Delta t^2)\\approx O(\\Delta t)$. \n\nTo make Euler's method more precise we can obviously\ndecrease $\\Delta t$ (increase $N$), but this can lead to loss of numerical precision.\nEuler's method is not recommended for precision calculation,\nalthough it is handy to use in order to get a first\nview on how a solution may look like.\n\nEuler's method is asymmetric in time, since it uses information about the derivative at the beginning\nof the time interval. This means that we evaluate the position at $y_1$ using the velocity\nat $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at\n$v_{n+1}$, that is (in a slightly more generalized form)\n\n\n
\n\n$$\n\\begin{equation} \ny_{n+1}=y_{n}+ v_{n+1}+O(\\Delta t^2)\n\\label{_auto10} \\tag{11}\n\\end{equation}\n$$\n\nand\n\n\n
\n\n$$\n\\begin{equation}\nv_{n+1}=v_{n}+(\\Delta t) a_{n}+O(\\Delta t^2).\n\\label{_auto11} \\tag{12}\n\\end{equation}\n$$\n\nThe acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated\nas well. This is the Euler-Cromer method.\n\n**Exercise**: go back to the above code with Euler's method and add the Euler-Cromer method.\n\n## Deriving the Velocity-Verlet Method\n\nLet us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in.\n\nWe have the Taylor expansion for the position given by\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_i+O((\\Delta t)^3).\n$$\n\nThe corresponding expansion for the velocity is\n\n$$\nv_{i+1} = v_i+(\\Delta t)a_i+\\frac{(\\Delta t)^2}{2}v^{(2)}_i+O((\\Delta t)^3).\n$$\n\nVia Newton's second law we have normally an analytical expression for the derivative of the velocity, namely\n\n$$\na_i= \\frac{d^2 x}{dt^2}\\vert_{i}=\\frac{d v}{dt}\\vert_{i}= \\frac{F(x_i,v_i,t_i)}{m}.\n$$\n\nIf we add to this the corresponding expansion for the derivative of the velocity\n\n$$\nv^{(1)}_{i+1} = a_{i+1}= a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2)=a_i+(\\Delta t)v^{(2)}_i+O((\\Delta t)^2),\n$$\n\nand retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have\n\n$$\n(\\Delta t)v^{(2)}_i\\approx a_{i+1}-a_i.\n$$\n\nWe can then rewrite the Taylor expansion for the velocity as\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left( a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\n## The velocity Verlet method\n\nOur final equations for the position and the velocity become then\n\n$$\nx_{i+1} = x_i+(\\Delta t)v_i+\\frac{(\\Delta t)^2}{2}a_{i}+O((\\Delta t)^3),\n$$\n\nand\n\n$$\nv_{i+1} = v_i+\\frac{(\\Delta t)}{2}\\left(a_{i+1}+a_{i}\\right)+O((\\Delta t)^3).\n$$\n\nNote well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate \nthe position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time\n$t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well.\n\n## Adding the Velocity-Verlet Method\n\nWe can now easily add the Verlet method to our original code as\n\n\n```\nDeltaT = 0.01\n#set up arrays \ntfinal = 10 # in years\nn = ceil(tfinal/DeltaT)\n# set up arrays for t, a, v, and x\nt = np.zeros(n)\nv = np.zeros((n,2))\nr = np.zeros((n,2))\n# Initial conditions as compact 2-dimensional arrays\nr0 = np.array([1.0,0.0])\nv0 = np.array([0.0,2*pi])\nr[0] = r0\nv[0] = v0\nFourpi2 = 4*pi*pi\n# Start integrating using the Velocity-Verlet method\nfor i in range(n-1):\n # Set up forces, air resistance FD, note now that we need the norm of the vecto\n # Here you could have defined your own function for this\n rabs = sqrt(sum(r[i]*r[i]))\n a = -Fourpi2*r[i]/(rabs**3)\n # update velocity, time and position using the Velocity-Verlet method\n r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a\n rabs = sqrt(sum(r[i+1]*r[i+1]))\n anew = -4*(pi**2)*r[i+1]/(rabs**3)\n v[i+1] = v[i] + 0.5*DeltaT*(a+anew)\n t[i+1] = t[i] + DeltaT\n# Plot position as function of time \nfig, ax = plt.subplots()\nax.set_ylabel('y[AU]')\nax.set_xlabel('x[AU]')\nax.plot(r[:,0], r[:,1])\nfig.tight_layout()\nsave_fig(\"EarthSunVV\")\nplt.show()\n```\n\nYou can easily generalize the calculation of the forces by defining a function\nwhich takes in as input the various variables. We leave this as a challenge to you.\n\n## Additional Material: Link between Line Integrals and Conservative forces\n\nThe concept of line integrals plays an important role in our discussion of energy conservation,\nour definition of potentials and conservative forces.\n\nLet us remind ourselves of some the basic elements (most of you may\nhave seen this in a calculus course under the general topic of vector\nfields).\n\nWe define a path integration $C$, that is we integrate\nfrom a point $\\boldsymbol{r}_1$ to a point $\\boldsymbol{r}_2$. \nLet us assume that the path $C$ is represented by an arc length $s$. In three dimension we have the following representation of $C$\n\n$$\n\\boldsymbol{r}(s)=x(s)\\boldsymbol{e}_1+y(s)\\boldsymbol{e}_2+z(s)\\boldsymbol{e}_3,\n$$\n\nthen our integral of a function $f(x,y,z)$ along the path $C$ is defined as\n\n$$\n\\int_Cf(x,y,z)ds=\\int_a^bf\\left(x(s),y(s),z(s)\\right)ds,\n$$\n\nwhere the initial and final points are $a$ and $b$, respectively.\n\n## Exactness and Independence of Path\n\nWith the definition of a line integral, we can in tunrn set up the\ntheorem of independence of integration path.\n\nLet us define\n$f(x,y,z)$, $g(x,y,z)$ and $h(x,y,z)$ to be functions which are\ndefined and continuous in a domain $D$ in space. Then a line integral\nlike the above is said to be independent of path in $D$, if for every\npair of endpoints $a$ and $b$ in $D$ the value of the integral is the\nsame for all paths $C$ in $D$ starting from a point $a$ and ending in\na point $b$. The integral depends thus only on the integration limits\nand not on the path.\n\n## Differential Forms\n\nAn expression of the form\n\n$$\nfdx+gdy+hdz,\n$$\n\nwhere $f$, $g$ and $h$ are functions defined in $D$, is a called a first-order differential form\nin three variables.\nThe form is said to be exact if it is the differential\n\n$$\ndu= \\frac{\\partial u}{\\partial x}dx+\\frac{\\partial u}{\\partial y}dy+\\frac{\\partial u}{\\partial z}dz,\n$$\n\nof a differentiable function $u(x,y,z)$ everywhere in $D$, that is\n\n$$\ndu=fdx+gdy+hdz.\n$$\n\nIt is said to be exact if and only if we can then set\n\n$$\nf=\\frac{\\partial u}{\\partial x},\n$$\n\nand\n\n$$\ng=\\frac{\\partial u}{\\partial y},\n$$\n\nand\n\n$$\nh=\\frac{\\partial u}{\\partial z},\n$$\n\neverywhere in the domain $D$.\n\n## In Vector Language\n\nIn vector language the above means that the differential form\n\n$$\nfdx+gdy+hdz,\n$$\n\nis exact in $D$ if and only if the vector function (it could be a force, or velocity, acceleration or other vectors we encounter in this course)\n\n$$\n\\boldsymbol{F}=f\\boldsymbol{e}_1+g\\boldsymbol{e}_2+h\\boldsymbol{e}_3,\n$$\n\nis the gradient of a function $u(x,y,z)$\n\n$$\n\\boldsymbol{v}=\\boldsymbol{\\nabla}u=\\frac{\\partial u}{\\partial x}\\boldsymbol{e}_1+\\frac{\\partial u}{\\partial y}\\boldsymbol{e}_2+\\frac{\\partial u}{\\partial z}\\boldsymbol{e}_3.\n$$\n\n## Path Independence Theorem\n\nIf this is the case, we can state the path independence theorem which\nstates that with functions $f(x,y,z)$, $g(x,y,z)$ and $h(x,y,z)$ that fulfill the above\nexactness conditions, the line integral\n\n$$\n\\int_C\\left(fdx+gdy+hdz\\right),\n$$\n\nis independent of path in $D$ if and only if the differential form under the integral sign is exact in $D$.\n\nThis is the path independence theorem. \n\nWe will not give a proof of the theorem. You can find this in any vector analysis chapter in a mathematics textbook.\n\nWe note however that the path integral from a point $p$ to a final point $q$ is given by\n\n$$\n\\int_p^q\\left(fdx+gdy+hdz\\right)=\\int_p^q\\left(\\frac{\\partial u}{\\partial x}dx+\\frac{\\partial u}{\\partial y}dy+\\frac{\\partial u}{\\partial z}dz\\right)=\\int_p^qdu.\n$$\n\nAssume now that we have a dependence on a variable $s$ for $x$, $y$ and $z$. We have then\n\n$$\n\\int_p^qdu=\\int_{s_1}^{s_2}\\frac{du}{ds}ds = u(x(s),y(s),z(s))\\vert_{s=s_1}^{s=s_2}=u(q)-u(p).\n$$\n\nThis last equation\n\n$$\n\\int_p^q\\left(fdx+gdy+hdz\\right)=u(q)-u(p),\n$$\n\nis the analogue of the usual formula\n\n$$\n\\int_a^bf(x)dx=F(x)\\vert_a^b=F(b)-F(a),\n$$\n\nwith $F'(x)=f(x)$.\n\n## Work-Energy Theorem again\n\nWe remember that a the work done by a force\n$\\boldsymbol{F}=f\\boldsymbol{e}_1+g\\boldsymbol{e}_2+h\\boldsymbol{e}_3$ on a displacemnt $d\\boldsymbol{r}$\n\n$$\nW=\\int_C\\boldsymbol{F}d\\boldsymbol{r}=\\int_C(fdx+gdy+hdz).\n$$\n\nFrom the path independence theorem, we know that this has to result in\nthe difference between the two endpoints only. This is exact if and\nonly if the force is the force $\\boldsymbol{F}$ is the gradient of a scalar\nfunction $u$. We call this scalar function, which depends only the\npositions $x,y,z$ for the potential energy $V(x,y,z)=V(\\boldsymbol{r})$.\n\nWe have thus\n\n$$\n\\boldsymbol{F}(\\boldsymbol{r})\\propto \\boldsymbol{\\nabla}V(\\boldsymbol{r}),\n$$\n\nand we define this as\n\n$$\n\\boldsymbol{F}(\\boldsymbol{r})= -\\boldsymbol{\\nabla}V(\\boldsymbol{r}).\n$$\n\nSuch a force is called **a conservative force**. The above expression can be used to demonstrate\nenergy conservation.\n\n## Additional Theorem\n\nFinally we can define the criterion for exactness and independence of\npath. This theorem states that if $f(x,y,z)$, $g(x,y,z)$ and\n$h(x,y,z)$ are continuous functions with continuous first partial derivatives in the domain $D$,\nthen the line integral\n\n$$\n\\int_C\\left(fdx+gdy+hdz\\right),\n$$\n\nis independent of path in $D$ when\n\n$$\n\\frac{\\partial h}{\\partial y}=\\frac{\\partial g}{\\partial z},\n$$\n\nand\n\n$$\n\\frac{\\partial f}{\\partial z}=\\frac{\\partial h}{\\partial x},\n$$\n\nand\n\n$$\n\\frac{\\partial g}{\\partial x}=\\frac{\\partial f}{\\partial y}.\n$$\n\nThis leads to the **curl** of $\\boldsymbol{F}$ being zero\n\n$$\n\\boldsymbol{\\nabla}\\times\\boldsymbol{F}=\\boldsymbol{\\nabla}\\times\\left(-\\boldsymbol{\\nabla}V(\\boldsymbol{r})\\right)=0!\n$$\n\n## Summarizing\n\nA conservative force $\\boldsymbol{F}$ is a defined as the partial derivative of a scalar potential which depends only on the position,\n\n$$\n\\boldsymbol{F}(\\boldsymbol{r})= -\\boldsymbol{\\nabla}V(\\boldsymbol{r}).\n$$\n\nThis leads to conservation of energy and a path independent line integral as long as the curl of the force is zero, that is\n\n$$\n\\boldsymbol{\\nabla}\\times\\boldsymbol{F}=\\boldsymbol{\\nabla}\\times\\left(-\\boldsymbol{\\nabla}V(\\boldsymbol{r})\\right)=0.\n$$\n", "meta": {"hexsha": "88f586b511ce74656bb2dc4fa8ec68de5b50c0e1", "size": 79458, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/week6/ipynb/week6.ipynb", "max_stars_repo_name": "Shield94/Physics321", "max_stars_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "doc/pub/week6/ipynb/week6.ipynb", "max_issues_repo_name": "Shield94/Physics321", "max_issues_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pub/week6/ipynb/week6.ipynb", "max_forks_repo_name": "Shield94/Physics321", "max_forks_repo_head_hexsha": "9875a3bf840b0fa164b865a3cb13073aff9094ca", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5925504691, "max_line_length": 237, "alphanum_fraction": 0.5192554557, "converted": true, "num_tokens": 11679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.15880223451037037}} {"text": "# Lambda School Data Science Module 143\n\n## Introduction to Bayesian Inference\n\n!['Detector! What would the Bayesian statistician say if I asked him whether the--' [roll] 'I AM A NEUTRINO DETECTOR, NOT A LABYRINTH GUARD. SERIOUSLY, DID YOUR BRAIN FALL OUT?' [roll] '... yes.'](https://imgs.xkcd.com/comics/frequentists_vs_bayesians.png)\n\n*[XKCD 1132](https://www.xkcd.com/1132/)*\n\n\n## Prepare - Bayes' Theorem and the Bayesian mindset\n\nBayes' theorem possesses a near-mythical quality - a bit of math that somehow magically evaluates a situation. But this mythicalness has more to do with its reputation and advanced applications than the actual core of it - deriving it is actually remarkably straightforward.\n\n### The Law of Total Probability\n\nBy definition, the total probability of all outcomes (events) if some variable (event space) $A$ is 1. That is:\n\n$$P(A) = \\sum_n P(A_n) = 1$$\n\nThe law of total probability takes this further, considering two variables ($A$ and $B$) and relating their marginal probabilities (their likelihoods considered independently, without reference to one another) and their conditional probabilities (their likelihoods considered jointly). A marginal probability is simply notated as e.g. $P(A)$, while a conditional probability is notated $P(A|B)$, which reads \"probability of $A$ *given* $B$\".\n\nThe law of total probability states:\n\n$$P(A) = \\sum_n P(A | B_n) P(B_n)$$\n\nIn words - the total probability of $A$ is equal to the sum of the conditional probability of $A$ on any given event $B_n$ times the probability of that event $B_n$, and summed over all possible events in $B$.\n\n### The Law of Conditional Probability\n\nWhat's the probability of something conditioned on something else? To determine this we have to go back to set theory and think about the intersection of sets:\n\nThe formula for actual calculation:\n\n$$P(A|B) = \\frac{P(A \\cap B)}{P(B)}$$\n\n\n\nThink of the overall rectangle as the whole probability space, $A$ as the left circle, $B$ as the right circle, and their intersection as the red area. Try to visualize the ratio being described in the above formula, and how it is different from just the $P(A)$ (not conditioned on $B$).\n\nWe can see how this relates back to the law of total probability - multiply both sides by $P(B)$ and you get $P(A|B)P(B) = P(A \\cap B)$ - replaced back into the law of total probability we get $P(A) = \\sum_n P(A \\cap B_n)$.\n\nThis may not seem like an improvement at first, but try to relate it back to the above picture - if you think of sets as physical objects, we're saying that the total probability of $A$ given $B$ is all the little pieces of it intersected with $B$, added together. The conditional probability is then just that again, but divided by the probability of $B$ itself happening in the first place.\n\n### Bayes Theorem\n\n\n\nHere is is, the seemingly magic tool:\n\n$$P(A|B) = \\frac{P(B|A)P(A)}{P(B)}$$\n\nIn words - the probability of $A$ conditioned on $B$ is the probability of $B$ conditioned on $A$, times the probability of $A$ and divided by the probability of $B$. These unconditioned probabilities are referred to as \"prior beliefs\", and the conditioned probabilities as \"updated.\"\n\nWhy is this important? Scroll back up to the XKCD example - the Bayesian statistician draws a less absurd conclusion because their prior belief in the likelihood that the sun will go nova is extremely low. So, even when updated based on evidence from a detector that is $35/36 = 0.972$ accurate, the prior belief doesn't shift enough to change their overall opinion.\n\nThere's many examples of Bayes' theorem - one less absurd example is to apply to [breathalyzer tests](https://www.bayestheorem.net/breathalyzer-example/). You may think that a breathalyzer test that is 100% accurate for true positives (detecting somebody who is drunk) is pretty good, but what if it also has 8% false positives (indicating somebody is drunk when they're not)? And furthermore, the rate of drunk driving (and thus our prior belief) is 1/1000.\n\nWhat is the likelihood somebody really is drunk if they test positive? Some may guess it's 92% - the difference between the true positives and the false positives. But we have a prior belief of the background/true rate of drunk driving. Sounds like a job for Bayes' theorem!\n\n$$\n\\begin{aligned}\nP(Drunk | Positive) &= \\frac{P(Positive | Drunk)P(Drunk)}{P(Positive)} \\\\\n&= \\frac{1 \\times 0.001}{0.08} \\\\\n&= 0.0125\n\\end{aligned}\n$$\n\nIn other words, the likelihood that somebody is drunk given they tested positive with a breathalyzer in this situation is only 1.25% - probably much lower than you'd guess. This is why, in practice, it's important to have a repeated test to confirm (the probability of two false positives in a row is $0.08 * 0.08 = 0.0064$, much lower), and Bayes' theorem has been relevant in court cases where proper consideration of evidence was important.\n\n## Derive Baye's Rule\n\n\\begin{align}\nP(A|B) &= \\frac{P(A \\cap B)}{P(B)}\\\\\n\\Rightarrow P(A|B)P(B) &= P(A \\cap B)\\\\\nP(B|A) &= \\frac{P(B \\cap A)}{P(A)}\\\\\n\\Rightarrow P(B|A)P(A) &= P(B \\cap A)\\\\\n\\Rightarrow P(A|B)P(B) &= P(B|A)P(A) \\\\\nP(A \\cap B) &= P(B \\cap A)\\\\\nP(A|B) &= \\frac{P(B|A) \\times P(A)}{P(B)}\n\\end{align}\n\n## Live Lecture - Deriving Bayes' Theorem, Calculating Bayesian Confidence\n\nNotice that $P(A|B)$ appears in the above laws - in Bayesian terms, this is the belief in $A$ updated for the evidence $B$. So all we need to do is solve for this term to derive Bayes' theorem. Let's do it together!\n\n\n```python\n# Activity 2 - Use SciPy to calculate Bayesian confidence intervals\n# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bayes_mvs.html#scipy.stats.bayes_mvs\n\nfrom scipy import stats\nimport numpy as np\n\nnp.random.seed(seed=42)\n\ncoinflips = np.random.binomial(n=1, p=.5, size=100)\nprint(coinflips)\n```\n\n [0 1 1 1 0 0 0 1 1 1 0 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0\n 0 1 0 0 0 0 1 0 1 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 0 1\n 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0]\n\n\n\n```python\ndef confidence_interval(data, confidence=.95):\n n = len(data)\n mean = sum(data)/n\n data = np.array(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2.0, n-1)\n return (mean , mean-interval, mean+interval)\n```\n\n\n```python\nconfidence_interval(coinflips)\n```\n\n\n\n\n (0.47, 0.3704689875017368, 0.5695310124982632)\n\n\n\n\n```python\nhelp(stats.bayes_mvs)\n```\n\n Help on function bayes_mvs in module scipy.stats.morestats:\n \n bayes_mvs(data, alpha=0.9)\n Bayesian confidence intervals for the mean, var, and std.\n \n Parameters\n ----------\n data : array_like\n Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.\n Requires 2 or more data points.\n alpha : float, optional\n Probability that the returned confidence interval contains\n the true parameter.\n \n Returns\n -------\n mean_cntr, var_cntr, std_cntr : tuple\n The three results are for the mean, variance and standard deviation,\n respectively. Each result is a tuple of the form::\n \n (center, (lower, upper))\n \n with `center` the mean of the conditional pdf of the value given the\n data, and `(lower, upper)` a confidence interval, centered on the\n median, containing the estimate to a probability ``alpha``.\n \n See Also\n --------\n mvsdist\n \n Notes\n -----\n Each tuple of mean, variance, and standard deviation estimates represent\n the (center, (lower, upper)) with center the mean of the conditional pdf\n of the value given the data and (lower, upper) is a confidence interval\n centered on the median, containing the estimate to a probability\n ``alpha``.\n \n Converts data to 1-D and assumes all data has the same mean and variance.\n Uses Jeffrey's prior for variance and std.\n \n Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``\n \n References\n ----------\n T.E. Oliphant, \"A Bayesian perspective on estimating mean, variance, and\n standard-deviation from data\", https://scholarsarchive.byu.edu/facpub/278,\n 2006.\n \n Examples\n --------\n First a basic example to demonstrate the outputs:\n \n >>> from scipy import stats\n >>> data = [6, 9, 12, 7, 8, 8, 13]\n >>> mean, var, std = stats.bayes_mvs(data)\n >>> mean\n Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))\n >>> var\n Variance(statistic=10.0, minmax=(3.176724206..., 24.45910382...))\n >>> std\n Std_dev(statistic=2.9724954732045084, minmax=(1.7823367265645143, 4.945614605014631))\n \n Now we generate some normally distributed random data, and get estimates of\n mean and standard deviation with 95% confidence intervals for those\n estimates:\n \n >>> n_samples = 100000\n >>> data = stats.norm.rvs(size=n_samples)\n >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)\n \n >>> import matplotlib.pyplot as plt\n >>> fig = plt.figure()\n >>> ax = fig.add_subplot(111)\n >>> ax.hist(data, bins=100, density=True, label='Histogram of data')\n >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')\n >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',\n ... alpha=0.2, label=r'Estimated mean (95% limits)')\n >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')\n >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,\n ... label=r'Estimated scale (95% limits)')\n \n >>> ax.legend(fontsize=10)\n >>> ax.set_xlim([-4, 4])\n >>> ax.set_ylim([0, 0.5])\n >>> plt.show()\n \n\n\n\n```python\n#0.37046898750173674\n#0.3704689875017368\n\nstats.bayes_mvs(coinflips, alpha=.95)\n```\n\n\n\n\n (Mean(statistic=0.47, minmax=(0.37046898750173674, 0.5695310124982632)),\n Variance(statistic=0.25680412371134015, minmax=(0.1939698977025208, 0.3395533426586547)),\n Std_dev(statistic=0.5054540733507159, minmax=(0.44042013771229943, 0.5827120581030176)))\n\n\n\n\n```python\ncoinflips_mean_dist, _, _ = stats.mvsdist(coinflips)\ncoinflips_mean_dist\n```\n\n\n\n\n \n\n\n\n\n```python\nhelp(coinflips_mean_dist)\n```\n\n Help on rv_frozen in module scipy.stats._distn_infrastructure object:\n \n class rv_frozen(builtins.object)\n | rv_frozen(dist, *args, **kwds)\n | \n | # Frozen RV class\n | \n | Methods defined here:\n | \n | __init__(self, dist, *args, **kwds)\n | Initialize self. See help(type(self)) for accurate signature.\n | \n | cdf(self, x)\n | \n | entropy(self)\n | \n | expect(self, func=None, lb=None, ub=None, conditional=False, **kwds)\n | \n | interval(self, alpha)\n | \n | isf(self, q)\n | \n | logcdf(self, x)\n | \n | logpdf(self, x)\n | \n | logpmf(self, k)\n | \n | logsf(self, x)\n | \n | mean(self)\n | \n | median(self)\n | \n | moment(self, n)\n | \n | pdf(self, x)\n | \n | pmf(self, k)\n | \n | ppf(self, q)\n | \n | rvs(self, size=None, random_state=None)\n | \n | sf(self, x)\n | \n | stats(self, moments='mv')\n | \n | std(self)\n | \n | var(self)\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | random_state\n \n\n\n\n```python\ncoinflips_mean_dist.rvs(100)\n```\n\n\n\n\n array([0.47447628, 0.51541425, 0.54722018, 0.4589882 , 0.51501386,\n 0.53819192, 0.43382292, 0.53546659, 0.47026173, 0.44967562,\n 0.4621107 , 0.42691904, 0.37324325, 0.47531437, 0.46052277,\n 0.48711257, 0.52456771, 0.43332181, 0.49545882, 0.44671454,\n 0.47520117, 0.47047251, 0.41828918, 0.50159477, 0.42965501,\n 0.45273383, 0.48045849, 0.45342529, 0.48238344, 0.53966291,\n 0.48230241, 0.48073422, 0.48553525, 0.47962228, 0.41274185,\n 0.42892633, 0.5170948 , 0.42678096, 0.42249309, 0.51499109,\n 0.47059199, 0.39903942, 0.41790336, 0.46406817, 0.42232382,\n 0.42163269, 0.47848227, 0.48232842, 0.4731858 , 0.51077244,\n 0.3957508 , 0.48504646, 0.49014295, 0.53252732, 0.45495376,\n 0.47883978, 0.60393033, 0.4492549 , 0.44797902, 0.54782121,\n 0.43380002, 0.5760073 , 0.36941266, 0.44467418, 0.4939245 ,\n 0.45278835, 0.55635162, 0.48695459, 0.39080983, 0.45948606,\n 0.2941779 , 0.35950718, 0.44805696, 0.4725126 , 0.42218381,\n 0.45985418, 0.47545393, 0.44317753, 0.46267013, 0.4458753 ,\n 0.44204707, 0.51334913, 0.50914181, 0.49923748, 0.46895674,\n 0.43892798, 0.45984946, 0.44984632, 0.53560791, 0.45865723,\n 0.48646824, 0.55937503, 0.41464303, 0.50701457, 0.46934196,\n 0.37681534, 0.42748113, 0.49812825, 0.48278895, 0.4964763 ])\n\n\n\n\n```python\nimport pandas as pd\npd.DataFrame(coinflips).describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
0
count100.000000
mean0.470000
std0.501614
min0.000000
25%0.000000
50%0.000000
75%1.000000
max1.000000
\n
\n\n\n\n## Assignment - Code it up!\n\nMost of the above was pure math - now write Python code to reproduce the results! This is purposefully open ended - you'll have to think about how you should represent probabilities and events. You can and should look things up, and as a stretch goal - refactor your code into helpful reusable functions!\n\nSpecific goals/targets:\n\n1. Write a function `def prob_drunk_given_positive(prob_drunk_prior, prob_positive, prob_positive_drunk)` that reproduces the example from lecture, and use it to calculate and visualize a range of situations\n2. Explore `scipy.stats.bayes_mvs` - read its documentation, and experiment with it on data you've tested in other ways earlier this week\n3. Create a visualization comparing the results of a Bayesian approach to a traditional/frequentist approach\n4. In your own words, summarize the difference between Bayesian and Frequentist statistics\n\nIf you're unsure where to start, check out [this blog post of Bayes theorem with Python](https://dataconomy.com/2015/02/introduction-to-bayes-theorem-with-python/) - you could and should create something similar!\n\nStretch goals:\n\n- Apply a Bayesian technique to a problem you previously worked (in an assignment or project work) on from a frequentist (standard) perspective\n- Check out [PyMC3](https://docs.pymc.io/) (note this goes beyond hypothesis tests into modeling) - read the guides and work through some examples\n- Take PyMC3 further - see if you can build something with it!\n\n\n```python\nimport pandas as pd\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n```\n\n## Problem 1\n\n\n```python\ndef prob_drunk_given_positive(prob_positive_drunk, prob_drunk_prior, prob_positive):\n test1 = (prob_positive_drunk * prob_drunk_prior) / prob_positive\n test2 = (prob_positive_drunk * prob_drunk_prior) / (prob_positive)**2 \n result1 = 'Probability a person is drunk, given one failed breathalyzer test:', test1\n result2 = 'Probability a person is drunk, given two failed breathalyzer tests:', test2\n return result1, result2\n\nprob_drunk_given_positive(1, 0.001, 0.08)\n```\n\n\n\n\n (('Probability a person is drunk, given one failed breathalyzer test:',\n 0.0125),\n ('Probability a person is drunk, given two failed breathalyzer tests:',\n 0.15625))\n\n\n\n## Problem 2\n\n\n```python\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/voting-records/house-votes-84.data'\ncolumns = ['class_name', 'handicapped_infants', 'water_project_cost_sharing', 'adoption_of_the_budget_resolution',\n 'physician_fee_freeze', 'el_salvador_aid', 'religious_groups_in_schools', 'anti_satellite_test_ban',\n 'aid_to_nicaraguan_contras', 'mx_missile', 'immigration', 'synfuels_corporation_cutback',\n 'education_spending', 'superfund_right_to_sue', 'crime', 'duty_free_exports',\n 'export_administration_act_south_africa']\n\ndf = pd.read_csv(url, header=None, names=columns, na_values='?').set_index('class_name')\ndf.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
handicapped_infantswater_project_cost_sharingadoption_of_the_budget_resolutionphysician_fee_freezeel_salvador_aidreligious_groups_in_schoolsanti_satellite_test_banaid_to_nicaraguan_contrasmx_missileimmigrationsynfuels_corporation_cutbackeducation_spendingsuperfund_right_to_suecrimeduty_free_exportsexport_administration_act_south_africa
class_name
republicannynyyynnnyNaNyyyny
republicannynyyynnnnnyyynNaN
democratNaNyyNaNyynnnnynyynn
democratnyynNaNynnnnynynny
democratyyynyynnnnyNaNyyyy
\n
\n\n\n\n\n```python\n# Removed nan values because bayes_mvs doesn't have an omit param\ndf = df.dropna()\n```\n\n\n```python\ndf = df.replace({'y': 1, 'n': 0})\n```\n\n\n```python\nrep = df.loc['republican']\ndem = df.loc['democrat']\n```\n\n\n```python\nrep.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
handicapped_infantswater_project_cost_sharingadoption_of_the_budget_resolutionphysician_fee_freezeel_salvador_aidreligious_groups_in_schoolsanti_satellite_test_banaid_to_nicaraguan_contrasmx_missileimmigrationsynfuels_corporation_cutbackeducation_spendingsuperfund_right_to_suecrimeduty_free_exportsexport_administration_act_south_africa
class_name
republican0101110000011101
republican1001101110011101
republican0101110000011100
republican0101110000011101
republican0101110000011100
\n
\n\n\n\n\n```python\ndem.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
handicapped_infantswater_project_cost_sharingadoption_of_the_budget_resolutionphysician_fee_freezeel_salvador_aidreligious_groups_in_schoolsanti_satellite_test_banaid_to_nicaraguan_contrasmx_missileimmigrationsynfuels_corporation_cutbackeducation_spendingsuperfund_right_to_suecrimeduty_free_exportsexport_administration_act_south_africa
class_name
democrat0110110000001111
democrat1110001110100011
democrat1110001110000011
democrat1010001111000011
democrat1010001110100011
\n
\n\n\n\n\n```python\ndef confidence_interval(data, confidence=0.95):\n '''\n Calculate a confidence interval around a sample mean for given data.\n using t-distribution and two tailed test, default 95% confidence.\n \n Arguments:\n data = iterable (list or np array) of sample observations\n confidence - level of confidence for interval\n '''\n \n data = np.array(data)\n mean = np.mean(data)\n n = len(data)\n stderr = stats.sem(data)\n interval = stderr * stats.t.ppf((1 + confidence) / 2., n-1)\n return (mean, mean - interval, mean + interval)\n\ndef report_confidence_interval(confidence_interval):\n '''\n Return a string with a pretty report of a confidence interval\n \n Arguments:\n confidence_interval - a tuple of (mean, lower bount, upper bound)\n \n Returns:\n None, but prints to screen the report\n '''\n# print('Mean: {}'.format(confidence_interval[0]))\n# print('Lower bound: {}'.format(confidence_interval[1]))\n# print('Upper bound: {}'.format(confidence_interval[2]))\n s = 'our mean lies in the interval [{:.2}, {:.2}]'.format(\n confidence_interval[1], confidence_interval[2])\n return s\n```\n\n\n```python\nstats.bayes_mvs(rep['handicapped_infants'], alpha=0.95)\n```\n\n\n\n\n (Mean(statistic=0.21296296296296297, minmax=(0.13450349074958223, 0.2914224351763437)),\n Variance(statistic=0.1723985890652557, minmax=(0.13163384272877396, 0.22552107883595443)),\n Std_dev(statistic=0.4142216885759803, minmax=(0.3628137851967231, 0.4748905967019713)))\n\n\n\n\n```python\nconfidence_interval(rep['handicapped_infants'])\n```\n\n\n\n\n (0.21296296296296297, 0.13450349074958223, 0.2914224351763437)\n\n\n\n\n```python\nrep.describe().T\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countmeanstdmin25%50%75%max
handicapped_infants108.00.2129630.4113100.00.00.00.01.0
water_project_cost_sharing108.00.4722220.5015550.00.00.01.01.0
adoption_of_the_budget_resolution108.00.1574070.3658820.00.00.00.01.0
physician_fee_freeze108.00.9907410.0962250.01.01.01.01.0
el_salvador_aid108.00.9537040.2111060.01.01.01.01.0
religious_groups_in_schools108.00.8703700.3374610.01.01.01.01.0
anti_satellite_test_ban108.00.2685190.4452550.00.00.01.01.0
aid_to_nicaraguan_contras108.00.1481480.3569030.00.00.00.01.0
mx_missile108.00.1388890.3474430.00.00.00.01.0
immigration108.00.5740740.4967880.00.01.01.01.0
synfuels_corporation_cutback108.00.1574070.3658820.00.00.00.01.0
education_spending108.00.8518520.3569030.01.01.01.01.0
superfund_right_to_sue108.00.8425930.3658820.01.01.01.01.0
crime108.00.9814810.1354450.01.01.01.01.0
duty_free_exports108.00.1111110.3157350.00.00.00.01.0
export_administration_act_south_africa108.00.6666670.4736020.00.01.01.01.0
\n
\n\n\n\n\n```python\nstats.bayes_mvs(dem['handicapped_infants'], alpha=0.95)\n```\n\n\n\n\n (Mean(statistic=0.5887096774193549, minmax=(0.5008854514528095, 0.6765339033859002)),\n Variance(statistic=0.24813383097840572, minmax=(0.1929709352919263, 0.3187452362753357)),\n Std_dev(statistic=0.4971022146015008, minmax=(0.4392845721077925, 0.5645752706905747)))\n\n\n\n### Tuple unpacking: this will allow me to add the bayesian mean, upper bound, and lower bound to the comparison table for problem 3.\n\n\n```python\na, b, c = stats.bayes_mvs(dem['handicapped_infants'], alpha=0.95)\n```\n\n\n```python\nprint(a)\nprint(b)\nprint(c)\n```\n\n Mean(statistic=0.5887096774193549, minmax=(0.5008854514528095, 0.6765339033859002))\n Variance(statistic=0.24813383097840572, minmax=(0.1929709352919263, 0.3187452362753357))\n Std_dev(statistic=0.4971022146015008, minmax=(0.4392845721077925, 0.5645752706905747))\n\n\n\n```python\nd, e = a\n```\n\n\n```python\nprint(d)\nprint(e)\n```\n\n 0.5887096774193549\n (0.5008854514528095, 0.6765339033859002)\n\n\n\n```python\nf,g = e\nprint(f)\nprint(g)\n```\n\n 0.5008854514528095\n 0.6765339033859002\n\n\n\n```python\nstats.ttest_1samp(dem['handicapped_infants'], 0.588710)\n```\n\n\n\n\n Ttest_1sampResult(statistic=-7.270529297663421e-06, pvalue=0.9999942107355586)\n\n\n\n\n```python\nconfidence_interval(dem['handicapped_infants'])\n```\n\n\n\n\n (0.5887096774193549, 0.5008854514528094, 0.6765339033859004)\n\n\n\n\n```python\ndem.describe().T\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countmeanstdmin25%50%75%max
handicapped_infants124.00.5887100.4940640.00.01.01.01.0
water_project_cost_sharing124.00.4516130.4996720.00.00.01.01.0
adoption_of_the_budget_resolution124.00.8548390.3536920.01.01.01.01.0
physician_fee_freeze124.00.0483870.2154530.00.00.00.01.0
el_salvador_aid124.00.2016130.4028320.00.00.00.01.0
religious_groups_in_schools124.00.4435480.4988180.00.00.01.01.0
anti_satellite_test_ban124.00.7661290.4250080.01.01.01.01.0
aid_to_nicaraguan_contras124.00.8306450.3765870.01.01.01.01.0
mx_missile124.00.7903230.4087300.01.01.01.01.0
immigration124.00.5322580.5009830.00.01.01.01.0
synfuels_corporation_cutback124.00.5080650.5019630.00.01.01.01.0
education_spending124.00.1290320.3365960.00.00.00.01.0
superfund_right_to_sue124.00.2903230.4557530.00.00.01.01.0
crime124.00.3467740.4778740.00.00.01.01.0
duty_free_exports124.00.5967740.4925350.00.01.01.01.0
export_administration_act_south_africa124.00.9435480.2317280.01.01.01.01.0
\n
\n\n\n\n## Problem 3\n\n\n```python\ntable = pd.DataFrame()\n\ndef comparison_table(rep_df, dem_df):\n confidence = 0.95\n for issue in rep_df.describe():\n table.loc[issue, 'dem_mean'] = dem_df[issue].mean()\n table.loc[issue, 'rep_mean'] = rep_df[issue].mean()\n table.loc[issue, 'dem_interval'] = stats.sem(dem_df[issue])*stats.t.ppf((1+confidence)/2, dem_df[issue].size-1)\n table.loc[issue, 'rep_interval'] = stats.sem(rep_df[issue])*stats.t.ppf((1+confidence)/2, rep_df[issue].size-1)\n table.loc[issue, 'dem_ub_ci'] = table.loc[issue, 'dem_mean'] + table.loc[issue, 'dem_interval']\n table.loc[issue, 'rep_ub_ci'] = table.loc[issue, 'rep_mean'] + table.loc[issue, 'rep_interval']\n table.loc[issue, 'dem_lb_ci'] = table.loc[issue, 'dem_mean'] - table.loc[issue, 'dem_interval']\n table.loc[issue, 'rep_lb_ci'] = table.loc[issue, 'rep_mean'] - table.loc[issue, 'rep_interval']\n dem_bayes = stats.bayes_mvs(dem_df[issue], alpha=0.95)\n dem_a, dem_b, dem_c = dem_bayes\n dem_d, dem_e = dem_a\n dem_f, dem_g = dem_e\n table.loc[issue, 'dem_bayes_mean'] = dem_d\n table.loc[issue, 'dem_bayes_ub'] = dem_g\n table.loc[issue, 'dem_bayes_lb'] = dem_f\n rep_bayes = stats.bayes_mvs(rep_df[issue], alpha=0.95)\n rep_a, rep_b, rep_c = rep_bayes\n rep_d, rep_e = rep_a\n rep_f, rep_g = rep_e\n table.loc[issue, 'rep_bayes_mean'] = rep_d\n table.loc[issue, 'rep_bayes_ub'] = rep_g\n table.loc[issue, 'rep_bayes_lb'] = rep_f\n return table\n\ncomparison_table(rep, dem)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
dem_meanrep_meandem_intervalrep_intervaldem_ub_cirep_ub_cidem_lb_cirep_lb_cidem_bayes_meandem_bayes_ubdem_bayes_lbrep_bayes_meanrep_bayes_ubrep_bayes_lb
handicapped_infants0.5887100.2129630.0878240.0784590.6765340.2914220.5008850.1345030.5887100.6765340.5008850.2129630.2914220.134503
water_project_cost_sharing0.4516130.4722220.0888210.0956740.5404340.5678960.3627920.3765480.4516130.5404340.3627920.4722220.5678960.376548
adoption_of_the_budget_resolution0.8548390.1574070.0628720.0697940.9177110.2272010.7919670.0876140.8548390.9177110.7919670.1574070.2272010.087614
physician_fee_freeze0.0483870.9907410.0382990.0183550.0866861.0090960.0100880.9723850.0483870.0866860.0100880.9907411.0090960.972385
el_salvador_aid0.2016130.9537040.0716070.0402690.2732200.9939730.1300060.9134340.2016130.2732200.1300060.9537040.9939730.913434
religious_groups_in_schools0.4435480.8703700.0886690.0643720.5322180.9347430.3548790.8059980.4435480.5322180.3548790.8703700.9347430.805998
anti_satellite_test_ban0.7661290.2685190.0755490.0849350.8416780.3534530.6905800.1835840.7661290.8416780.6905800.2685190.3534530.183584
aid_to_nicaraguan_contras0.8306450.1481480.0669420.0680810.8975870.2162290.7637040.0800670.8306450.8975870.7637040.1481480.2162290.080067
mx_missile0.7903230.1388890.0726550.0662760.8629780.2051650.7176670.0726120.7903230.8629780.7176670.1388890.2051650.072612
immigration0.5322580.5740740.0890540.0947650.6213120.6688390.4432040.4793090.5322580.6213120.4432040.5740740.6688390.479309
synfuels_corporation_cutback0.5080650.1574070.0892280.0697940.5972930.2272010.4188360.0876140.5080650.5972930.4188360.1574070.2272010.087614
education_spending0.1290320.8518520.0598330.0680810.1888650.9199330.0691990.7837710.1290320.1888650.0691990.8518520.9199330.783771
superfund_right_to_sue0.2903230.8425930.0810140.0697940.3713370.9123860.2093090.7727990.2903230.3713370.2093090.8425930.9123860.772799
crime0.3467740.9814810.0849460.0258370.4317211.0073180.2618280.9556450.3467740.4317210.2618280.9814811.0073180.955645
duty_free_exports0.5967740.1111110.0875530.0602280.6843270.1713390.5092220.0508830.5967740.6843270.5092220.1111110.1713390.050883
export_administration_act_south_africa0.9435480.6666670.0411920.0903420.9847400.7570090.9023570.5763250.9435480.9847400.9023570.6666670.7570090.576325
\n
\n\n\n\n\n```python\ntable = table.reset_index()\ntable.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
indexdem_meanrep_meandem_intervalrep_intervaldem_ub_cirep_ub_cidem_lb_cirep_lb_cidem_bayes_meandem_bayes_ubdem_bayes_lbrep_bayes_meanrep_bayes_ubrep_bayes_lb
0handicapped_infants0.5887100.2129630.0878240.0784590.6765340.2914220.5008850.1345030.5887100.6765340.5008850.2129630.2914220.134503
1water_project_cost_sharing0.4516130.4722220.0888210.0956740.5404340.5678960.3627920.3765480.4516130.5404340.3627920.4722220.5678960.376548
2adoption_of_the_budget_resolution0.8548390.1574070.0628720.0697940.9177110.2272010.7919670.0876140.8548390.9177110.7919670.1574070.2272010.087614
3physician_fee_freeze0.0483870.9907410.0382990.0183550.0866861.0090960.0100880.9723850.0483870.0866860.0100880.9907411.0090960.972385
4el_salvador_aid0.2016130.9537040.0716070.0402690.2732200.9939730.1300060.9134340.2016130.2732200.1300060.9537040.9939730.913434
\n
\n\n\n\n\n```python\nrep_freq = table[['index', 'rep_mean', 'rep_lb_ci', 'rep_ub_ci']]\ndem_freq = table[['index', 'dem_mean', 'dem_lb_ci', 'dem_ub_ci']]\nrep_bayes = table[['index', 'rep_bayes_mean', 'rep_bayes_lb', 'rep_bayes_ub']]\ndem_bayes = table[['index', 'dem_bayes_mean', 'dem_bayes_lb', 'dem_bayes_ub']]\n```\n\n\n```python\n# Plot frequentist approach\ndem_means, dem_std = dem_freq['dem_mean'], (dem_freq['dem_ub_ci'] - dem_freq['dem_mean']);\nrep_means, rep_std = rep_freq['rep_mean'], (rep_freq['rep_ub_ci'] - rep_freq['rep_mean']);\n\nind = np.arange(len(dem_freq))\nwidth = 0.3\n\n# create plot\nfig, ax = plt.subplots(figsize=(25, 9))\n\ndem_rects = ax.bar(ind - width/2, dem_means, width, yerr=dem_std,\n color='blue', label='House Democrats');\nrep_rects = ax.bar(ind + width/2, rep_means, width, yerr=rep_std,\n color='red', label='House Republicans');\n\n# labeling\nax.set_title('Distribution of House of Representatives Voting in 1984', fontsize=18);\nax.set_ylabel('Probability to Vote Yes', fontsize=14);\nax.set_xticks(ind);\nax.set_xticklabels(('handicapped_infants', 'water_project_cost_sharing', 'adoption_of_the_budget_resolution',\n 'physician_fee_freeze', 'el_salvador_aid', 'religious_groups_in_schools', 'anti_satellite_test_ban',\n 'aid_to_nicaraguan_contras', 'mx_missile', 'immigration', 'synfuels_corporation_cutback',\n 'education_spending', 'superfund_right_to_sue', 'crime', 'duty_free_exports',\n 'export_administration_act_south_africa'));\nax.set_xticklabels(ax.get_xticklabels(), rotation=60, horizontalalignment='right', fontsize=14);\nax.legend();\n\n\n```\n\n\n```python\n# Plot frequentist approach\ndem_means, dem_std = dem_bayes['dem_bayes_mean'], (dem_bayes['dem_bayes_ub'] - dem_bayes['dem_bayes_mean']);\nrep_means, rep_std = rep_bayes['rep_bayes_mean'], (rep_bayes['rep_bayes_ub'] - rep_bayes['rep_bayes_mean']);\n\nind = np.arange(len(dem_bayes))\nwidth = 0.3\n\n# create plot\nfig, ax = plt.subplots(figsize=(25, 9))\n\ndem_rects = ax.bar(ind - width/2, dem_means, width, yerr=dem_std,\n color='blue', label='House Democrats');\nrep_rects = ax.bar(ind + width/2, rep_means, width, yerr=rep_std,\n color='red', label='House Republicans');\n\n# labeling\nax.set_title('Distribution of House of Representatives Voting in 1984', fontsize=18);\nax.set_ylabel('Probability to Vote Yes', fontsize=14);\nax.set_xticks(ind);\nax.set_xticklabels(('handicapped_infants', 'water_project_cost_sharing', 'adoption_of_the_budget_resolution',\n 'physician_fee_freeze', 'el_salvador_aid', 'religious_groups_in_schools', 'anti_satellite_test_ban',\n 'aid_to_nicaraguan_contras', 'mx_missile', 'immigration', 'synfuels_corporation_cutback',\n 'education_spending', 'superfund_right_to_sue', 'crime', 'duty_free_exports',\n 'export_administration_act_south_africa'));\nax.set_xticklabels(ax.get_xticklabels(), rotation=60, horizontalalignment='right', fontsize=14);\nax.legend();\n\n```\n\n## Problem 4\n\nThe results from the frequentist approach and the Bayesian approach were very similar, but had slight differences. Those differences could be enough to make the frequentist approach less reliable, depending on the data set. For data sets that require high precision, you should use the Baeysian approach.\n\n## Resources\n\n- [Worked example of Bayes rule calculation](https://en.wikipedia.org/wiki/Bayes'_theorem#Examples) (helpful as it fully breaks out the denominator)\n- [Source code for mvsdist in scipy](https://github.com/scipy/scipy/blob/90534919e139d2a81c24bf08341734ff41a3db12/scipy/stats/morestats.py#L139)\n", "meta": {"hexsha": "4411606971c6b9a62a1d312b9363319698f863b8", "size": 349767, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "module3-introduction-to-bayesian-inference/LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_stars_repo_name": "JLDaniel77/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_stars_repo_head_hexsha": "87f57558233c2558e023912fc5d6e0ee35ec58e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "module3-introduction-to-bayesian-inference/LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_issues_repo_name": "JLDaniel77/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_issues_repo_head_hexsha": "87f57558233c2558e023912fc5d6e0ee35ec58e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module3-introduction-to-bayesian-inference/LS_DS3_143_Introduction_to_Bayesian_Inference.ipynb", "max_forks_repo_name": "JLDaniel77/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments", "max_forks_repo_head_hexsha": "87f57558233c2558e023912fc5d6e0ee35ec58e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 109.8859566447, "max_line_length": 116728, "alphanum_fraction": 0.7837817747, "converted": true, "num_tokens": 19022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.15747526376050383}} {"text": "```javascript\n%%javascript\nMathJax.Hub.Config({\n TeX: { equationNumbers: { autoNumber: \"AMS\" } }\n});\nMathJax.Hub.Queue(\n [\"resetEquationNumbers\", MathJax.InputJax.TeX],\n [\"PreProcess\", MathJax.Hub],\n [\"Reprocess\", MathJax.Hub]);\n```\n\n\n \n\n\n\n\n\n$$\\newcommand{\\ket}[1]{\\left|{#1}\\right\\rangle}$$\n$$\\newcommand{\\bra}[1]{\\left\\langle{#1}\\right|}$$\n$$\\newcommand{\\braket}[2]{\\left\\langle{#1}\\middle|{#2}\\right\\rangle}$$\n\n\n# Flexible Representation of Quantum Images (FRQI)\n\n\nThe goal of the Flexible Representation of Quantum Images (FRQI) [1] is to provide a quantum representation of images that allows an efficient encoding of the classical data into a quantum state and the subsequent use of operators for image processing operations.\nIn this case, encoding the classical image into a quantum state requires a polynomial number of simple gates [2].\n\n## The FRQI state\n\nThe quantum state representing the image is:\n\n\\begin{equation}\n\\ket{I(\\theta}=\\frac{1}{2^{n}}\\sum_{i=0}^{2^{2n}-1}\\left(\\cos \\theta_{i}\\ket{0}+\\sin\\theta_{i}\\ket{1}\\right)\\otimes\\ket{i}\n\\label{eq:FRQI_state}\n\\end{equation}\n\n\\begin{equation}\n \\theta_{i}\\in\\left[ 0,\\frac{\\pi}{2}\\right], i = 0,1,\\cdots,2^{2n}-1\n \\label{eq:FRQI_angle}\n\\end{equation}\n\nThe FRQI state is a normalized state as from equation $\\eqref{eq:FRQI_state}$ we see that $\\left\\|I(\\theta)\\right\\|=1$\nand is made of two parts:\n\n* color information encoding: $\\cos\\theta_{i}\\ket{0}+\\sin\\theta_{i}\\ket{1}$ \n* associated pixel position encoding: $\\ket{i}$\n\n\nA simple example for a $2x2$ image is given below, with corresponding $\\theta$ angles (color encoding) and associated kets (position encoding) :\n\n\\begin{array}{|c|c|}\n\\hline\n\\theta_{0},\\ket{00} & \\theta_{1},\\ket{01} \\\\\n\\hline\n\\theta_{2},,\\ket{10} & \\theta_{3},,\\ket{11} \\\\\n\\hline\n\\end{array}\n\nAnd the equivalent quantum state is \n\\begin{equation*}\n\\ket{I}=\\frac{1}{2}\\left[ \\left(\\cos\\theta_{0}\\ket{0}+\\sin\\theta_{0}\\ket{1} \\right)\\otimes\\ket{00} + \\left(\\cos\\theta_{1}\\ket{0}+\\sin\\theta_{1}\\ket{1} \\right)\\otimes\\ket{01} \\\\+ \\left(\\cos\\theta_{2}\\ket{0}+\\sin\\theta_{2}\\ket{1} \\right)\\otimes\\ket{10} + \\left(\\cos\\theta_{3}\\ket{0}+\\sin\\theta_{3}\\ket{1} \\right)\\otimes\\ket{11}\\right]\n\\label{eq:22state} \\tag{2.1}\n\\end{equation*}\n\n## Building the FRQI state: a two steps process\n\nGoing from an initialized state $\\ket{0}^{\\otimes2n+1}$ to the FRQI state specified in $\\eqref{eq:FRQI_state}$ is a two steps process and we first need to put the system in full superposition, except for the last qubit which we will use to encode the color. $H^{\\otimes2n}$ being the tensor product of $2n$ Hadamard operations, our intermediate state is \n\n\\begin{equation}\n\\ket{H}=\\frac{1}{2^{n}}\\ket{0}\\otimes\\sum_{i=0}^{2^{2n}-1}\\ket{i}=\\mathcal{H}\\left(\\ket{0}^{\\otimes2n+1}\\right)\n\\label{eq:superpos}\n\\end{equation}\n\nAs demonstrated in [1] there exist a unitary transformation $\\mathcal{P}=\\mathcal{RH}$ transforming the initial state $\\ket{0}^{\\otimes2n+1}$ into the FRQI $I(\\theta)$ state and \n\n\\begin{equation}\n\\mathcal{R}\\ket{H}=\\left(\\prod_{i=0}^{2^{2n}-1}R_{i}\\right)\\ket{H}=\\ket{I(\\theta)}\n\\end{equation}\n\nThe $R_{i}$ operations are controlled rotations matrices defined by:\n\n\\begin{equation}\nR_{i}=\\left( I\\otimes \\sum^{2^{2n}-1}_{j=0,j\\neq i}\\ket{j}\\bra{j}\\right) + R_{y}\\left(2\\theta_{i}\\right)\\otimes\\ket{i}\\bra{i}\n\\end{equation}\n\nWhere $R_{y}(2\\theta_{i})$ are the standard rotation matrices:\n\n\\begin{equation}\nR_{y}(2\\theta_{i})=\n\\begin{pmatrix}\n\\cos\\theta_{i} & -\\sin\\theta_{i}\\\\\n\\sin\\theta_{i} & \\cos\\theta_{i} \n\\end{pmatrix}\n\\end{equation}\n\nThe controlled rotations can be implemented via the generalized $C^{2n}\\left( R_{y}(2\\theta_{i} \\right)$, which can be broken down into standard rotations and $CNOT$ gates.\nFor instance if we take the case for $n=1$, which means we have $4$ pixels (i.e. a $2x2$ image), we do have the following equivalence, which can then be implemented easily.\n\n\n \n\nNote that we still need to take care of the increment in the pixel location, this is done via the $X$ gates.\n\n\n\n**References**: \n\n[1] Le, P.Q., Dong, F. & Hirota, K. A flexible representation of quantum images for polynomial preparation, image compression, and processing operations. Quantum Inf Process 10, 63–84 (2011). https://doi.org/10.1007/s11128-010-0177-y \n\n[2] Le, Phuc Quang, Fayang Dong and Kaoru Hirota. “Flexible Representation of Quantum Images and Its Computational Complexity Analysis.” (2009). https://doi.org/10.14864/fss.25.0.185.0\n\n\n```python\n# Prep the code: \n%matplotlib inline\n# Importing standard Qiskit libraries and configuring account\nimport qiskit as qk\nfrom qiskit import QuantumCircuit, execute, Aer, IBMQ\nfrom qiskit.compiler import transpile, assemble\nfrom qiskit.tools.jupyter import *\nfrom qiskit.visualization import *\nfrom math import pi\n#Loading your IBM Q account(s)\nprovider = IBMQ.load_account()\n#%qiskit_job_watcher\n\n\n```\n\n ibmqfactory.load_account:WARNING:2020-06-29 17:57:10,261: Credentials are already in use. The existing account in the session will be replaced.\n\n\n## Implementation and measurement : 2x2 image, greyscale values\n\nBarriers are used for added clarity on the different blocks associated with individual pixels.\nWe also use greyscale images (i.e. the L component of a LRGB image), which means only one value is of interest for the color encoding: the intensity. In other words, all angles $\\theta_{i}$ equal to $0$ means that all the pixels are black, if all $\\theta_{i}$ values are equal to $\\pi/2$ then all the pixels are white, and so on. The values of interest are $0, \\pi/4 \\; and \\; \\pi/2$.\n\n### Exemple 1 : $\\theta_{i}=0 \\;, \\; \\forall i$ - all pixels at minimum intensity\n\n\n\n\n```python\nqr = qk.QuantumRegister(3)\ncr = qk.ClassicalRegister(3)\nqc= qk.QuantumCircuit(qr,cr)\n\n\ntheta=0 # all pixels black\n#theta=pi/4 # all pixels half greyscale intensity\n#theta=pi/2 # all pixels white\n#theta=pi/8 # all pixels at 25% intensity\n\nqc.h(0)\nqc.h(1)\n\nqc.barrier(qr)\n#Pixel 1\n\nqc.cry(theta,0,2)\nqc.cx(0,1)\nqc.cry(-theta,1,2)\nqc.cx(0,1)\nqc.cry(theta,1,2)\n\nqc.barrier(qr)\n#Pixel 2\n\nqc.x(1)\n\nqc.cry(theta,0,2)\nqc.cx(0,1)\nqc.cry(-theta,1,2)\nqc.cx(0,1)\nqc.cry(theta,1,2)\n\nqc.barrier(qr)\n\nqc.x(1)\nqc.x(0)\nqc.cry(theta,0,2)\nqc.cx(0,1)\nqc.cry(-theta,1,2)\nqc.cx(0,1)\nqc.cry(theta,1,2)\n\n\nqc.barrier(qr)\n\nqc.x(1)\n\nqc.cry(theta,0,2)\nqc.cx(0,1)\nqc.cry(-theta,1,2)\nqc.cx(0,1)\nqc.cry(theta,1,2)\n\n\nqc.barrier(qr)\nqc.measure(qr,cr)\n\ncircuit_drawer(qc, output=\"mpl\")\n```\n\n### Measurement and image retrieval\n\n\nWe can see from $\\eqref{eq:22state}$ that all the terms associated with the state $\\ket{1}$ in the color encoding part of the FRQI state will vanish because of the value of $\\theta$ so we do expect to see only $4$ equiprobable states.\n\n\n\n```python\nbackend_sim = Aer.get_backend('qasm_simulator')\njob_sim = execute(qc, backend_sim,shots=4096)\nresult_sim = job_sim.result()\ncounts = result_sim.get_counts(qc)\nprint(counts)\nplot_histogram(counts)\n```\n\n### Exemple 2 : $\\theta_{i}=\\pi/2 \\;, \\; \\forall i$ - all pixels at maximum intensity\n\nThe circuit is identical to the first defined, except for the value of $\\theta$.\n\n\n```python\nqr1 = qk.QuantumRegister(3)\ncr1 = qk.ClassicalRegister(3)\nqc1 = qk.QuantumCircuit(qr1,cr1)\n\n\ntheta=pi/2 # all pixels white\n\n\nqc1.h(0)\nqc1.h(1)\n\nqc1.barrier(qr1)\n#Pixel 1\n\nqc1.cry(theta,0,2)\nqc1.cx(0,1)\nqc1.cry(-theta,1,2)\nqc1.cx(0,1)\nqc1.cry(theta,1,2)\n\nqc1.barrier(qr1)\n#Pixel 2\n\nqc1.x(1)\n\nqc1.cry(theta,0,2)\nqc1.cx(0,1)\nqc1.cry(-theta,1,2)\nqc1.cx(0,1)\nqc1.cry(theta,1,2)\n\nqc1.barrier(qr1)\n\nqc1.x(1)\nqc1.x(0)\nqc1.cry(theta,0,2)\nqc1.cx(0,1)\nqc1.cry(-theta,1,2)\nqc1.cx(0,1)\nqc1.cry(theta,1,2)\n\n\nqc1.barrier(qr1)\n\nqc1.x(1)\n\nqc1.cry(theta,0,2)\nqc1.cx(0,1)\nqc1.cry(-theta,1,2)\nqc1.cx(0,1)\nqc1.cry(theta,1,2)\n\n\nqc1.barrier(qr1)\nqc1.measure(qr1,cr1)\n\ncircuit_drawer(qc1, output=\"mpl\")\n```\n\n### Measurement and image retrieval\nIn this case we do expect to see the terms associated with the $\\cos$ in the equation $\\eqref{eq:22state}$ to vanish, and get 4 equiprobable states with a \"1\" prefix.\n\n\n```python\nbackend_sim = Aer.get_backend('qasm_simulator')\njob_sim = execute(qc1, backend_sim,shots=4096)\nresult_sim = job_sim.result()\ncounts = result_sim.get_counts(qc1)\nprint(counts)\nplot_histogram(counts)\n```\n\n### Exemple 3 : $\\theta_{i}=\\pi/4 \\;, \\; \\forall i$ - all pixels at $50\\%$ intensity\n\n\n```python\nqr2 = qk.QuantumRegister(3)\ncr2 = qk.ClassicalRegister(3)\nqc2 = qk.QuantumCircuit(qr2,cr2)\n\n\ntheta=pi/4 # all pixels white\n\n\nqc2.h(0)\nqc2.h(1)\n\nqc2.barrier(qr2)\n#Pixel 1\n\nqc2.cry(theta,0,2)\nqc2.cx(0,1)\nqc2.cry(-theta,1,2)\nqc2.cx(0,1)\nqc2.cry(theta,1,2)\n\nqc2.barrier(qr2)\n#Pixel 2\n\nqc2.x(1)\n\nqc2.cry(theta,0,2)\nqc2.cx(0,1)\nqc2.cry(-theta,1,2)\nqc2.cx(0,1)\nqc2.cry(theta,1,2)\n\nqc2.barrier(qr2)\n\nqc2.x(1)\nqc2.x(0)\nqc2.cry(theta,0,2)\nqc2.cx(0,1)\nqc2.cry(-theta,1,2)\nqc2.cx(0,1)\nqc2.cry(theta,1,2)\n\n\nqc2.barrier(qr2)\n\nqc2.x(1)\n\nqc2.cry(theta,0,2)\nqc2.cx(0,1)\nqc2.cry(-theta,1,2)\nqc2.cx(0,1)\nqc2.cry(theta,1,2)\n\n\nqc2.barrier(qr2)\nqc2.measure(qr2,cr2)\n\ncircuit_drawer(qc2, output=\"mpl\")\n```\n\n### Measurement and image retrieval\nIn this case we do expect to get all the 8 equiprobable states.\n\n\n```python\nbackend_sim = Aer.get_backend('qasm_simulator')\njob_sim = execute(qc2, backend_sim,shots=4096)\nresult_sim = job_sim.result()\ncounts = result_sim.get_counts(qc2)\nprint(counts)\nplot_histogram(counts)\n```\n\n## Circuit analysis and run on a real device\nAs the only difference between the circuits is the rotation angle $\\theta$, we can check the depth, and number of gates needed for this class of circuits (i.e. 2x2 images).\n\n### Circuit analysis\n\nLet's use our circuit with $\\theta_{i}=\\pi/2 \\;, \\; \\forall i$ as exemple (maximum intensity for all pixels).\n\n\n```python\nprint(\"Depth : \",qc1.depth())\nprint(\"Operations: \", qc1.count_ops())\n```\n\n Depth : 23\n Operations: OrderedDict([('cry', 12), ('cx', 8), ('barrier', 5), ('x', 4), ('measure', 3), ('h', 2)])\n\n\nThis does not look too complex but if we want to see how this circuit can be unrolled by the transpiler, it gets a bit more complicated.\n\n\n```python\nfrom qiskit.compiler import transpile\nfrom qiskit.transpiler import PassManager\nfrom qiskit.transpiler.passes import Unroller\npass_ = Unroller(['u3', 'cx'])\npm = PassManager(pass_)\nnew_circ = pm.run(qc1)\nnew_circ.draw(output='mpl')\n```\n\n\n```python\nprint(\"Depth : \",new_circ.depth())\nprint(\"Operations: \", new_circ.count_ops())\n```\n\n Depth : 50\n Operations: OrderedDict([('cx', 32), ('u3', 30), ('barrier', 5), ('measure', 3)])\n\n\nThe depth for example doubled in size ! \n\nWe can get closer to what would actually be run on a real device by feeding the transpiler with a device coupling map (for instance, Vigo). We will also use optimization level 3.\n\n\n```python\nfrom qiskit.test.mock import FakeRome\ndevice_backend = FakeRome()\n# The device coupling map is needed for transpiling to correct\n# CNOT gates before simulation\ncoupling_map = device_backend.configuration().coupling_map\noptimized_3 = transpile(qc1, backend=device_backend, seed_transpiler=11, optimization_level=3)\nprint('gates = ', optimized_3.count_ops())\nprint('depth = ', optimized_3.depth())\n```\n\n gates = OrderedDict([('cx', 54), ('u3', 28), ('barrier', 5), ('measure', 3), ('u2', 2)])\n depth = 72\n\n\n### Run on a real device\n\nWe are now ready to run on a real device and will use the device Vigo for this experience.\n\n\n```python\n#my_provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')\n\nmy_provider = IBMQ.get_provider(hub='ibm-q-community', group='hackathon', project='nrc-ws-2020')\n\nbackend_real=my_provider.get_backend('ibmq_rome')\njob_real = execute(qc1, backend_real,shots=4096)\nresult_real = job_real.result()\ncounts = result_real.get_counts(qc1)\nprint(counts)\nplot_histogram(counts)\n```\n\nAs we can see the result is not really what we were expecting so we increase the number of shots to the maximum the device can handle (8192).\n\n\n\n```python\nmy_provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')\nbackend_real=my_provider.get_backend('ibmq_rome')\njob_real = execute(qc1, backend_real,shots=8192)\nresult_real = job_real.result()\ncounts = result_real.get_counts(qc1)\nprint(counts)\nplot_histogram(counts)\n```\n\n\n```python\nbackend_sim = Aer.get_backend('qasm_simulator')\njob_sim = execute(qc1, backend_sim,shots=4096)\nresult_sim = job_sim.result()\ncounts = result_sim.get_counts(qc1)\nprint(counts)\nplot_histogram(counts)\n```\n\n## Compression\n\nAs the images we would like to encode are growing in size and given the depth of the circuits we will have to run, it is quite obvious that whatever we can do in order to reduce the complexity of the circuit (depth and number of $CNOT$ gates) will make a great difference.\n\nCompression can be achieved byy grouping pixels with the same intensity. What makes them distincts is the binary string used to encode the position, but they share the same angle for the associated controlled rotation. Let's consider for exemple the following image:\n\n \n\nThe blue pixels are at positions are $\\ket{0}, \\ket{8}, \\ket{16}, \\ket{24}, \\ket{32}, \\ket{40}, \\ket{48}$ and $\\ket{56}$. \n\\\nTheir respective binary representation and boolean expressions are:\n\n\\begin{array}{|c|c|c|}\n\\hline\nposition & binary \\; string & boolean \\; expression \\\\\n\\hline\n\\ket{0} &\\ket{000000} & \\overline{x_{5}}\\overline{x_{4}}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{8} &\\ket{001000} & \\overline{x_{5}}\\overline{x_{4}}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{16} &\\ket{001000} & \\overline{x_{5}}x_{4}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{24} &\\ket{011000} & \\overline{x_{5}}x_{4}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{32} &\\ket{100000} & x_{5}\\overline{x_{4}}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{40} &\\ket{101000} & x_{5}\\overline{x_{4}}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{48} &\\ket{110000} & x_{5}x_{4}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\ket{56} &\\ket{111000} & x_{5}x_{4}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} \\\\\n\\hline\n\\end{array}\n\nThe boolean expression we would like to simplify/minimize is then :\n\n$exp = \\overline{x_{5}}\\overline{x_{4}}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+\\overline{x_{5}}\\overline{x_{4}}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+\\overline{x_{5}}x_{4}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+\\overline{x_{5}}x_{4}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{5}\\overline{x_{4}}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{5}\\overline{x_{4}}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{5}x_{4}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{5}x_{4}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}$\n\n\\begin{align*}\nexp&=(\\overline{x_{5}}+x_{5})(\\overline{x_{4}}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}} +\\overline{x_{4}}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{4}\\overline{x_{3}}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}+x_{4}x_{3}\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}})\\\\\n &=\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}(\\overline{x_{4}}\\overline{x_{3}}+\\overline{x_{4}}x_{3}+x_{4}\\overline{x_{3}}+x_{4}x_{3})\\\\\n &=\\overline{x_{2}}\\overline{x_{1}}\\overline{x_{0}}\n\\end{align*}\n\nWe can then not only group the pixels under one conditional rotation, but we also see that the conditions for the controlled gate also have been reduced, which will result in a reduction of single gates needed for implementation. \n\n\n```python\nimport qiskit.tools.jupyter\n%qiskit_version_table\n```\n\n\n

Version Information

Qiskit SoftwareVersion
Qiskit0.19.2
Terra0.14.1
Aer0.5.1
Ignis0.3.0
Aqua0.7.1
IBM Q Provider0.7.1
System information
Python3.7.6 | packaged by conda-forge | (default, Mar 23 2020, 22:45:16) \n[Clang 9.0.1 ]
OSDarwin
CPUs6
Memory (Gb)16.0
Thu Jun 25 00:27:22 2020 EDT
\n\n\n\n```python\nprovider.backends()\n```\n\n\n\n\n [,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ]\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "165b2b1bcf8822da43fbeba6d4173c4026635701", "size": 333051, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/ch-applications/Flexible Representation of Quantum Images - FRQI.ipynb", "max_stars_repo_name": "mbozzore/qiskit-textbook", "max_stars_repo_head_hexsha": "9af7e484e15cf52e60281d789b1cbbdad5313c35", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T12:15:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T12:15:44.000Z", "max_issues_repo_path": "content/ch-applications/Flexible Representation of Quantum Images - FRQI.ipynb", "max_issues_repo_name": "robertloredo/qiskit-textbook", "max_issues_repo_head_hexsha": "e3e7f30a80a4e961fbda3f189ead0ebacbb6d84c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/ch-applications/Flexible Representation of Quantum Images - FRQI.ipynb", "max_forks_repo_name": "robertloredo/qiskit-textbook", "max_forks_repo_head_hexsha": "e3e7f30a80a4e961fbda3f189ead0ebacbb6d84c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 347.6524008351, "max_line_length": 89988, "alphanum_fraction": 0.9276567252, "converted": true, "num_tokens": 6026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1574732084666787}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2_log__]\n >Metropolis: [lambda_1_log__]\n Could not pickle model, sampling singlethreaded.\n Sequential sampling (4 chains in 1 job)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2_log__]\n >Metropolis: [lambda_1_log__]\n 100%|██████████| 15000/15000 [00:07<00:00, 2062.26it/s]\n 100%|██████████| 15000/15000 [00:06<00:00, 2240.08it/s]\n 100%|██████████| 15000/15000 [00:06<00:00, 2216.32it/s]\n 100%|██████████| 15000/15000 [00:06<00:00, 2247.26it/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nlambda_1_mean = lambda_1_samples.mean()\nlambda_2_mean = lambda_2_samples.mean()\n\nprint(\"lambda_1 mean: {:.2f} \\nlambda_2 mean: {:.2f}\".format(lambda_1_mean, lambda_2_mean))\n```\n\n lambda_1 mean: 17.75 \n lambda_2 mean: 22.72\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\nfractional_increases = lambda_1_samples/lambda_2_samples\n\nprint(\"Expected percent increase: {:.1f}%\".format(fractional_increases.mean() * 100))\n```\n\n Expected percent increase: 78.3%\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nnew_lambda_1 = np.mean(lambda_1_samples[tau_samples < 45])\n\nprint(\"New lambda_1 mean: {:.2f}\".format(new_lambda_1))\n```\n\n New lambda_1 mean: 17.75\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "db1a2f1ebe2a4a545c8c9b9c4bb105027688827d", "size": 300419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "rayheberer/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "f3774c40717bbb4cf94ecebe9056f28a259ad8c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "rayheberer/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "f3774c40717bbb4cf94ecebe9056f28a259ad8c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "rayheberer/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "f3774c40717bbb4cf94ecebe9056f28a259ad8c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-09-05T23:21:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T23:21:27.000Z", "avg_line_length": 268.4709562109, "max_line_length": 89976, "alphanum_fraction": 0.8985383747, "converted": true, "num_tokens": 11751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.1574376320165406}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n# Loading setting from file\n\nimport matplotlib\nimport json\n\ns = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\nmatplotlib.rcParams.update(s)\n```\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n Sampling 4 chains, 0 divergences: 100%|██████████| 60000/60000 [00:09<00:00, 6045.13draws/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\n# from IPython.core.display import HTML\n# def css_styling():\n# styles = open(\"../styles/custom.css\", \"r\").read()\n# return HTML(styles)\n# css_styling()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "e6a33514c8bcd9fed910f53ad21926070449f851", "size": 318189, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "pcallec/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "43335483f992ebb7fb5410a0c3ee785828d5b77f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "pcallec/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "43335483f992ebb7fb5410a0c3ee785828d5b77f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "pcallec/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "43335483f992ebb7fb5410a0c3ee785828d5b77f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 303.6154580153, "max_line_length": 90796, "alphanum_fraction": 0.9088434861, "converted": true, "num_tokens": 10944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.15705316988397539}} {"text": "# Testing numerical methods\n\n\n```python\nfrom IPython.core.display import HTML\ncss_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'\nHTML(url=css_file)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nBack in October, Greg Wilson [blogged about testing scientific software](http://software-carpentry.org/blog/2014/10/why-we-dont-teach-testing.html). He specifically points to [a lesson introducing the Euler method](http://nbviewer.ipython.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb) as part of the [Practical Numerical Methods with Python MOOC](http://openedx.seas.gwu.edu/courses/GW/MAE6286/2014_fall/about), and asks why a certain number (the measured convergence rate) is *close enough* to the expected value.\n\nThe big question of testing in scientific software, how this should be done, and how it is being done, has led to the [*Close Enough for Scientific Work*](https://github.com/swcarpentry/close-enough-for-scientific-work) project, as launched and explained by Greg Wilson in [this blog post](http://software-carpentry.org/blog/2014/11/close-enough-for-scientific-work.html). If you're reading this, you should be following that project! As I've helped out on the MOOC, which is led by [Lorena Barba](http://lorenabarba.com/), I've been (over)thinking what sort of answer we could, or should, give. Well aware that we're heading for the [academic version of the balloon joke](https://www2.bc.edu/~radinr/Management_Humor/jokes.htm) (an answer that is correct, of little use, and took a long time to arrive), let's begin...\n\n## Background\n\n$$\n\\newcommand{\\dt}{\\Delta t}\n\\newcommand{\\udt}[1]{u^{({#1})}(T)}\n$$\n\nWe have a system of differential equations to solve: the solution will be $u(t)$. The numerical solution we get will depend on one parameter, the timestep $\\dt$. The resulting numerical approximation, at the point $t=T$, will be $\\udt{\\dt}$: the exact solution is $u(T)$. \n\nThe method used is Euler's method, also [introduced in an earlier lesson in the MOOC](http://nbviewer.ipython.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_02_Phugoid_Oscillation.ipynb), and [explained in detail by Lorena in this screencast](https://www.youtube.com/watch?v=6i6qhqDCViA). The key result derived there is that Euler's method is *first order*, so that\n\n$$\n\\begin{equation}\n u(T) - \\udt{\\dt} = c_1 \\dt + c_2 \\dt^2 + {\\cal O}(\\dt^3) \\simeq c_1 \\dt.\n\\end{equation}\n$$\n\nFor sufficiently small $\\dt$ the error is proportional to $\\dt$.\n\nAs we can't (usually) know the exact solution $u(T)$ ahead of time, a standard check is *grid convergence*: compute three solutions with different timesteps (eg, $\\dt, 2\\dt, 4\\dt$) and compare them. The comparison to use is\n\n$$\n\\begin{equation}\n s_m = \\log_2 \\left( \\frac{\\udt{4\\dt} - \\udt{2\\dt}}{\\udt{2\\dt} - \\udt{\\dt}} \\right) \\simeq 1.\n\\end{equation}\n$$\n\nThe symbol $s_m$ is used as it's the *(measured) slope* of the best fit line through the errors, as shown on the [original lesson](http://nbviewer.ipython.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb):\n\n\n####Figure 1. Convergence test plot taken from the original lesson.\n\nThe [original lesson](http://nbviewer.ipython.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb) does precisely this comparison (using the phugoid model, with specific parameter values, and $\\dt = 0.001$), finding a measured slope $s_m = 1.014$. Is this *close enough* to 1?\n\n## TL;DR: Answer\n\nAnswer**s**\n\n1. [*I don't care about the algorithm: I just want the answer to be right*](http://nbviewer.ipython.org/github/IanHawke/close-enough-balloons/blob/master/01-Close-Enough-Errorbars.ipynb): $0.585 \\lesssim s_m \\lesssim 1.585$ is close enough for Euler's method.\n2. [*I don't care about the answer: I just want the algorithm behaviour to be right*](http://nbviewer.ipython.org/github/IanHawke/close-enough-balloons/blob/master/02-Close-Enough-Slopes.ipynb): $s_m=1.014$ with $\\dt=0.001$ is close enough if $1 \\le s_m \\le 1.0093$ with $\\dt=0.0005$.\n3. [*I don't care about the behaviour: I just want to know I've implemented Euler's method*](http://nbviewer.ipython.org/github/IanHawke/close-enough-balloons/blob/master/03-Close-Enough-Just-Euler.ipynb): measure the local truncation error instead, and check *both* the convergence rate *and* the leading order constant. $s_m$ by itself is useless.\n", "meta": {"hexsha": "38229df452a8f92c33ff827088c9a0630bd35b13", "size": 11835, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "00-Close-Enough-Post-Overall.ipynb", "max_stars_repo_name": "IanHawke/close-enough-balloons", "max_stars_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-03-10T23:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-01T23:53:24.000Z", "max_issues_repo_path": "00-Close-Enough-Post-Overall.ipynb", "max_issues_repo_name": "IanHawke/close-enough-balloons", "max_issues_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "00-Close-Enough-Post-Overall.ipynb", "max_forks_repo_name": "IanHawke/close-enough-balloons", "max_forks_repo_head_hexsha": "6b7c27d90e8c012b1f95c2daa4ff2e84849a2c52", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3811188811, "max_line_length": 825, "alphanum_fraction": 0.5479509928, "converted": true, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606815201671963, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.15686998668881053}} {"text": "## Manningの粗度係数を再考する\n\n### Manningの公式の概要\n\nManningの公式は、Robert Manningによって提案された横断面内で平均化された流速$V$を示す実験公式であり、次式のように示される。\n\n$$\n\\begin{align}\n V = \\dfrac{1}{n}i_e^{1/2}R^{2/3}\n\\end{align} \n$$\nここで、$n$:Manningの粗度係数($m^{-1/3} \\cdot s$)、$i_e$:エネルギー勾配、$R$:径深(m)である。\n\n本式は現在世界で最も使われている平均流速公式である。\n\n上式の実験定数はManningの粗度係数のみであるが次元を有しており定数として適切でない。\nそれにもかかわらず、式形が非常に単純なため、実験水路から実河川まで様々な条件下での豊富な観測資料を元にManningの粗度係数は整理されている。そのため、容易に概略値を把握することが可能である。\n\n例えば、Chowの「OPEN-CHANNEL HYDRAULICS」では水路条件を100種類以上に分類し、Manningの粗度係数を一般値を示している。[^1]\n\n日本では「水理公式集(平成11年版)」[^2]や「河川砂防技術基準(案)同解説調査編」[^3]に次表のようにまとめられている。\n\n\n[^1]: Chow,V.,T.: Open-channel hydraulics, pp.110-113, McGraw-Hill, 1959.\n\n[^2]: 土木学会水理委員会水理公式集改訂小委員会 : 水理公式集, p.89, 土木学会, 1999.\n\n[^3]: 建設省河川局,日本河川協会 : 建設省河川砂防技術基準(案)同解説調査編, p.133, 技報堂出版, 1997.\n\n - 「水理公式集(平成11年版)」\n\n
\n\n
\n\n - 「河川砂防技術基準(案)同解説調査編」\n \n
\n\n
\n\n\n### Manningの公式への水理学的な意味付け\n\n流速係数$\\phi=V/u_*$をManningの公式を用いて整理すると次式となる。\n$$\n\\begin{align}\n\\phi &= \\frac{V}{u_*} = \\frac{k_s^{1/6}}{n \\sqrt{g}} \\left(\\frac{R}{k_s} \\right)^{1/6} \\nonumber \n\\end{align}\n$$\nここに$k_s$:相当粗度(m)である。\n一方開水路完全粗面の対数則による流速係数は次式となる。\n\n$$\n\\begin{align}\n\\phi &= \\frac{1}{\\kappa}\\log_e{\\frac{h}{k}} - \\frac{1}{\\kappa} + C \n\\end{align}\n$$\n\n両式より、$\\phi$と$k_s^{1/6}/(n \\sqrt{g})$の関係を整理したものが次図の点線である。\n\n
\n\n
\n図 Manning・Stricklerの式と粗面対数則との比較[^4]\n\n管路や開水路では流速係数$\\phi$は8~25程度であるため、$k_s^{1/6}/(n \\sqrt{g})$は図中直線の一定値に近似できる。\nこれより、流速係数は以下のように近似できる。\n\n$$\n\\begin{align}\n\\frac{k_s^{1/6}}{n \\sqrt{g}} & \\sim 7.66 \\nonumber \\\\\n\\phi &= \\frac{V}{u_*} = 7.66 \\left(\\frac{R}{k_s} \\right)^{1/6} \n\\end{align}\n$$\n\nこれはManning・Stricklerの公式と呼ばれる。\n上記のように近似できることは実用上は径深によってManningの粗度係数が変わらないことを示している。 \n今日では本式を使用することは少ないが、Manningの公式に水理学的な意味を与えた点で重要である。\n\n[^4]: 椿東一郎 : 水理学I, p.110, 森北出版, 1973.\n\n### 沖積河川の河床抵抗\n\n多くの沖積河川では河床上に河床波(小規模河床形態)が形成されている。河床波とは砂漣、砂堆、反砂堆等の水深スケールの河床形状を示して、日本土木学会水理委員会によると次表のように分類される。[^5]\nまた、Simonsはより詳細な分類を示している。[^6]\n\n
\n\n
\n\n河床波(ここでは砂堆)上の流れを模式的に示すと下図のとおりである。[^7]\n\n
\n\n
\n\nここで、(水深平均)流れに対する河床が与える抵抗を考えると「摩擦抵抗」と「剥離に伴う形状抵抗」に分類できる。\nManningの公式のような平均流速公式ではこの両者の影響が混ざって含まれることになる。\n\n「摩擦抵抗」は河床材料によって決定するため対数則によって評価する。一方、「剥離に伴う形状抵抗」は河床波の形状を考慮して急拡損失の考え方により評価する。\nここで河床波の形状が問題となる。模型実験では二次元水路を使用することにより河床波の形状を計測することは比較的容易であるが、実河川では難しく、近年の研究で高解像度のセンサーを用いた実河川の河床波の計測事例が報告されている[^8]が、まだ一般的とは言えず、実河川の河床波形状を計測すること難しい。\n\n\n
\n\n
\n\nさらに、実河川の流れは非定常にであり、流れの規模によって河床波の形状が変化する。このような実河川における出水中の河床波の変化を計測事例はほとんど報告されておらず[^9],[^10]、実態は不明である。\n\n
\n\n
\n\n
\n\n
\n\nこれらより実河川の河床抵抗を厳密に推定することは難しいことが理解できる。そのため、Manningの公式が積極的に代用されている。前項にはManningの粗度係数は水深によってほとんど変化しないと示したが、これは河床波形状が変化しない条件で成立し、変化する場合には形状抵抗による損失が変化するため、Manningの粗度係数も変化する。\n\nなお、Manningの粗度係数は一定値として取り扱うことが一般的である。観測資料が十分でなく、大規模出水時に観測データから同定された値を使うためである。\n\n[^5]: 水理委員会移動床流れの抵抗と河床形状研究小委員会 : 移動床流れにおける河床形態と粗度, 土木学会論文報告集第210号, pp.65-91, 1973.\n\n[^6]: Simons,D.B.,Şentürk, F. : Sediment Transport Technology, Water Resources Publications, 1977.\n\n[^7]: 芦田和男,江頭進治,中川一 : 21世紀の河川学:安全で自然豊かな河川を目指して, p.121, 京都大学学術出版会, 2008.\n\n[^8]: 例えば、秋田麗子,西口亮太,野間口芳希 : 水中の河床地形の面的計測とその活用方策について, 河川技術論文集, 第23巻, pp.173-178, 2017.\n\n[^9]: 高部一彦,人見寿,坂野章,山本浩一 : 涸沼川における河床波観測及び解析, 河川技術論文集, 第11巻, pp.387-392, 2005.\n\n[^10]: 末次忠司, 日下部隆昭, 坊野聡子 : 土砂管理施策のためのキーノート, 国土技術政策総合研究所資料, No.231, 2005.\n\n### 河床波の変化を考慮した河床抵抗の評価方法\n\n前項のとおり、実河川での検証が難しいため、模型実験結果を元に河床抵抗の評価を行う。\n\nEngelund[^11]は河床抵抗を以下のようにモデル化した。\n\n$$\n\\begin{align}\n \\tau_* = \\tau_*^{\\prime} + \\tau_*^{\\prime\\prime}\n\\end{align} \n$$\n\nここで、$\\tau_*$:全無次元掃流力、$\\tau_*^{\\prime}$:摩擦抵抗による無次元掃流力(=無次元有効掃流力)、 $\\tau_*^{\\prime\\prime}$:形状抵抗による無次元掃流力である。\n\n相似則より$\\tau_*$は$\\tau_*^{\\prime}$のみの関数であることを示した。これより実験結果を使用して次図[^12]の関係式を示した。\n\n\n
\n\n
\n\n\nさらに、岸・黒木[^5]はEngelundの相似則を修正し、$\\tau_*$は$\\tau_*^{\\prime}$,$R/d$の関数となることを示し、次図[^12]の関係を示した。\n\n\n
\n\n
\n\n\n\n現時点ではこれが最も有用な研究成果と考えられる。\n\n参考までにEngelundと岸・黒木の研究成果を比較する。両者による無次元掃流力-有効無次元掃流力の図を重ね合わせると次図のとおりである。なお、岸・黒木の図は$R/d$が1000、500、100の3ケースを示す。\n\n\n
\n\n
\n\n両者を比較するとdune領域、flat-bed・antidune領域ではそれほど大きな差異はないが、transition領域の取り扱いが異なっている。\nEngelundはtransition領域の変化が不明なため定式化していないが、岸・黒木は定式化しており、この領域の取り扱いが$R/d$によって異なっている。\nよって、transition領域の影響を考慮するためには岸・黒木の方法を使う他はない。\n\n\n河床波の変化による流れ場への影響を理解しやすくするため、岸・黒木の図を$\\phi$と$\\tau_*$の関係に変換した図[^12]を以下に示す。\n\n
\n\n
\n\n縦軸の$\\phi=V/u_*$は流れやすさを示すため、transition領域で急激に流れやすくなる、つまり、河床抵抗が減少することが理解できる。\n\n[^11]: Engelund F. : Hydraulic Resistance of Alluvial Streams, Journal of the Hydraulics Division, Vol. 92, Issue 2, pp.315-326, 1966. \n\n[^12]: 河村三郎 : 土砂水理学, pp.226-230, 森北出版, 1982.\n\n### 岸・黒木の方法による河床抵抗の評価\n\n岸・黒木の方法による河床抵抗の評価の計算方法について示す。\n次図(再記)の各領域区分の無次元掃流力$\\tau_*$と有効無次元掃流力$\\tau_*^{\\prime}$の関係式は以下のとおりとなっている。\n\n
\n\n
\n\n\n$$\n\\begin{align}\n\\rm{dune1} : \\tau_*^{\\prime} &= 0.21\\tau_*^{1/2} \\\\\n\\rm{dune2} : \\tau_*^{\\prime} &= 1.49(R/d)^{-1/4}\\tau_* \\\\\n\\rm{flat\\text{-}bed} : \\tau_*^{\\prime} &= \\tau_* \\\\\n\\rm{antidune} : \\tau_*^{\\prime} &= 0.264(R/d)^{1/5}\\tau_*^{1/2} \\\\\n\\rm{transition1} : \\tau_*^{\\prime} &= 6.5 \\times 10^7(R/d)^{-5/2} \\tau_*^{11/2}\n\\end{align}\n$$\n\n\nまた、dune領域とtransition領域、flat-bed領域とantidune領域の区分は次式となる。\n\n\n$$\n\\begin{align}\n\\rm{dune \\text{ -- } transition} : \\tau_* &= 0.02(R/d)^{1/2} \\\\\n\\rm{flat\\text{-}bed \\text{ -- } antidune} : \\tau_* &= 0.07(R/d)^{2/5} \n\\end{align}\n$$\n\n\n上図中のtransition2領域は関係式が設定されていない。transition2はdune2とantiduneを直線で繋いでおり、dune領域の上限値を示している。\ntransition領域では複雑な変化を示すため定式化は難しいが、岸・黒木の方法より、dune1 -- transition1 -- flat-bed -- antiduneの過程で遷移する(図中赤線)ものと考える。\nなお、antiduneは射流場のみで発生するため、ほとんど沖積河川の場合、flat-bedまでの変化を考慮すれば良い。\n\n### 岸・黒木の方法の課題\n\n#### 河床波の遷移の履歴\n\nここまでに示した考え方は基本的に定常、等流、平衡を前提に構築されている。\nまた、模型実験のデータを基に関数をフィッティングしている。\n\n実河川の適用性は、Engelund[^11]はRio Grande川での観測データと一致することを示しており、岸・黒木[^5]も同じデータを用いて妥当性を示している。\nしかし、岸・黒木は石狩川の観測データとの比較により水理量と河床形状の関係が常に平衡にはならずに履歴の影響を受けること示しており、手法の適用上の課題を指摘している。\n\n今後はより多くの河川で観測を実施して手法の適用性を検証する必要がある。\n\n#### 河床波の形状抵抗の直接評価\n\nEngelundおよび岸・黒木の方法は、相似を仮定して無次元掃流力と有効無次元掃流力の関係を用いて河床波の影響を評価しているが、河床波の形状損失を直接評価する方が理想的である。\n\nこの方法は、これまでの研究では一次元流れを仮定した急拡損失による評価が行われてきたが、乱流モデルを用いた鉛直二次元または三次元解析によって評価する必要がある。\nまた、現時点では実河川による検証データの取得が難しいため、模型実験を基本に検証を進めることが望ましい。\n\n### 参考:流砂量評価における有効掃流力\n\n掃流力は流れにとっては抵抗になるが河床土砂にとっては駆動力となる。その力は全抵抗から形状抵抗を差し引いた有効掃流力である。\nそのため、河床波の遷移は掃流砂量にも大きな影響を与える。\n\n日本で最も使用される芦田・道上の掃流砂量式には有効掃流力が含まれている。これはdune上の流れを想定していることを意味しており、本来であれば、河床波形状に応じてこの式形を変更する必要がある。\n\nまた、使用頻度は低いが、佐藤・吉川・芦田の式(土研公式)ではManningの粗度係数によって式形を変更している。これは、河床波形状の影響を示しているが、河床波形状はManningの粗度係数のみでは決定しないため、使用の際には注意が必要である。\n\n---\n\n## bibtex\n\n\n```python\nfrom pybtex.database.input import bibtex\n\nparser = bibtex.Parser()\nbib_data = parser.parse_file(\"refs.bib\")\n```\n\n### book\n\n\n```python\nkey = 'komura1982'\nline = ''\nts = bib_data.entries[key]\ns = bib_data.entries[key].persons['author']\n\nfor ss in s:\n for sl in ss.last_names:\n line += sl + ','\n \n for sl in ss.first_names:\n line += sl + ','\n \nline += \":\"\n\nline += ts.fields['title'] \\\n+ \", pp.\" + ts.fields['pages'] \\\n+ \", \" + ts.fields['publisher'] \\\n+ \", \" + ts.fields['year'] + \".\"\n```\n\n### jarnal\n\n\n```python\nkey = 'jsce1973'\nline = ''\nts = bib_data.entries[key]\ns = bib_data.entries[key].persons['author']\n\nfor ss in s:\n for sl in ss.last_names:\n line += sl + ','\n \n for sl in ss.first_names:\n line += sl + ','\n \nline += \":\"\n\nline += ts.fields['title'] \\\n+ \", \" + ts.fields['journal'] \\\n+ \", \" + ts.fields['number'] \\\n+ \", pp.\" + ts.fields['pages'] \\\n+ \", \" + ts.fields['year'] + \".\"\n```\n\n\n```python\nline\n```\n\n\n\n\n '河村,三郎,:土砂水理学, pp.226, 森北出版, 1982.'\n\n\n\n\n```python\n\n```\n\n## graph\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport holoviews as hv\nimport seaborn as sns\nfrom matplotlib import rcParams\n```\n\n\n```python\n# backend = 'bokeh' \nbackend = 'matplotlib'\n\nif backend == 'matplotlib':\n sns.set(context='notebook', font_scale=1.0, style=\"whitegrid\", palette=\"bright\")\n rcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'VL PGothic', 'Noto Sans CJK JP']\n\nhv.extension(backend) \n\nlw = 'line_width' if backend == 'bokeh' else 'linewidth'\nlstyle = 'line_dash' if backend == 'bokeh' else 'linestyle'\n\nlw1 = {lw:3}\nlw2 = {lw:1}\nlsdot = {lstyle:'dotted'}\nlsdash = {lstyle:'dashed'}\ngrd = {'show_grid':True}\n```\n\n\n\n\n\n\n\n
\n\n\n\n\n\n \n\n\n\n
\n\n\n\n\n\n\n```python\n\n```\n\n\n```python\ndf = pd.read_csv('https://computational-sediment-hyd.github.io/HydraulicsTips-in-CivilEngineer/data/Engelund.csv', header=None)\ndf.columns = ['x','y']\n```\n\n\n```python\ntaus1 = np.logspace(-1,0.2,num=20,endpoint=True,base=10.0)\ntaus2 = np.logspace(-0.5,0.4,num=20,endpoint=True,base=10.0)\n\ngEng = hv.Curve((df.x,df.y), label='Engelund').options(color='k', **lw1, **grd) \\\n*hv.Curve((0.06+0.4*taus1**2,taus1), label='Engelund').options(color='k', **lw1, **grd) \ngo1 = hv.Curve((0.4*taus1**2,taus1), label='$\\\\tau_{*}^{\\prime}=0.4\\\\tau_*^2$').options(color='k', **lsdot, **grd)\ngo2 = hv.Curve((taus2,taus2), label='$\\\\tau_{*}^{\\prime}=\\\\tau_*$').options(color='k', **lsdash, **grd)\n```\n\n\n```python\ndef kishikuroki1(taus, Rbyd):\n \n if taus < 0.02*(Rbyd)**0.5:\n tausd = 0.21*taus**0.5\n elif taus < 0.07*(Rbyd)**0.4:\n tausd = 1.49*(Rbyd)**(-0.25)*taus\n else:\n tausd = 0.264*(Rbyd)**0.2*taus**0.5\n \n return tausd\n\ndef kishikuroki2(taus, Rbyd):\n \n if taus < 0.02*(Rbyd)**0.5:\n tausd = 0.21*taus**0.5\n elif taus < 0.07*(Rbyd)**0.4:\n tausd = 6.5*10**7*(Rbyd)**(-2.5)*taus**5.5 \n tausd = tausd if tausd < taus else taus\n else:\n tausd = 0.264*(Rbyd)**0.2*taus**0.5\n \n return tausd\n```\n\n\n```python\ndef mkfig(Rbyd, color):\n taus = np.arange(0.05,5.01,0.01)\n tausd1 = [ kishikuroki1(tt, Rbyd) for tt in taus ]\n tausd2 = [ kishikuroki2(tt, Rbyd) for tt in taus ]\n \n g = hv.Curve((tausd1, taus)).options(color=color, **grd) * hv.Curve((tausd2, taus),label='Kishi-Kuroki, R/d='+str(Rbyd)).options(color=color, **grd)\n \n return g\n```\n\n\n```python\ngkk = (mkfig(1000,'r')*mkfig(500,'b')*mkfig(100,'g'))\n```\n\n\n```python\ngl = (gkk*gEng*go1*go2).options(logx=True, logy=True, legend_position='top_left'\n , xlabel='dimensionless effective shear stress $\\\\tau_{*}^{\\prime}$', ylabel='dimensionless shear stress $\\\\tau_*$').redim.range(x=(0.01,10), y=(0.1,10))\n\ngl = gl.options(aspect=1.5, fig_size=200, **grd)\ngl\n```\n\n\n\n\n
\n\n\n\n\n```python\nhv.save(gl,'engelund_add_kishikuroki.svg')\n```\n\n\n```python\n\n```\n\n\n```python\ngl = (g*gkk).options(width=500,height=400, logx=True, logy=True, legend_position='top_left'\n , xlabel='dimensionless effective shear stress τ*d', ylabel='dimensionless shear stress τ*').redim.range(x=(0.01,10), y=(0.1,10))\ngl\n```\n\n\n\n\n
\n\n\n\n\n\n
\n
\n\n\n\n", "meta": {"hexsha": "ad6dd2a550217ff50d6cff3fa821b2af528581e6", "size": 223000, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reconsiderManningCoef.ipynb", "max_stars_repo_name": "computational-sediment-hyd/HydraulicsTips-in-CivilEngineer", "max_stars_repo_head_hexsha": "c596c85a5e0f59c0afa2bf76043e3069ba19c2f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reconsiderManningCoef.ipynb", "max_issues_repo_name": "computational-sediment-hyd/HydraulicsTips-in-CivilEngineer", "max_issues_repo_head_hexsha": "c596c85a5e0f59c0afa2bf76043e3069ba19c2f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reconsiderManningCoef.ipynb", "max_forks_repo_name": "computational-sediment-hyd/HydraulicsTips-in-CivilEngineer", "max_forks_repo_head_hexsha": "c596c85a5e0f59c0afa2bf76043e3069ba19c2f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 120.3453858608, "max_line_length": 85524, "alphanum_fraction": 0.7327488789, "converted": true, "num_tokens": 7556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754065479083276, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.1566411819140729}} {"text": "\n# PHY321 Classical Mechanics 1\n\n \n**Final project, due Friday April 30**, midnight (1159pm)\n\nDate: **Apr 22, 2021**\n\n## Practicalities about homeworks and projects\n\n1. You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. **Remember to write your name(s)**!\n\n2. How do I(we) hand in? Due to the extraordinary situation we are in now, the final projec should be handed in fully via D2L. You can scan your handwritten notes and upload to D2L or you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical part should always be handed in as a jupyter notebook.\n\n### Introduction to the final project, total score: 150 points\n\nThe relevant reading background is\n1. chapters 2-8 and 14 of Taylor\n\n2. lecture notes throughout the semester and previous homework and midterm projects.\n\nThe final project aims at covering most of the topics we have\ndiscussed during the semester. You should feel free to use either\npaper and pencil and/or symbolic software (sympy, Mathematica or\nsimilar) for the non-computational exercises.\n\n\n### Exercise 1, Two-body Problems and Conservative Forces (total 90pt)\n\nThe relevant material from Taylor are chapters 4 and 8. Homework sets 6-9 and the chapters on [forces](https://mhjensen.github.io/Physics321/doc/LectureNotes/_build/html/chapter4.html) and [two-body problems](https://mhjensen.github.io/Physics321/doc/LectureNotes/_build/html/chapter6.html) from the lecture notes may also be of use. \n\nThis exercise is a follow-up of hw6. There we studied the so-called\nLennard-Jones potential which is widely used in molecular dynamics\ncalculations. This potential is based on parametrizations from\nexpertiments. In molecular dynamics calculations the assumption is\nthat atoms move according to the laws of Newton, given the correct\nmodel for interactions. We can say then that quantum-mechanical\ndegrees of freedom stemming from the interactions between electrons\nand protons in an atom, are parametrized in terms of an effective\npotential.\n\nWe will limit ourselves to a two-body problem.\n\nThe goal of this exercise is to model a gas of argon atoms (here two\natoms only interacting), where the atoms interact according to the\nfamous Lennard-Jones potential,\n\n\n
\n\n$$\n\\begin{equation}\n V(r) = 4\\varepsilon\\left((\\frac{\\sigma}{r})^{12} - (\\frac{\\sigma}{r})^6\\right), \\label{eq:lj} \\tag{1}\n\\end{equation}\n$$\n\nwhere $r$ is the distance between two atoms,\n$r=\\vert\\boldsymbol{r}_i-\\boldsymbol{r}_j\\vert$, that is the norm of the relative\ndistance vector $\\boldsymbol{r}$. The quantities $\\sigma$ and $\\varepsilon$ are\nparameters which determine which chemical compound is modelled. This\npotential is a good approximation for noble gases like helium, neon, argon and other.\n\nWe start first with a basic study of the potential\n\n* **1a (5pt):** Plot the potential as a function of $r$ with $\\varepsilon=1$ and $\\sigma=1$, for example for $r \\in [0.9,3]$.\n\n* **1b (5pt):** The behaviour of $V(r)$ is vastly different for $r < \\sigma$ and $r > \\sigma$. Which term in the potential, ([1](#eq:lj)), dominates in each case and what is the effect?\n\n* **1c (5pt):** Find and characterise the equilibrium points of the potential.\n\n* **1d (5pt):** Describe qualitatively the motion of two atoms which start at rest separated by a distance of ${1.5}\\sigma$. What if they start with a separation of ${0.95}\\sigma$? (Hint: use the graph of the potential.)\n\n* **1e (5pt):** Describe the shape of the potential close to the stable equilibrium point. Can you think of other force(s) with the same behaviour?\n\nThen we switch our attention to the equations of motion.\n\n* **1f (5pt):** Find the force on atom $i$ at position $\\boldsymbol{r}_i$ from atom $j$ at position $\\boldsymbol{r}_j$.\n\n* **1g (5pt):** Is this a conservative force? Show that the **curl** is zero.\n\n* **1h (5pt):** Are linear and angular momentum conserved? You need to show this by calculating the relevant quantities.\n\n* **1i (5pt):** Show that the equation of motion for atom $i$ is\n\n$$\n\\frac{d^2\\boldsymbol{r}_i}{dt^2} = \\frac{24\\varepsilon}{m} \\sum_{j \\neq i} \\left(2(\\frac{\\sigma}{\\vert\\boldsymbol{r}_i-\\boldsymbol{r}_j}\\vert)^{12}-(\\frac{\\sigma}{\\vert\\boldsymbol{r}_i-\\boldsymbol{r}_j}\\vert)^6\\right)\\frac{\\boldsymbol{r}_i-\\boldsymbol{r}_j}{\\vert\\boldsymbol{r}_i-\\boldsymbol{r}_j\\vert^2}.\n$$\n\nNumerical accuracy is reduced when computing with values which are\nmany orders of magnitude apart. This is often an issue in physics, and\nmolecular dynamics is no exception. For example, the mass of argon is\nsmaller than 10E-25kg, while typical length scales are\non the order of nanometers, 10E-9m.\n\nThe remedy is to change units so that most quantities are close to\n$1$. From ([1](#eq:lj)) it is clear that $\\sigma$ and $\\varepsilon$\nare the typical scales for length and energy.\n\n* **1j (5pt):** Introduce the scaled coordinates $\\boldsymbol{r}_i\\,'=\\boldsymbol{r}_i/\\sigma$ and show that the equation of motion can be rewritten in terms of these coordinates as (where $t'=t/\\tau$ for a suitable choice of $\\tau$.)\n\n\n
\n\n$$\n\\begin{equation}\n\\frac{d^2\\boldsymbol{r}_i\\,'}{{dt'^2}} = 24 \\sum_{j \\neq i} \\left(2\\vert\\boldsymbol{r}_i\\,'-\\boldsymbol{r}_j\\,'\\vert^{-12}-\\vert\\boldsymbol{r}_i\\,'-\\boldsymbol{r}_j\\,\\vert^{-6}\\right)\\frac{\\boldsymbol{r}_i\\,'-\\boldsymbol{r}_j\\,'}{\\vert\\boldsymbol{r}_i\\,'-\\boldsymbol{r}_j\\,'\\vert^2}, \\label{eq:undim} \\tag{2}\n\\end{equation}\n$$\n\n* **1k (5pt):** What is the characteristic time scale $\\tau$, and what is its value for argon, which has $\\sigma=3.405$Å (1Å=1E-10m), $m = 39.95u$ (with 1u=1.66E-27kg) and $\\varepsilon=1.0318$ E-2eV (1eV=1.602E-19J)?\n\nWe switch now to a numerical procedure and study the simulation of two interacting atoms.\n* **1l (10pt):** Write a function which solves ([2](#eq:undim)) for two atoms and finds the positions and velocities of the atoms as a function of time. Implement either the Euler-Cromer or the Velocity-Verlet method to solve the equations od motion.\n\n* **1m (5pt):** Simulate the motion of two atoms which start at rest separated by a distance of ${1.5}\\sigma$. Use $\\Delta t'={0.01}$, simulate until $t'=5$ and integrate with one of the above methods.\n\n* **1n (5pt):** Plot the distance between the atoms as a function of time. How does the motion fit with your expectations?\n\n* **1o (5pt):** Repeat the previous tasks, but now with an initial separation of $0.95\\sigma$. Explain your results.\n\n* **1p (10pt):** Compute and plot the kinetic, potential and total energy as a function of time for. Should the total energy be conserved? Why, or why not? Does your program fulfil this? If not, what could be the cause?\n\n### Exercise 2, Coupled Harmonic Oscillators (60pt)\n\nThe relevant chapters from Taylor are chapters 5-7 and the lectures notes on [harmonic oscillations](https://mhjensen.github.io/Physics321/doc/LectureNotes/_build/html/chapter5.html) and the [Lagrangian Formalism and Calculus of Variations](https://mhjensen.github.io/Physics321/doc/LectureNotes/_build/html/chapter8.html). Your codes from homework sets 5-8 and the first midterm may also be of interest.\n\nConsider a mass $m$ that is connected to a wall by a spring with\nspring constant $k$. A second identical mass $m$ is connected to the\nfirst mass by an identical spring. Motion is confined to the $x$ direction only.\n\n* **2a (10pt):** Make a drawing of the system, set up forces and define variables $x_1$ and $x_2$ for the two masses.\n\n* **2b (10pt):** Write the Lagrangian in terms of the positions of the two masses $x_1$ and $x_2$.\n\n* **2c (10pt):** Use the Euler-Lagrange equations to find the equations of motion.\n\n* **2d (10pt):** Find the analytical solutions using a guess of the type\n\n$$\nx_1=Ae^{i\\omega t},~~~x_2=Be^{i\\omega t}.\n$$\n\nSolve for $A/B$ and $\\omega$. Express your answers in terms of $\\omega_0^2=k/m$.\n\n* **2e (20pt):** Write now a program which solves these two coupled differential equations for $x_1$ and $x_2$. Compute the positions $x_1$ and $x_2$ by choosing your initial conditions and compare with the analytical answers from 2d. \n\n### Classical Mechanics Extra Credit Assignment: Scientific Writing and attending Talks\n\nThe following gives you an opportunity to earn **five extra credit\npoints** on each of the remaining homeworks and **ten extra credit points**\non the midterms and finals. This assignment also covers an aspect of\nthe scientific process that is not taught in most undergraduate\nprograms: scientific writing. Writing scientific reports is how\nscientist communicate their results to the rest of the field. Knowing\nhow to assemble a well written scientific report will greatly benefit\nyou in you upper level classes, in graduate school, and in the work\nplace.\n\nThe full information on extra credits is found at . There you will also find examples on how to write a scientific article. \nBelow you can also find a description on how to gain extra credits by attending scientific talks.\n\n\nThis assignment allows you to gain extra credit points by practicing\nyour scientific writing. For each of the remaining homeworks you can\nsubmit the specified section of a scientific report (written about the\nnumerical aspect of the homework) for five extra credit points on the\nassignment. For the two midterms and the final, submitting a full\nscientific report covering the numerical analysis problem will be\nworth ten extra points. For credit the grader must be able to tell\nthat you put effort into the assignment (i.e. well written, well\nformatted, etc.). If you are unfamiliar with writing scientific\nreports, [see the information here](https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/IntroductionScientificWriting.md)\n\nThe following table explains what aspect of a scientific report is due\nwith which homework. You can submit the assignment in any format you\nlike, in the same document as your homework, or in a different one.\nRemember to cite any external references you use and include a\nreference list. There are no length requirements, but make sure what\nyou turn in is complete and through. If you have any questions,\nplease contact Julie Butler at butler@frib.msu.edu.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
HW/Project Due Date Extra Credit Assignment
HW 3 2-8 Abstract
HW 4 2-15 Introduction
HW 5 2-22 Methods
HW 6 3-1 Results and Discussion
**Midterm 1** **3-12** *Full Written Report*
HW 7 3-22 Abstract
HW 8 3-29 Introduction
HW 9 4-5 Results and Discussion
**Midterm 2** **4-16** *Full Written Report*
HW 10 4-26 Abstract
**Final** **4-30** *Full Written Report*
\n\nYou can also gain extra credits if you attend scientific talks.\nThis is described here.\n\n\n### Integrating Classwork With Research\n\nThis opportunity will allow you to earn up to 5 extra credit points on a Homework per week. These points can push you above 100% or help make up for missed exercises.\nIn order to earn all points you must:\n\n1. Attend an MSU research talk (recommended research oriented Clubs is provided below)\n\n2. Summarize the talk using at least 150 words\n\n3. Turn in the summary along with your Homework.\n\nApproved talks:\nTalks given by researchers through the following clubs:\n* Research and Idea Sharing Enterprise (RAISE)​: Meets Wednesday Nights Society for Physics Students (SPS)​: Meets Monday Nights\n\n* Astronomy Club​: Meets Monday Nights\n\n* Facility For Rare Isotope Beam (FRIB) Seminars: ​Occur multiple times a week\n\nIf you have any questions please consult Jeremy Rebenstock, rebensto@msu.edu.\n\nAll the material on extra credits is at .\n", "meta": {"hexsha": "51ed57dc769a155b346e4c3d8524caab0b506efb", "size": 16373, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/Homeworks/final/ipynb/final.ipynb", "max_stars_repo_name": "mhjensen/Physics321", "max_stars_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2020-01-09T17:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T00:48:58.000Z", "max_issues_repo_path": "doc/Homeworks/final/ipynb/final.ipynb", "max_issues_repo_name": "mhjensen/Physics321", "max_issues_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2020-01-08T03:47:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T15:02:57.000Z", "max_forks_repo_path": "doc/Homeworks/final/ipynb/final.ipynb", "max_forks_repo_name": "mhjensen/Physics321", "max_forks_repo_head_hexsha": "f858db36328c9fc127ccb44f62934d8f8749dd9f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 33, "max_forks_repo_forks_event_min_datetime": "2020-01-10T20:40:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:28:41.000Z", "avg_line_length": 58.475, "max_line_length": 413, "alphanum_fraction": 0.6220607097, "converted": true, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197264277872, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.15651482346549309}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)//2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n alpha = 1 + heads\n beta = 1 + N - heads\n y = dist.pdf(x, alpha, beta)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.text(0.05, 0.1, fr\"$\\alpha$ = {alpha}, $\\beta$ = {beta}\")\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\n2*(0.8)/(1+0.8)\n```\n\n\n\n\n 0.888888888888889\n\n\n\n\n```python\npos = lambda p: 2*(p)/(1+p)\n```\n\n\n```python\npos(0.2)\n```\n\n\n\n\n 0.33333333333333337\n\n\n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, pos(0.2), s=140, c=\"#348ABD\")\nplt.scatter(0.8, pos(0.8), s=140, c=\"r\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\n\n```\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\n# posterior = [1./3, 2./3]\nposterior = list(map(pos, prior))\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n# tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n tau = pm.Uniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\n\n```python\nmodel\n```\n\n\n\n\n$$\n \\begin{array}{rcl}\n \\text{lambda_1} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{lambda_2} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{tau} &\\sim & \\text{Uniform}(\\mathit{lower}=0.0,~\\mathit{upper}=73.0)\n \\end{array}\n $$\n\n\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\n\n```python\nmodel\n```\n\n\n\n\n$$\n \\begin{array}{rcl}\n \\text{lambda_1} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{lambda_2} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{tau} &\\sim & \\text{Uniform}(\\mathit{lower}=0.0,~\\mathit{upper}=73.0)\n \\end{array}\n $$\n\n\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\n\n```python\nmodel\n```\n\n\n\n\n$$\n \\begin{array}{rcl}\n \\text{lambda_1} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{lambda_2} &\\sim & \\text{Exponential}(\\mathit{lam}=0.05065023956194388)\\\\\\text{tau} &\\sim & \\text{Uniform}(\\mathit{lower}=0.0,~\\mathit{upper}=73.0)\\\\\\text{obs} &\\sim & \\text{Poisson}(\\mathit{mu}=f(f(f(\\text{tau}),~array),~f(\\text{lambda_1}),~f(\\text{lambda_2})))\n \\end{array}\n $$\n\n\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000, step=step, return_inferencedata=False)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n 100.00% [60000/60000 00:10<00:00 Sampling 4 chains, 0 divergences]\n
\n\n\n\n Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 16 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\n# w = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\n# plt.hist(tau_samples, bins=n_count_data, alpha=1,\n# label=r\"posterior of $\\tau$\",\n# color=\"#467821\", weights=w, rwidth=2.)\nplt.hist(tau_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\tau$\", color=\"#467821\", density=True)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint(lambda_1_samples.mean())\nprint(lambda_2_samples.mean())\n```\n\n 17.743441731223147\n 22.714756780055026\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\nprint(np.mean(lambda_1_samples/lambda_2_samples))\nprint(lambda_1_samples.mean()/lambda_2_samples.mean())\n```\n\n 0.7823251285477749\n 0.7811416121700672\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "752c400994fc738b5270e842c3ac96bc9db6ae5c", "size": 313439, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "Cyberface/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "370a7c49900cb87b1eca26be8c5a833274f294da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "Cyberface/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "370a7c49900cb87b1eca26be8c5a833274f294da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "Cyberface/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "370a7c49900cb87b1eca26be8c5a833274f294da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 222.9295874822, "max_line_length": 95620, "alphanum_fraction": 0.8903518707, "converted": true, "num_tokens": 12332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.15522582713469318}} {"text": "# Bond Prices and Yields\nDebt securities are often called **fixed-income securities**, because they promise either a fixed stream of income or one determined according to a specified formula.\n## Bond Characteristics\n**bond**: A security that obligates the issuer to make specified pay-ments to the holder over a period of time.\n\nbond’s **par value, face value**: The payment to the bondholder at the maturity of the bond.\n\n**coupon rate**: A bond’s annual interest payment per dollar of par value.\n\n**zero-coupon bonds**: A bond paying no coupons that sells at a discount and provides only a payment of par value at maturity.\n\n>**e.g.**\n>\n>- Par value of $\\$1,000$ \n- Coupon rate of $8\\%$\n- The initial price is $\\$997$\n- Maturity, $5$ years\n- Semi-annual coupon payments\n>\n>Cash flow of the buyer\n>\n>\n\n### Treasury Bonds and Notes\n$$\n\\begin{array}{c} \\hline\n\\begin{array}{c:c}\n\\text{T-Notes} & \\text{T-Bonds} \\\\ \\hline\n1 \\text{ to } 10 \\text{ years} & 10 \\text{ to } 30 \\text{ years} \\\\ \\hline\n\\end{array} \\\\\n\\text{denominations of \\$}100 \\text{ or \\$}1000 \\\\\n\\text{semiannual coupon payments} \\\\ \\hline\n\\end{array}\n$$\n\n**Notice**: The number in table with *column* represents the anually coupon, which paid once of six months.\n\nThere's also a minimum price increment, or **tick size**.\n\n>**e.g.**\n>\n>Suppose now the tick size is $\\newcommand{\\ffrac}{\\displaystyle \\frac} \\ffrac{1} {128}$. And the ask price on the board is $132.9922\\%$ of $1000$ dollars.\n>\n>So when it comes to $\\ffrac{126} {128}$, it's $0.984375 < 0.9922$, so there is still space for it to goes up until $\\ffrac{127} {128} = 0.9921875 \\approx 0.9922$, same value after round to $4$ decimal digits\n\nThe other term, **ask yield**, is the yield to maturity (YTM) based on the ask price, which equals to $\\text{Ask Price} + \\text{Total Coupon}$\n\n### Accured Interest and Quoted Bond Priceds\n$\\odot$The bond prices that you see quoted in the financial pages are NOT actually the prices that investors pay for the bond. This is because the quoted price does not include the interest that accrues between coupon payment dates.$\\Join$\n\nIf a bond is purchased between coupon payments, the buyer must pay the seller for accrued interest.\n\n$$\\text{Accrued interest} = \\frac{\\text{Annual coupon payment}} {2} \\times \\frac{\\text{Days since last coupon payment}} {\\text{Days separting coupon payments}}$$\n\nThe actual payment for the buyer is called **invoice price** which is the sum of **quoted price** and **Accured interest**.\n\n>**e.g.** Suppose that the coupon rate is $8\\%$. You buy after $30$ days after last coupon payment, and there are $182$ days in the semiannual coupon period.\n>\n>The semiannual coupon payment is $40$ dollars. And the seller is entitled to a payment of accrued interest of $\\ffrac{30} {182}$ of the semiannual coupon, which is $40 \\times \\ffrac{30} {182} = 6.59$. If the quoted price of the bond is $\\$990$, then the invoice price will be $\\$990 + \\$6.59 = \\$996.59$.\n\n### Corporate Bonds\n**Callable bonds**: Bonds that may be repurchased by the issuer at a specified call price during the call period.\n- higher coupon rate than noncallable bonds\n- higher promised yields to maturity than noncallable bonds\n- when the coupon bond are higher than the current interest rate, the firm may call it back\n\n**Convertible bonds**: the buyer has an option to convert bonds into stocks.\n- lower coupon rate than nonconvertible bonds\n- lower promised yields to maturity than noncallable bonds\n\n**Puttable bonds**: the buyer has an option to retire the bond earlier.\n- Retire the bond when the market interest rates are higher than before\n\n**Floating-rate bonds**: coupon rates periodically reset according to some\nmarket rates.\n- For example, $\\text{next year coupon rate (annully adjusted)} = \\text{T-bill rate (at adjustment date)} + 2\\%$\n\n### Preferred Stock\n- like bonds, preferred stock promises to pay a specified stream of dividends (normally a fixed amount)\n- unlike bonds, the failure to pay the promised dividend does not result in corporate bankruptcy\n- the claim to the firm’s assets has lower priority than that of bondholders but higher priority than that of common stockholders.\n- unlike bonds, payment on divident is not tax-deductible expenses to the firm\n- an offsetting tax advantage: When one corporation buys the preferred stock of another corporation, it pays taxes on only $30\\%$ of the dividends received. For example: if the firm’s tax bracket is $35\\%$, then the **effective tax rate** on preferred dividends is $30\\% \\times 35\\% = 10.5\\%$.\n- Preferred stock rarely gives its holders full voting privileges in the firm. However, if the preferred dividend is skipped, the preferred stockholders will then be provided some voting power.\n- Based on above, most preferred stock is held by corporations.\n\n### International Bonds\nExchange rate risk!\n\n1. Foreign bonds\n - Yankee bonds: Dollar-denominated bonds sold in the U.S. by non-U.S. issuers\n - Samurai bonds: Yen-denominated bonds sold in Japan by non-Japanese issuers\n - Bulldog bonds: Pound-denominated bonds sold in the U.K. by non-U.K. issuers\n2. Eurobonds\n - Euroyen: Yen-denominated bonds selling outside Japan\n - Eurosterling: Pound-denominated bonds selling outside the U.K.\n\n## Bond Pricing\nCalculate the present value of all future cash flow at YTM.\n\n**YTM**: universal discount rate for cash flows of any horizons, $r$.\n\n$$\\begin{align}\n\\text{Bond value} &= \\text{Present value of coupons} + \\text{Present value of par value} \\\\\n&= \\sum_{t=1} ^{T} \\frac{\\text{Coupon}} {(1+r)^t} + \\frac{\\text{Par}} {(1+r)^T}\n\\end{align}$$\n\nTo better calculate, we define the following \n\n$$\\text{Annuity factor}(r,T) = \\frac{1} {r} \\left[ 1 - \\frac{1} {(1+r)^T}\\right], \\text{PV factor}(r,T) = \\frac{1} {(1+r)^T}$$\n\nSo that $\\text{Bond value} = \\text{Coupon} \\times \\text{Annuity factor}(r,T) + \\text{Par Value} \\times \\text{PV factor}(r,T)$\n\n**The inverse relationship between price and yield**: Bond price will fall as market interest rates rise, which is the central feature of fixed-income securities.\n\n$\\odot$Generally, keeping all other factors the same, the longer the maturity of the bond, the greater the sensitivity of its price to fluctuations in the interest rate. $\\Join$\n\n>**e.g.** Given $\\text{Par} = 100$, $\\text{Annual coupon rate} = 10\\%$, $\\text{YTM} = r = 10\\%$, $\\text{Maturity} = T = 2$;\n>\n>If you bought at 1/1/2000, it will pay first coupon at 1/1/2001 and mature at 1/1/2002, so that its price now\n>\n>$$\\sum_{t=1} ^{T} \\frac{\\text{Coupon}} {(1+r)^t} + \\frac{\\text{Par}} {(1+r)^T} = \\frac{\\$10} {(1+0.1)^1} + \\frac{\\$10 + \\$100} {(1+0.1)^2} = \\$100$$\n>\n>And if you bought at 4/1/2000, first we need to calculate the $\\text{Accrued Interest}$\n>\n>$$\\frac{1/1/2000 - 4/1/2000} {1/1/2000 - 1/1/ 2001} =\\frac{91} {366} = 0.2486$$\n>\n>Then is the discount, remember to discount to the issue date, which is\n>\n>$$\\sum_{t=1}^{T} \\frac{\\text{Coupon}} {(1+r)^{t-0.2486}} + \\frac{\\text{Par}} {(1+r)^{T-0.2486}}= \\frac{10} {1.01^{0.751}} + \\frac{110} {1.01^{1.751}} = 102.4$$\n>\n>Or another way:\n>\n>$$\\text{Invoice Price} = \\text{Quoted Price} + \\text{Accrued Interest} = 99.912 + 2.486 = 102.4$$\n\n\n\n\n## Bond Yields\n### Yield to Maturity\n**yield to maturity (YTM)**: The discount rate that makes the present value of a bond’s payments equal to its price.\n\nLet $n$ be the number of payments, we solve $r$ using the equation below\n\n$$\\text{Bond-Price Today} = \\sum_{t=1}^{n}\\frac{\\text{Coupon}} {\\left( 1+r \\right)^t} + \\frac{\\text{Par}} {\\left( 1+r \\right)^n} $$\n\nSo that $\\text{YTM} = n * r$, and the effective annual rate is $\\left( 1+r \\right)^n$\n\nSimilar if bond price is during coupon dates.\n\n**current yield**: Annual coupon divided by bond price.\n\n>**e.g.**\n>\n>- $\\text{Par} = \\$1000$\n- Semiannual coupon payments\n- $\\text{Annual coupon rate} = 8\\%$\n- $\\text{Maturity} = T = 30$ years\n- $\\text{Bond price} = \\text{PV} = \\$1,276.76$\n>\n>So that $\\text{Coupon Rate} = 8\\%$\n>\n>$\\text{current yield} = \\ffrac {\\text{Annual coupon payments}} {\\text{Bond price}} = \\ffrac{\\$ 80} {\\$ 1276.76} = 6.27\\%$\n>\n>Using calculator, $\\text{YTM} = r = 0.06 $\n\nNormally\n\n- YTM = Coupon Rate →→→ Price = Par (sell at par)\n- **Discount Bond**: YTM > Coupon Rate →→→ Price < Par (sell at a discount)\n - Coupon Rate < Current Yield < YTM\n- **Premium Bond**: YTM < Coupon Rate →→→ Price > Par (sell at a premium)\n - Coupon Rate > Current Yield > YTM\n\nAnd one thing to remember is that both YTM and Coupon Rate are annulized into APR's (Annual Percentage Rate).\n\n### Yield to Call\nSimilar to Yield to Maturity, now it's mature ahead of the term in a higher call price\n\n>**e.g.**\n>\n>- $\\text{Par} = \\$1000$\n- Semiannual coupon payments\n- $\\text{Annual coupon rate} = 8\\%$\n- $\\text{Maturity} = T = 30$ years\n- $\\text{Bond price} = \\text{PV} = \\$1150$\n- Callable in $10$ years at a call price of $1100$\n>\n>YTM:```=YIELD(DATE(2000,1,1),DATE(2030,1,1),8%,115,100,2)``` = $6.82\\%$\n>\n>YTC:```=YIELD(DATE(2000,1,1),DATE(2010,1,1),8%,115,110,2)``` = $6.61\\%$\n\n## Bond Prices over Time\nEven if the interest rate (YTM) is constant over the life of the bond, the bond price still varies over time unless it’s sold at the par (CR=YTM).\n\n\n\n## Default Risk and Bond Pricing\n**investment grade bond**: A bond rated BBB and above by Standard & Poor's or Baa and above by Moody's.\n\n**speculative grade or junk bonds**: A bond rated BB or lower by Standard & Poor's, Ba or lower by Moody's, or unrated.\n\nContrary to T-bonds, Corporate bonds have default risk, which affects the bond rating.\n\n### Yield to Maturity and Default Risk\nBondholders are expected to receive only $70\\%$ of par when the firm goes bankrupt. And at that time, the expected YTM will be lower than the previously stated YTM.\n\nDefault Premium = Yield spreads between corporate and comparable T-bonds\n\n### Credit Default Swaps\n\nCDS is an insurance policy on the default risk of a corporate bond or loan.\n\nIn the event of default, CDS buyer may deliver a defaulted bond to the seller in return for the bond's par value.\n\n## The Yield Curve\n**Yield curve**: a graph of YTM as a function of term to maturity.\n\nT**erm structure of interest rates**: the relationship between YTM and term to maturity.\n\nTypes:\n\n1. Flat Yield Curve\n2. Upward-sloping (Rising Yield Curve) (the most common one) \n3. Downward-sloping (Inverted Yield Curve)\n4. Hump shaped\n\n### The Expectations Theory\n**Expectation hypothesis**: The theory that YTM are determined by expectations of future short-term interest rates.\n\n>**e.g.** Returns to two two-year investment strategies\n>\n>$r_1 = 8\\%$, $E(r_2) = 10\\%$. what is the fair current YTM for two-year bond?\n>\n>$$y_2 = \\frac{\\sqrt{1.08 \\times 1.10} - 1} {2} = 8.995\\%$$\n>\n>So that on the yield curve, $y_1 = 8\\%$, $y_2 = 8.995\\%$\n>\n>- Upward-sloping yield curve $\\Rightarrow$ expect future interest rate $\\uparrow$\n - More loan and more money in stock market\n- Downward-sloping yield curve $\\Rightarrow$ expect future interest rate $\\downarrow$\n\n**forward rate**: The inferred short-term rate of interest for a future period that makes the expected total return of a long-term bond equal to that of rolling over short-term bonds.\n\nUsing the expectations hypothesis to infer the market’s expectation of future short-term rates inversely.\n\n>**e.g.**\n>\n>Given $y_1=8\\%$, $y_2=8.995\\%$, since $\\left( 1+y_1 \\right)\\cdot\\left( 1+f_2 \\right) = \\left( 1+y_2 \\right)^2$, we have\n>\n>$$f_2 = \\frac{\\left( 1+y_2 \\right)^2} {\\left( 1+y_1 \\right)} - 1 = 10\\%$$\n>\n>Given YTM for two-year bond: $6\\%$; YTM for three-year bond: $7\\%$\n>\n>What is the forward rate for the third year?\n>\n>$$f_3 = \\frac{\\left( 1+y_3 \\right)^3} {\\left( 1+y_2 \\right)^2} - 1 = 9.03\\%$$\n\n$$f_n = \\frac{\\left( 1+y_n \\right)^n} {\\left( 1+y_{n-1} \\right)^{n-1}} - 1$$\n\n### The Liquidity Preference Theory\nLong-term bonds are subject to greater interest rate risk than short-term bonds. Therefore investors in long-term bonds might require a risk premium (liquidity premium) to compensate them for this risk.\n\n**liquidity preference theory**: The theory that investors demand a risk premium on long-term bonds.\n\n**liquidity premium**: The extra expected return demanded by investors as compensation for the greater risk of longer-term bonds.\n\n$$\\text{Forward Rate}: f_n = E(r_n) + \\text{liquidity premium}$$\n\n>**e.g.**\n>\n>- Without $1\\%$ liquidity premium, $y_1 = 8\\%$, $f_2 = 8\\%$.\n - $y_2 = 8\\%$, flat yield curve\n>\n>\n>- With $1\\%$ liquidity premium, $y_1 = 8\\%$, $f_2 = 8\\% + 1\\% = 9\\%$.\n - $y_2 = \\sqrt{1.08\\times 1.09} - 1 = 8.5\\% > y_1 = 8\\%$, upward-sloping yield curve\n\nSo that **in the *presence* of liquidity premium**, even **in the *absence* of any expectation of future increases in interest rates**, still the yield curve will be upward-sloping.\n\n### A Synthesis\nA trade-off between Liquidity Preference and Expectations Theories\n\n\n\nAnd for most of time long term t-notes have higher return rate than short term t-bills, meaning that it's commonly upward-sloping.\n\n## Summary\n- Debt securities are distinguished by their promise to pay a fixed or specified stream of income to their holders. The coupon bond is a typical debt security.\n- Treasury notes and bonds have original maturities greater than one year. They are issued at or near par value, with their prices quoted net of accrued interest.\n- Callable bonds should offer higher promised yields to maturity to compensate investors for the fact that they will not realize full capital gains should the interest rate fall and the bonds be called away from them at the stipulated call price. Bonds often are issued with a period of call protection. In addition, discount bonds selling significantly below their call price offer implicit call protection.\n- Put bonds give the bondholder rather than the issuer the choice to terminate or extend the life of the bond.\n- Convertible bonds may be exchanged, at the bondholder’s discretion, for a specified number of shares of stock. Convertible bondholders “pay” for this option by accepting a lower coupon rate on the security.\n- Floating-rate bonds pay a fixed premium over a referenced short-term interest rate. Risk is limited because the rate paid is tied to current market conditions.\n- The yield to maturity is the single discount rate that equates the present value of a security’s cash flows to its price. Bond prices and yields are inversely related. For premium bonds, the coupon rate is greater than the current yield, which is greater than the yield to maturity. These inequalities are reversed for discount bonds.\n- The yield to maturity often is interpreted as an estimate of the average rate of return to an investor who purchases a bond and holds it until maturity. This interpretation is subject to error, however. Related measures are yield to call, realized compound yield, and expected (versus promised) yield to maturity.\n- Treasury bills are U.S. government–issued zero-coupon bonds with original maturities of up to one year. Treasury STRIPS are longer-term default-free zero-coupon bonds. Prices of zero-coupon bonds rise exponentially over time, providing a rate of appreciation equal to the interest rate. The IRS treats this price appreciation as imputed taxable interest income to the investor.\n- When bonds are subject to potential default, the stated yield to maturity is the maximum possible yield to maturity that can be realized by the bondholder. In the event of default, however, that promised yield will not be realized. To compensate bond investors for default risk, bonds must offer default premiums, that is, promised yields in excess of those offered by default-free government securities. If the firm remains healthy, its bonds will provide higher returns than government bonds. Otherwise, the returns may be lower.\n- Bond safety often is measured using financial ratio analysis. Bond indentures offer safeguards to protect the claims of bondholders. Common indentures specify sinking fund requirements, collateralization, dividend restrictions, and subordination of future debt.\n- Credit default swaps provide insurance against the default of a bond or loan. The swap buyer pays an annual premium to the swap seller but collects a payment equal to lost value if the loan later goes into default.\n- The term structure of interest rates is the relationship between time to maturity and term to maturity. The yield curve is a graphical depiction of the term structure. The forward rate is the break-even interest rate that would equate the total return on a rollover strategy to that of a longer-term zero-coupon bond.\n- The expectations hypothesis holds that forward interest rates are unbiased forecasts of future interest rates. The liquidity preference theory, however, argues that long-term bonds will carry a risk premium known as a liquidity premium. A positive liquidity premium can cause the yield curve to slope upward even if no increase in short rates is anticipated.\n\n## Key Terms\n- bond\n- callable bonds\n- collateral\n- convertible bonds\n- coupon rate\n- credit default swap (CDS)\n- current yield\n- debenture\n- default premium\n- discount bonds\n- expectations hypothesis\n- face value\n- floating-rate bonds\n- forward rate\n- horizon analysis\n- indenture\n- investment grade bonds\n- liquidity preference theory\n- liquidity premium\n- par value\n- premium bonds\n- put bond\n- realized compound return\n- reinvestment rate risk\n- sinking fund\n- speculative grade or junk bond\n- subordination clauses\n- term structure of interest rates\n- yield curve\n- yield to maturity (YTM)\n- zero-coupon bond\n\n## Key Formula\n- Price of a coupon bond\n\n$$\\begin{align}\n\\text{Bond value} &= \\text{Present value of coupons} + \\text{Present value of par value} \\\\\n&= \\sum_{t=1} ^{T} \\frac{\\text{Coupon}} {(1+r)^t} + \\frac{\\text{Par}} {(1+r)^T} \\\\\n&= \\text{Coupon} \\times \\text{Annuity factor}(r,T) + \\text{Par Value} \\times \\text{PV factor}(r,T)\n\\end{align}$$\n\n- Forward rate of interest\n$$1 + f_n = \\frac{\\left( 1+y_n \\right)^n} {\\left( 1+y_{n-1} \\right)^{n-1}}$$\n\n- Liquidity premium = Forward rate – Expected short rate\n\n## Assignment\n1. Sinking funds are commonly viewed as protecting the ___ of the bond.\n - ~~Issure~~\n - ~~Underwriter~~\n - Holder\n - ~~Dealer~~\n2. A mortgage bond is \n - secured by property owned by the firm\n - ~~secured by equipment owned by the firm~~\n - ~~unsecured~~\n - ~~secured by other securities held by the firm~~\n3. Floating-rate bonds have a ___ that is adjusted with current market interest rates.\n - ~~maturity date~~\n - ~~coupon payment date~~\n - coupon rate\n - ~~dividend yield~~\n4. The primary difference between Treasury notes and bonds is\n - maturity at issue\n - ~~default risk~~\n - ~~coupon rate~~\n - ~~tax status~~\n5. TIPS offer investors inflation protection by ___ by the inflation rate each year.\n - ~~increasing only the coupon rate~~\n - increasing both the par value and the coupon payment\n - ~~increasing only the par value~~\n - ~~increasing the promised yield to maturity~~\n6. ___ bonds represent a novel way of obtaining insurance from capital markets against specified disasters.\n - ~~Asset-backed bonds~~\n - ~~TIPS~~\n - Catastrophe\n - ~~Pay-in-kind~~\n7. Everything else equal, the ___ the maturity of a bond and the ___ the coupon, the greater the sensitivity of the bond's price to interest rate changes.\n - ~~longer; higher~~\n - ~~shorter; higher~~\n - longer; lower\n - ~~shorter; lower~~\n8. A coupon bond that pays interest of $\\$60$ annually has a par value of $\\$1,000$, matures in $5$ years, and is selling today at an $\\$84.52$ discount from par value. The yield to maturity on this bond is\n$$8.12\\%$$\n\n9. Given zero coupon bonds: A with $1$ year of maturity and YTM: $6\\%$; B with $2$ year of maturity and YTM: $7.50\\%$, The expected $1\\text{-year}$ interest rate $1$ year from now should be about\n$$1.075^2 \\div 1.06 - 1 \\approx 9.0212\\%$$\n\n10. **VIP** A $1\\%$ decline in yield will have the least effect on the price of a bond with a\n - ~~20-year maturity, selling at 80~~\n - ~~20-year maturity, selling at 100~~\n - 10-year maturity, selling at 100\n - ~~10-year maturity, selling at 80~~\n11. An investor pays $\\$989.40$ for a bond. The bond has an annual coupon rate of $4.8\\%$. What is the current yield on this bond?\n$$\\$48 \\div \\$989.40 = 4.8514\\%$$\n\n12. A bond was purchased at a premium and is now selling at a discount because of a change in market interest rates. If the bond pays a $4\\%$ annual coupon, what is the likely impact on the holding-period return if an investor decides to sell now?\n - ~~Increased~~\n - Decreased\n - ~~Stayed the same~~\n - ~~The answer cannot be determined from the information given~~\n13. You buy a TIPS at issue at par for $\\$1,000$. The bond has a $4.0\\%$ coupon. Inflation is $3.0\\%$, $4.0\\%$, and $5.0\\%$ over the next $3$ years. The total annual coupon income you will receive in year $3$ is \n$$\\$44 \\times 1.033 \\times 1.04 \\times 1.05 = \\$44.9904$$\n\n14. A coupon bond that pays interest of $\\$61$ annually has a par value of $\\$1,000$, matures in $5$ years, and is selling today at a $\\$75.50$ discount from par value. The current yield on this bond is\n$$\\$61 \\div (\\$1000 - \\$75.5) = 6.60\\%$$\n", "meta": {"hexsha": "50fe2a2a2da166e4312c044ab06a0c38f931965f", "size": 26814, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FinMath/Intermediate Investment/Note_Chap10.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "FinMath/Intermediate Investment/Note_Chap10.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FinMath/Intermediate Investment/Note_Chap10.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 53.628, "max_line_length": 542, "alphanum_fraction": 0.6135973745, "converted": true, "num_tokens": 5865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.15454746547166803}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500, 1000, 10000]\n\n# generate samples from coin with p(head)=0.5\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 1000)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.axvline(0.5, color=\"k\", linestyle=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(20)\npoi = stats.poisson\nlambda_ = [1.5, 4.25, 15.0]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[2]),\n label=\"$\\lambda = %.1f$\" % lambda_[2], alpha=0.60, lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1, 0.125, 1e-6]\n\nfor l in lambda_:\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n label=\"$\\lambda = %.3f$\" % l)\n #plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\n C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n # log-likelihood\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n Sampling 4 chains: 100%|██████████| 60000/60000 [00:44<00:00, 1351.96draws/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=50, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=50, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint('Mean lambda_1 %.2f'%lambda_1_samples.mean())\nprint('Mean lambda_2 %.2f'%lambda_2_samples.mean())\n```\n\n Mean lambda_1 17.74\n Mean lambda_2 22.54\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n(lambda_1_samples/lambda_2_samples).mean()\n```\n\n\n\n\n 0.789677940613353\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\ntau_adapted_idx = tau_samples[tau_samples<45]\nlambda_1_samples[tau_adapted_idx].mean()\n```\n\n\n\n\n 17.351476201120462\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "cc5489430469f58f454b4e71934fa4b65076c3c0", "size": 318770, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "kopytjuk/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "f8bc5f88f99b216b5cdfead5a269d06450598d9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "kopytjuk/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "f8bc5f88f99b216b5cdfead5a269d06450598d9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "kopytjuk/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "f8bc5f88f99b216b5cdfead5a269d06450598d9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 286.6636690647, "max_line_length": 106132, "alphanum_fraction": 0.9025221947, "converted": true, "num_tokens": 11705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.15452399642084755}} {"text": "```python\n# This mounts your Google Drive to the Colab VM.\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# TODO: Enter the foldername in your Drive where you have saved the unzipped\n# assignment folder, e.g. 'cs231n/assignments/assignment1/'\nFOLDERNAME = \"cs231n_Feifei/assignments/2021/assignment2\"\nassert FOLDERNAME is not None, \"[!] Enter the foldername.\"\n\n# Now that we've mounted your Drive, this ensures that\n# the Python interpreter of the Colab VM can load\n# python files from within it.\nimport sys\nsys.path.append('/content/drive/MyDrive/{}'.format(FOLDERNAME))\n\n# This downloads the CIFAR-10 dataset to your Drive\n# if it doesn't already exist.\n%cd /content/drive/MyDrive/$FOLDERNAME/cs231n/datasets/\n!bash get_datasets.sh\n%cd /content/drive/MyDrive/$FOLDERNAME\n```\n\n Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n /content/drive/MyDrive/cs231n_Feifei/assignments/2021/assignment2/cs231n/datasets\n /content/drive/MyDrive/cs231n_Feifei/assignments/2021/assignment2\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n# Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. One idea along these lines is batch normalization, proposed by [1] in 2015.\n\nTo understand the goal of batch normalization, it is important to first recognize that machine learning methods tend to perform better with input data consisting of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features. This will ensure that the first layer of the network sees data that follows a nice distribution. However, even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance, since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\n\nThe authors of [1] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, they propose to insert into the network layers that normalize batches. At training time, such a layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\n\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n\n[1] [Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.](https://arxiv.org/abs/1502.03167)\n\n\n```python\n# Setup cell.\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams[\"figure.figsize\"] = (10.0, 8.0) # Set default size of plots.\nplt.rcParams[\"image.interpolation\"] = \"nearest\"\nplt.rcParams[\"image.cmap\"] = \"gray\"\n\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\"Returns relative error.\"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\ndef print_mean_std(x,axis=0):\n print(f\" means: {x.mean(axis=axis)}\")\n print(f\" stds: {x.std(axis=axis)}\\n\")\n```\n\n =========== You can safely ignore the message below if you are NOT working on ConvolutionalNetworks.ipynb ===========\n \tYou will need to compile a Cython extension for a portion of this assignment.\n \tThe instructions to do this will be given in a section of the notebook below.\n\n\n\n```python\n# Load the (preprocessed) CIFAR-10 data.\ndata = get_CIFAR10_data()\nfor k, v in list(data.items()):\n print(f\"{k}: {v.shape}\")\n```\n\n X_train: (49000, 3, 32, 32)\n y_train: (49000,)\n X_val: (1000, 3, 32, 32)\n y_val: (1000,)\n X_test: (1000, 3, 32, 32)\n y_test: (1000,)\n\n\n# Batch Normalization: Forward Pass\nIn the file `cs231n/layers.py`, implement the batch normalization forward pass in the function `batchnorm_forward`. Once you have done so, run the following to test your implementation.\n\nReferencing the paper linked to above in [1] may be helpful!\n\n\n```python\n# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization \n\n# Simulate the forward pass for a two-layer network.\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint_mean_std(a,axis=0)\n\ngamma = np.ones((D3,))\nbeta = np.zeros((D3,))\n\n# Means should be close to zero and stds close to one.\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\n\n# Now means should be close to beta and stds close to gamma.\nprint('After batch normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=0)\n```\n\n Before batch normalization:\n means: [ -2.3814598 -13.18038246 1.91780462]\n stds: [27.18502186 34.21455511 37.68611762]\n \n After batch normalization (gamma=1, beta=0)\n means: [5.32907052e-17 7.04991621e-17 1.85962357e-17]\n stds: [0.99999999 1. 1. ]\n \n After batch normalization (gamma= [1. 2. 3.] , beta= [11. 12. 13.] )\n means: [11. 12. 13.]\n stds: [0.99999999 1.99999999 2.99999999]\n \n\n\n\n```python\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\n\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\n\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint_mean_std(a_norm,axis=0)\n```\n\n After batch normalization (test-time):\n means: [-0.03927354 -0.04349152 -0.10452688]\n stds: [1.01531427 1.01238373 0.97819987]\n \n\n\n# Batch Normalization: Backward Pass\nNow implement the backward pass for batch normalization in the function `batchnorm_backward`.\n\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\n\nOnce you have finished, run the following to numerically check your backward pass.\n\n\n```python\n# Gradient check batchnorm backward pass.\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\n\n# You should expect to see relative errors between 1e-13 and 1e-8.\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.7029235612572515e-09\n dgamma error: 7.420414216247087e-13\n dbeta error: 2.8795057655839487e-12\n\n\n# Batch Normalization: Alternative Backward Pass\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For example, you can derive a very simple formula for the sigmoid function's backward pass by simplifying gradients on paper.\n\nSurprisingly, it turns out that you can do a similar simplification for the batch normalization backward pass too! \n\nIn the forward pass, given a set of inputs $X=\\begin{bmatrix}x_1\\\\x_2\\\\...\\\\x_N\\end{bmatrix}$, \n\nwe first calculate the mean $\\mu$ and variance $v$.\nWith $\\mu$ and $v$ calculated, we can calculate the standard deviation $\\sigma$ and normalized data $Y$.\nThe equations and graph illustration below describe the computation ($y_i$ is the i-th element of the vector $Y$).\n\n\\begin{align}\n& \\mu=\\frac{1}{N}\\sum_{k=1}^N x_k & v=\\frac{1}{N}\\sum_{k=1}^N (x_k-\\mu)^2 \\\\\n& \\sigma=\\sqrt{v+\\epsilon} & y_i=\\frac{x_i-\\mu}{\\sigma}\n\\end{align}\n\n\n\nThe meat of our problem during backpropagation is to compute $\\frac{\\partial L}{\\partial X}$, given the upstream gradient we receive, $\\frac{\\partial L}{\\partial Y}.$ To do this, recall the chain rule in calculus gives us $\\frac{\\partial L}{\\partial X} = \\frac{\\partial L}{\\partial Y} \\cdot \\frac{\\partial Y}{\\partial X}$.\n\nThe unknown/hard part is $\\frac{\\partial Y}{\\partial X}$. We can find this by first deriving step-by-step our local gradients at \n$\\frac{\\partial v}{\\partial X}$, $\\frac{\\partial \\mu}{\\partial X}$,\n$\\frac{\\partial \\sigma}{\\partial v}$, \n$\\frac{\\partial Y}{\\partial \\sigma}$, and $\\frac{\\partial Y}{\\partial \\mu}$,\nand then use the chain rule to compose these gradients (which appear in the form of vectors!) appropriately to compute $\\frac{\\partial Y}{\\partial X}$.\n\nIf it's challenging to directly reason about the gradients over $X$ and $Y$ which require matrix multiplication, try reasoning about the gradients in terms of individual elements $x_i$ and $y_i$ first: in that case, you will need to come up with the derivations for $\\frac{\\partial L}{\\partial x_i}$, by relying on the Chain Rule to first calculate the intermediate $\\frac{\\partial \\mu}{\\partial x_i}, \\frac{\\partial v}{\\partial x_i}, \\frac{\\partial \\sigma}{\\partial x_i},$ then assemble these pieces to calculate $\\frac{\\partial y_i}{\\partial x_i}$. \n\nYou should make sure each of the intermediary gradient derivations are all as simplified as possible, for ease of implementation. \n\nAfter doing so, implement the simplified batch normalization backward pass in the function `batchnorm_backward_alt` and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\n\n\n```python\nnp.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))\n```\n\n dx difference: 1.8935408978368493e-12\n dgamma difference: 0.0\n dbeta difference: 0.0\n speedup: 1.85x\n\n\n# Fully Connected Networks with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your `FullyConnectedNet` in the file `cs231n/classifiers/fc_net.py`. Modify your implementation to add batch normalization.\n\nConcretely, when the `normalization` flag is set to `\"batchnorm\"` in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\n\n**Hint:** You might find it useful to define an additional helper layer similar to those in the file `cs231n/layer_utils.py`.\n\n\n```python\nnp.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\n# You should expect losses between 1e-4~1e-10 for W, \n# losses between 1e-08~1e-10 for b,\n# and losses between 1e-08~1e-09 for beta and gammas.\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n normalization='batchnorm')\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()\n```\n\n Running check with reg = 0\n Initial loss: 2.2611955101340957\n W1 relative error: 1.10e-04\n W2 relative error: 4.70e-06\n W3 relative error: 3.92e-10\n b1 relative error: 1.39e-09\n b2 relative error: 5.55e-09\n b3 relative error: 1.17e-10\n beta1 relative error: 6.94e-09\n beta2 relative error: 1.84e-09\n gamma1 relative error: 7.57e-09\n gamma2 relative error: 1.63e-09\n \n Running check with reg = 3.14\n Initial loss: 6.996533220108303\n W1 relative error: 1.98e-06\n W2 relative error: 2.28e-06\n W3 relative error: 1.11e-08\n b1 relative error: 5.55e-09\n b2 relative error: 2.22e-08\n b3 relative error: 2.10e-10\n beta1 relative error: 6.65e-09\n beta2 relative error: 3.39e-09\n gamma1 relative error: 5.94e-09\n gamma2 relative error: 3.72e-09\n\n\n# Batch Normalization for Deep Networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.\n\n\n```python\nnp.random.seed(231)\n\n# Try training a very deep net with batchnorm.\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\nprint('Solver with batch norm:')\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True,print_every=20)\nbn_solver.train()\n\nprint('\\nSolver without batch norm:')\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=20)\nsolver.train()\n```\n\n Solver with batch norm:\n (Iteration 1 / 200) loss: 2.340974\n (Epoch 0 / 10) train acc: 0.104000; val_acc: 0.108000\n (Epoch 1 / 10) train acc: 0.330000; val_acc: 0.280000\n (Iteration 21 / 200) loss: 2.023269\n (Epoch 2 / 10) train acc: 0.377000; val_acc: 0.286000\n (Iteration 41 / 200) loss: 2.062190\n (Epoch 3 / 10) train acc: 0.472000; val_acc: 0.287000\n (Iteration 61 / 200) loss: 1.751384\n (Epoch 4 / 10) train acc: 0.577000; val_acc: 0.306000\n (Iteration 81 / 200) loss: 1.295173\n (Epoch 5 / 10) train acc: 0.597000; val_acc: 0.313000\n (Iteration 101 / 200) loss: 1.287729\n (Epoch 6 / 10) train acc: 0.711000; val_acc: 0.347000\n (Iteration 121 / 200) loss: 0.961143\n (Epoch 7 / 10) train acc: 0.767000; val_acc: 0.351000\n (Iteration 141 / 200) loss: 1.017802\n (Epoch 8 / 10) train acc: 0.774000; val_acc: 0.312000\n (Iteration 161 / 200) loss: 0.751491\n (Epoch 9 / 10) train acc: 0.824000; val_acc: 0.365000\n (Iteration 181 / 200) loss: 0.764919\n (Epoch 10 / 10) train acc: 0.868000; val_acc: 0.329000\n \n Solver without batch norm:\n (Iteration 1 / 200) loss: 2.302332\n (Epoch 0 / 10) train acc: 0.116000; val_acc: 0.121000\n (Epoch 1 / 10) train acc: 0.270000; val_acc: 0.234000\n (Iteration 21 / 200) loss: 2.072398\n (Epoch 2 / 10) train acc: 0.311000; val_acc: 0.251000\n (Iteration 41 / 200) loss: 1.852688\n (Epoch 3 / 10) train acc: 0.374000; val_acc: 0.287000\n (Iteration 61 / 200) loss: 1.705947\n (Epoch 4 / 10) train acc: 0.416000; val_acc: 0.309000\n (Iteration 81 / 200) loss: 1.558138\n (Epoch 5 / 10) train acc: 0.453000; val_acc: 0.319000\n (Iteration 101 / 200) loss: 1.652772\n (Epoch 6 / 10) train acc: 0.488000; val_acc: 0.329000\n (Iteration 121 / 200) loss: 1.380955\n (Epoch 7 / 10) train acc: 0.540000; val_acc: 0.322000\n (Iteration 141 / 200) loss: 1.262761\n (Epoch 8 / 10) train acc: 0.585000; val_acc: 0.334000\n (Iteration 161 / 200) loss: 1.078578\n (Epoch 9 / 10) train acc: 0.631000; val_acc: 0.349000\n (Iteration 181 / 200) loss: 0.927825\n (Epoch 10 / 10) train acc: 0.701000; val_acc: 0.338000\n\n\nRun the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.\n\n\n```python\ndef plot_training_history(title, label, baseline, bn_solvers, plot_fn, bl_marker='.', bn_marker='.', labels=None):\n \"\"\"utility function for plotting training history\"\"\"\n plt.title(title)\n plt.xlabel(label)\n bn_plots = [plot_fn(bn_solver) for bn_solver in bn_solvers]\n bl_plot = plot_fn(baseline)\n num_bn = len(bn_plots)\n for i in range(num_bn):\n label='with_norm'\n if labels is not None:\n label += str(labels[i])\n plt.plot(bn_plots[i], bn_marker, label=label)\n label='baseline'\n if labels is not None:\n label += str(labels[0])\n plt.plot(bl_plot, bl_marker, label=label)\n plt.legend(loc='lower center', ncol=num_bn+1) \n\n \nplt.subplot(3, 1, 1)\nplot_training_history('Training loss','Iteration', solver, [bn_solver], \\\n lambda x: x.loss_history, bl_marker='o', bn_marker='o')\nplt.subplot(3, 1, 2)\nplot_training_history('Training accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.train_acc_history, bl_marker='-o', bn_marker='-o')\nplt.subplot(3, 1, 3)\nplot_training_history('Validation accuracy','Epoch', solver, [bn_solver], \\\n lambda x: x.val_acc_history, bl_marker='-o', bn_marker='-o')\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n# Batch Normalization and Initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\n\nThe first cell will train eight-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.\n\n\n```python\nnp.random.seed(231)\n\n# Try training a very deep net with batchnorm.\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers_ws = {}\nsolvers_ws = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization='batchnorm')\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers_ws[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers_ws[weight_scale] = solver\n```\n\n Running weight scale 1 / 20\n Running weight scale 2 / 20\n Running weight scale 3 / 20\n Running weight scale 4 / 20\n Running weight scale 5 / 20\n Running weight scale 6 / 20\n Running weight scale 7 / 20\n Running weight scale 8 / 20\n Running weight scale 9 / 20\n Running weight scale 10 / 20\n Running weight scale 11 / 20\n Running weight scale 12 / 20\n Running weight scale 13 / 20\n Running weight scale 14 / 20\n Running weight scale 15 / 20\n Running weight scale 16 / 20\n\n\n /content/drive/My Drive/cs231n_Feifei/assignments/2021/assignment2/cs231n/layers.py:143: RuntimeWarning: overflow encountered in exp\n loss = - np.sum(x * mask) + np.sum(np.log(np.sum(np.exp(x), axis=1)))\n /content/drive/My Drive/cs231n_Feifei/assignments/2021/assignment2/cs231n/layers.py:145: RuntimeWarning: overflow encountered in exp\n dx = -1 * mask + np.exp(x) / np.sum(np.exp(x),\n /content/drive/My Drive/cs231n_Feifei/assignments/2021/assignment2/cs231n/layers.py:146: RuntimeWarning: invalid value encountered in true_divide\n axis=1).reshape((num_train, 1))\n\n\n Running weight scale 17 / 20\n Running weight scale 18 / 20\n Running weight scale 19 / 20\n Running weight scale 20 / 20\n\n\n\n```python\n# Plot results of weight scale experiment.\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers_ws[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))\n \n best_val_accs.append(max(solvers_ws[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs. weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(15, 15)\nplt.show()\n```\n\n## Inline Question 1:\nDescribe the results of this experiment. How does the weight initialization scale affect models with/without batch normalization differently, and why?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Batch Normalization and Batch Size\nWe will now run a small experiment to study the interaction of batch normalization and batch size.\n\nThe first cell will train 6-layer networks both with and without batch normalization using different batch sizes. The second layer will plot training accuracy and validation set accuracy over time.\n\n\n```python\ndef run_batchsize_experiments(normalization_mode):\n np.random.seed(231)\n \n # Try training a very deep net with batchnorm.\n hidden_dims = [100, 100, 100, 100, 100]\n num_train = 1000\n small_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n }\n n_epochs=10\n weight_scale = 2e-2\n batch_sizes = [5,10,50]\n lr = 10**(-3.5)\n solver_bsize = batch_sizes[0]\n\n print('No normalization: batch size = ',solver_bsize)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=None)\n solver = Solver(model, small_data,\n num_epochs=n_epochs, batch_size=solver_bsize,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n solver.train()\n \n bn_solvers = []\n for i in range(len(batch_sizes)):\n b_size=batch_sizes[i]\n print('Normalization: batch size = ',b_size)\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, normalization=normalization_mode)\n bn_solver = Solver(bn_model, small_data,\n num_epochs=n_epochs, batch_size=b_size,\n update_rule='adam',\n optim_config={\n 'learning_rate': lr,\n },\n verbose=False)\n bn_solver.train()\n bn_solvers.append(bn_solver)\n \n return bn_solvers, solver, batch_sizes\n\nbatch_sizes = [5,10,50]\nbn_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('batchnorm')\n```\n\n No normalization: batch size = 5\n Normalization: batch size = 5\n Normalization: batch size = 10\n Normalization: batch size = 50\n\n\n\n```python\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Batch Normalization)','Epoch', solver_bsize, bn_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 2:\nDescribe the results of this experiment. What does this imply about the relationship between batch normalization and batch size? Why is this relationship observed?\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization\nBatch normalization has proved to be effective in making networks easier to train, but the dependency on batch size makes it less useful in complex networks which have a cap on the input batch size due to hardware limitations. \n\nSeveral alternatives to batch normalization have been proposed to mitigate this problem; one such technique is Layer Normalization [2]. Instead of normalizing over the batch, we normalize over the features. In other words, when using Layer Normalization, each feature vector corresponding to a single datapoint is normalized based on the sum of all terms within that feature vector.\n\n[2] [Ba, Jimmy Lei, Jamie Ryan Kiros, and Geoffrey E. Hinton. \"Layer Normalization.\" stat 1050 (2016): 21.](https://arxiv.org/pdf/1607.06450.pdf)\n\n## Inline Question 3:\nWhich of these data preprocessing steps is analogous to batch normalization, and which is analogous to layer normalization?\n\n1. Scaling each image in the dataset, so that the RGB channels for each row of pixels within an image sums up to 1.\n2. Scaling each image in the dataset, so that the RGB channels for all pixels within an image sums up to 1. \n3. Subtracting the mean image of the dataset from each image in the dataset.\n4. Setting all RGB values to either 0 or 1 depending on a given threshold.\n\n## Answer:\n[FILL THIS IN]\n\n\n# Layer Normalization: Implementation\n\nNow you'll implement layer normalization. This step should be relatively straightforward, as conceptually the implementation is almost identical to that of batch normalization. One significant difference though is that for layer normalization, we do not keep track of the moving moments, and the testing phase is identical to the training phase, where the mean and variance are directly calculated per datapoint.\n\nHere's what you need to do:\n\n* In `cs231n/layers.py`, implement the forward pass for layer normalization in the function `layernorm_forward`. \n\nRun the cell below to check your results.\n* In `cs231n/layers.py`, implement the backward pass for layer normalization in the function `layernorm_backward`. \n\nRun the second cell below to check your results.\n* Modify `cs231n/classifiers/fc_net.py` to add layer normalization to the `FullyConnectedNet`. When the `normalization` flag is set to `\"layernorm\"` in the constructor, you should insert a layer normalization layer before each ReLU nonlinearity. \n\nRun the third cell below to run the batch size experiment on layer normalization.\n\n\n```python\n# Check the training-time forward pass by checking means and variances\n# of features both before and after layer normalization.\n\n# Simulate the forward pass for a two-layer network.\nnp.random.seed(231)\nN, D1, D2, D3 =4, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before layer normalization:')\nprint_mean_std(a,axis=1)\n\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\n\n# Means should be close to zero and stds close to one.\nprint('After layer normalization (gamma=1, beta=0)')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n\ngamma = np.asarray([3.0,3.0,3.0])\nbeta = np.asarray([5.0,5.0,5.0])\n\n# Now means should be close to beta and stds close to gamma.\nprint('After layer normalization (gamma=', gamma, ', beta=', beta, ')')\na_norm, _ = layernorm_forward(a, gamma, beta, {'mode': 'train'})\nprint_mean_std(a_norm,axis=1)\n```\n\n Before layer normalization:\n means: [-59.06673243 -47.60782686 -43.31137368 -26.40991744]\n stds: [10.07429373 28.39478981 35.28360729 4.01831507]\n \n After layer normalization (gamma=1, beta=0)\n means: [ 4.81096644e-16 -7.40148683e-17 2.22044605e-16 -5.92118946e-16]\n stds: [0.99999995 0.99999999 1. 0.99999969]\n \n After layer normalization (gamma= [3. 3. 3.] , beta= [5. 5. 5.] )\n means: [5. 5. 5. 5.]\n stds: [2.99999985 2.99999998 2.99999999 2.99999907]\n \n\n\n\n```python\n# Gradient check batchnorm backward pass.\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nln_param = {}\nfx = lambda x: layernorm_forward(x, gamma, beta, ln_param)[0]\nfg = lambda a: layernorm_forward(x, a, beta, ln_param)[0]\nfb = lambda b: layernorm_forward(x, gamma, b, ln_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = layernorm_forward(x, gamma, beta, ln_param)\ndx, dgamma, dbeta = layernorm_backward(dout, cache)\n\n# You should expect to see relative errors between 1e-12 and 1e-8.\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))\n```\n\n dx error: 1.433615657860454e-09\n dgamma error: 4.519489546032799e-12\n dbeta error: 2.276445013433725e-12\n\n\n# Layer Normalization and Batch Size\n\nWe will now run the previous batch size experiment with layer normalization instead of batch normalization. Compared to the previous experiment, you should see a markedly smaller influence of batch size on the training history!\n\n\n```python\nln_solvers_bsize, solver_bsize, batch_sizes = run_batchsize_experiments('layernorm')\n\nplt.subplot(2, 1, 1)\nplot_training_history('Training accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.train_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\nplt.subplot(2, 1, 2)\nplot_training_history('Validation accuracy (Layer Normalization)','Epoch', solver_bsize, ln_solvers_bsize, \\\n lambda x: x.val_acc_history, bl_marker='-^', bn_marker='-o', labels=batch_sizes)\n\nplt.gcf().set_size_inches(15, 10)\nplt.show()\n```\n\n## Inline Question 4:\nWhen is layer normalization likely to not work well, and why?\n\n1. Using it in a very deep network\n2. Having a very small dimension of features\n3. Having a high regularization term\n\n\n## Answer:\n[FILL THIS IN]\n\n", "meta": {"hexsha": "5f868446986623e27760082954b3b1ebeadffba1", "size": 429949, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "assignments/2021/assignment2/BatchNormalization.ipynb", "max_stars_repo_name": "Michellemingxuan/stanford_cs231n", "max_stars_repo_head_hexsha": "b1d0a5a4a3b2fe5d685e34a4ebd810cbc56ec143", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignments/2021/assignment2/BatchNormalization.ipynb", "max_issues_repo_name": "Michellemingxuan/stanford_cs231n", "max_issues_repo_head_hexsha": "b1d0a5a4a3b2fe5d685e34a4ebd810cbc56ec143", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignments/2021/assignment2/BatchNormalization.ipynb", "max_forks_repo_name": "Michellemingxuan/stanford_cs231n", "max_forks_repo_head_hexsha": "b1d0a5a4a3b2fe5d685e34a4ebd810cbc56ec143", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 429949.0, "max_line_length": 429949, "alphanum_fraction": 0.9350667172, "converted": true, "num_tokens": 9493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.15439971760091342}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n[Python for Probability, Statistics, and Machine Learning](https://www.springer.com/fr/book/9783319307152)\n\n\n```python\nfrom __future__ import division\n%pylab inline\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\nIt is sometimes very difficult to unequivocally attribute outcomes to causal\nfactors. For example, did your experiment generate the outcome you were hoping\nfor or not? Maybe something did happen, but the effect is not pronounced\nenough to separate it from inescapable measurement errors or other\nfactors in the ambient environment? Hypothesis testing is a powerful\nstatistical method to address these questions. Let's begin by again\nconsidering our coin-tossing experiment with unknown parameter $p$. Recall\nthat the individual coin-flips are Bernoulli distributed. The first step is\nto establish separate hypotheses. First, $H_0$ is the so-called null\nhypothesis. In our case this can be\n\n$$\nH_0 \\colon \\theta < \\frac{1}{2}\n$$\n\n and the alternative hypothesis is then\n\n$$\nH_1 \\colon \\theta \\geq \\frac{1}{2}\n$$\n\n With this set up, the question now boils down to figuring out which\nhypothesis the data is most consistent with. To choose between these, we need\na statistical test that is a function, $G$, of the sample set\n$\\mathbf{X}_n=\\left\\{ X_i \\right\\}_n $ into the real line, where $X_i$ is the\nheads or tails outcome ($X_i \\in \\lbrace 0,1 \\rbrace$). In other words, we\ncompute $G(\\mathbf{X}_n)$ and check if it exceeds a threshold $c$. If not, then\nwe declare $H_0$ (otherwise, declare $H_1$). Notationally, this is the\nfollowing:\n\n$$\n\\begin{align*}\n G(\\mathbf{X}_n) < c & \\Rightarrow H_0 \\\\\\\n G(\\mathbf{X}_n) \\geq c & \\Rightarrow H_1\n\\end{align*}\n$$\n\n In summary, we have the observed data $\\mathbf{X}_n$ and a function\n$G$ that maps that data onto the real line. Then, using the\nconstant $c$ as a threshold, the inequality effectively divides the real line\ninto two parts, one corresponding to each of the hypotheses.\n\nWhatever this test $G$ is, it will make mistakes of two types --- false\nnegatives and false positives. The false positives arise from the case where we\ndeclare $H_0$ when the test says we should declare $H_1$. This is\nsummarized in the Table ref{tbl:decision}.\n\n\n
\n\n$$\n\\begin{table}\n\\footnotesize\n\\centering\n\\begin{tabular}{l|p{1.3in}|p{1.3in}}\n\\multicolumn{1}{c}{ } & \\multicolumn{1}{c}{Declare $H_0$ } & \\multicolumn{1}{c}{ Declare $H_1$ } \\\\\n\\hline\n$H_0\\:$ True & Correct & False positive (Type I error) \\\\\n$H_1\\:$ True & False negative (Type II error) & Correct (true-detect) \\\\\n\\hline\n\\end{tabular}\n\\caption{Truth table for hypotheses testing.}\n\\label{tbl:decision} \\tag{1}\n\\end{table}\n$$\n\n For this example, here are the false positives (aka false alarms):\n\n$$\nP_{FA} = \\mathbb{P}\\left( G(\\mathbf{X}_n) > c \\mid \\theta \\leq \\frac{1}{2} \\right)\n$$\n\n Or, equivalently,\n\n$$\nP_{FA} = \\mathbb{P}\\left( G(\\mathbf{X}_n) > c \\mid H_0 \\right)\n$$\n\n Likewise, the other error is a false negative, which we can write\nanalogously as\n\n$$\nP_{FN} = \\mathbb{P}\\left( G(\\mathbf{X}_n) < c \\vert H_1\\right)\n$$\n\n By choosing some acceptable values for either of these errors,\nwe can solve for the other one. The practice is usually to pick a value of\n$P_{FA}$ and then find the corresponding value of $P_{FN}$. Note that it is\ntraditional in engineering to speak about *detection probability*, which is\ndefined as\n\n$$\nP_{D} = 1- P_{FN} = \\mathbb{P}\\left( G(\\mathbf{X}_n) > c \\mid H_1\\right)\n$$\n\n In other words, this is the probability of declaring $H_1$ when the\ntest exceeds the threshold. This is otherwise known as the *probability of a\ntrue detection* or *true-detect*.\n\n## Back to the Coin Flipping Example\n\nIn our previous maximum likelihood discussion, we wanted to derive an\nestimator for the *value* of the probability of heads for the coin\nflipping experiment. For hypthesis testing, we want to ask a softer\nquestion: is the probability of heads greater or less than $\\nicefrac{1}{2}$? As we\njust established, this leads to the two hypotheses:\n\n$$\nH_0 \\colon \\theta < \\frac{1}{2}\n$$\n\n versus,\n\n$$\nH_1 \\colon \\theta > \\frac{1}{2}\n$$\n\n Let's assume we have five observations. Now we need the $G$ function\nand a threshold $c$ to help pick between the two hypotheses. Let's count the\nnumber of heads observed in five observations as our\ncriterion. Thus, we have\n\n$$\nG(\\mathbf{X}_5) := \\sum_{i=1}^5 X_i\n$$\n\n and, suppose further that we pick $H_1$ only if exactly five out of\nfive observations are heads. We'll call this the *all-heads* test.\n\nNow, because all of the $X_i$ are random variables, so is $G$ and we must\nfind the corresponding probability mass function for $G$. Assuming the\nindividual coin tosses are independent, the probability of five heads is $\\theta^5$.\nThis means that the probability of rejecting the $H_0$ hypothesis (and choosing\n$H_1$, because there are only two choices here) based on the unknown underlying\nprobability is $\\theta^5$. In the parlance, this is known and the *power function*\nas in denoted by $\\beta$ as in\n\n$$\n\\beta(\\theta) = \\theta^5\n$$\n\n Let's get a quick plot this in [Figure](#fig:Hypothesis_testing_001).\n\n\n\n\n```python\n%matplotlib inline\n\nfrom matplotlib.pylab import subplots\nimport numpy as np\nfig,ax=subplots()\nfig.set_size_inches((6,3))\nxi = np.linspace(0,1,50)\n_=ax.plot(xi, (xi)**5,'-k',label='all heads')\n_=ax.set_xlabel(r'$\\theta$',fontsize=22)\n_=ax.plot(0.5,(0.5)**5,'ko')\nfig.tight_layout()\n#fig.savefig('fig-statistics/Hypothesis_Testing_001.png')\n```\n\n\n\n
\n\n

Power function for the all-heads test. The dark circle indicates the value of the function indicating $\\alpha$.

\n\n\n\n\n\n Now, we have the following false alarm probability,\n\n$$\nP_{FA} = \\mathbb{P}( G(\\mathbf{X}_n)= 5 \\vert H_0) =\\mathbb{P}( \\theta^5 \\vert H_0)\n$$\n\n Notice that this is a function of $\\theta$, which means there are\nmany false alarm probability values that correspond to this test. To be on the\nconservative side, we'll pick the supremum (i.e., maximum) of this function,\nwhich is known as the *size* of the test, traditionally denoted by $\\alpha$,\n\n$$\n\\alpha = \\sup_{\\theta \\in \\Theta_0} \\beta(\\theta)\n$$\n\n with domain $\\Theta_0 = \\lbrace \\theta < 1/2 \\rbrace$ which in our case is\n\n$$\n\\alpha = \\sup_{\\theta < \\frac{1}{2}} \\theta^5 = \\left(\\frac{1}{2}\\right)^5 = 0.03125\n$$\n\n Likewise, for the detection probability,\n\n$$\n\\mathbb{P}_{D}(\\theta) = \\mathbb{P}( \\theta^5 \\vert H_1)\n$$\n\n which is again a function of the parameter $\\theta$. The problem with\nthis test is that the $P_{D}$ is pretty low for most of the domain of\n$\\theta$. For instance, values in the nineties for $P_{D}$\nonly happen when $\\theta > 0.98$. In other words, if the coin produces\nheads 98 times out of 100, then we can detect $H_1$ reliably. Ideally, we want\na test that is zero for the domain corresponding to $H_0$ (i.e., $\\Theta_0$) and\nequal to one otherwise. Unfortunately, even if we increase the length of the\nobserved sequence, we cannot escape this effect with this test. You can try\nplotting $\\theta^n$ for larger and larger values of $n$ to see this.\n\n### Majority Vote Test\n\nDue to the problems with the detection probability in the all-heads test, maybe\nwe can think of another test that will have the performance we want? Suppose we\nreject $H_0$ if the majority of the observations are heads. Then, using the\nsame reasoning as above, we have\n\n$$\n\\beta(\\theta) = \\sum_{k=3}^5 \\binom{5}{k} \\theta^k(1-\\theta)^{5-k}\n$$\n\n[Figure](#fig:Hypothesis_testing_002) shows the power function\nfor both the majority vote and the all-heads tests.\n\n\n```python\nfig,ax=subplots()\nfig.set_size_inches((6,3))\nfrom sympy.abc import theta,k # get some variable symbols\nimport sympy as S\nxi = np.linspace(0,1,50)\nexpr=S.Sum(S.binomial(5,k)*theta**(k)*(1-theta)**(5-k),(k,3,5)).doit()\n_=ax.plot(xi, (xi)**5,'-k',label='all heads')\n_=ax.plot(xi, S.lambdify(theta,expr)(xi),'--k',label='majority vote')\n_=ax.plot(0.5, (0.5)**5,'ko')\n_=ax.plot(0.5, S.lambdify(theta,expr)(0.5),'ko')\n_=ax.set_xlabel(r'$\\theta$',fontsize=22)\n_=ax.legend(loc=0)\nfig.tight_layout()\n#fig.savefig('fig-statistics/Hypothesis_Testing_002.png')\n```\n\n\n\n
\n\n

Compares the power function for the all-heads test with that of the majority-vote test.

\n\n\n\n\n\n In this case, the new test has *size*\n\n$$\n\\alpha = \\sup_{\\theta < \\frac{1}{2}} \\theta^{5} + 5 \\theta^{4} \\left(- \\theta + 1\\right) + 10 \\theta^{3} \\left(- \\theta + 1\\right)^{2} = \\frac{1}{2}\n$$\n\n As before we only get to upwards of 90% for detection\nprobability only when the underlying parameter $\\theta > 0.75$. \nLet's see what happens when we consider more than five samples. For\nexample, let's suppose that we have $n=100$ samples and we want to\nvary the threshold for the majority vote test. For example, let's have\na new test where we declare $H_1$ when $k=60$ out of the 100 trials\nturns out to be heads. What is the $\\beta$ function in this case?\n\n$$\n\\beta(\\theta) = \\sum_{k=60}^{100} \\binom{100}{k} \\theta^k(1-\\theta)^{100-k}\n$$\n\n This is too complicated to write by hand, but the statistics module\nin Sympy has all the tools we need to compute this.\n\n\n```python\n>>> from sympy.stats import P, Binomial\n>>> theta = S.symbols('theta',real=True)\n>>> X = Binomial('x',100,theta)\n>>> beta_function = P(X>60)\n>>> print beta_function.subs(theta,0.5) # alpha\n0.0176001001088524\n>>> print beta_function.subs(theta,0.70) \n0.979011423996075\n```\n\n 0.0176001001088524\n 0.979011423996075\n\n\n\n\n\n 0.979011423996075\n\n\n\n These results are much better than before because the $\\beta$\nfunction is much steeper. If we declare $H_1$ when we observe 60 out of 100\ntrials are heads, then we wrongly declare heads approximately 1.8% of the\ntime. Otherwise, if it happens that the true value for $p>0.7$, we will\nconclude correctly approximately 97% of the time. A quick simulation can sanity\ncheck these results as shown below:\n\n\n```python\nfrom scipy import stats\nrv=stats.bernoulli(0.5) # true p = 0.5\n# number of false alarms ~ 0.018\nprint sum(rv.rvs((1000,100)).sum(axis=1)>60)/1000.\n```\n\n 0.016\n\n\n The above code is pretty dense so let's unpack it. In the first line, we use the `scipy.stats` module to define the\nBernoulli random variable for the coin flip. Then, we use the `rvs` method of\nthe variable to generate 1000 trials of the experiment where each trial\nconsists of 100 coin flips. This generates a $1000 \\times 100$ matrix where the\nrows are the individual trials and the columns are the outcomes of each\nrespective set of 100 coin flips. The `sum(axis=1)` part computes the sum across the\ncolumns. Because the values of the embedded matrix are only `1` or `0` this\ngives us the count of flips that are heads per row. The next `>60` part\ncomputes the boolean 1000-long vector of values that are bigger than 60. The\nfinal `sum` adds these up. Again, because the entries in the array are `True`\nor `False` the `sum` computes the count of times the number of heads has\nexceeded 60 per 100 coin flips in each of 1000 trials. Then, dividing this\nnumber by 1000 gives a quick approximation of false alarm probability we\ncomputed above for this case where the true value of $p=0.5$.\n\n## Receiver Operating Characteristic\n\nBecause the majority vote test is a binary test, we can compute the *Receiver\nOperating Characteristic* (ROC) which is the graph of the $(P_{FA},\nP_D)$. The term comes from radar systems but is a very general method for\nconsolidating all of these issues into a single graph. Let's consider a typical\nsignal processing example with two hypotheses. In $H_0$, there is noise but no\nsignal present at the receiver,\n\n$$\nH_0 \\colon X = \\epsilon\n$$\n\n where $\\epsilon \\sim \\mathcal{N}(0,\\sigma^2)$ represents additive\nnoise. In the alternative hypothesis, there is a deterministic signal at the receiver,\n\n$$\nH_1 \\colon X = \\mu + \\epsilon\n$$\n\n Again, the problem is to choose between these two hypotheses. For\n$H_0$, we have $X \\sim \\mathcal{N}(0,\\sigma^2)$ and for $H_1$, we have $ X \\sim\n\\mathcal{N}(\\mu,\\sigma^2)$. Recall that we only observe values for $x$ and\nmust pick either $H_0$ or $H_1$ from these observations. Thus, we need a\nthreshold, $c$, to compare $x$ against in order to distinguish the two\nhypotheses. [Figure](#fig:Hypothesis_testing_003) shows the probability density\nfunctions under each of the hypotheses. The dark vertical line is the threshold\n$c$. The gray shaded area is the probability of detection, $P_D$ and the shaded\narea is the probability of false alarm, $P_{FA}$. The test evaluates every\nobservation of $x$ and concludes $H_0$ if $x -->\n\n
\n\n

The two density functions for the $H_0$ and $H_1$ hypotheses. The shaded gray area is the detection probability and the shaded blue area is the probability of false alarm. The vertical line is the decision threshold.

\n\n\n\n\n\n**Programming Tip.**\n\nThe shading shown in [Figure](#fig:Hypothesis_testing_003) comes from\nMatplotlib's `fill_between` function. This function has a `where` keyword\nargument to specify which part of the plot to apply shading with specified\n`color` keyword argument. Note there is also a `fill_betweenx` function that\nfills horizontally. The `text` function can place formatted\ntext anywhere in the plot and can utilize basic \\LaTeX{} formatting.\nSee the IPython notebook corresponding to this section for the source code.\n\n\n\nAs we slide the threshold left and right along the horizontal axis, we naturally change the corresponding areas under\neach of the curves shown in [Figure](#fig:Hypothesis_testing_003) and thereby\nchange the values of $P_D$ and $P_{FA}$. The contour that emerges from sweeping\nthe threshold this way is the ROC as shown in [Figure](#fig:Hypothesis_testing_004). This figure also shows the diagonal line which\ncorresponds to making decisions based on the flip of a fair coin. Any\nmeaningful test must do better than coin flipping so the more the ROC bows up\nto the top left corner of the graph, the better. Sometimes ROCs are quantified\ninto a single number called the *area under the curve* (AUC), which varies from\n0.5 to 1.0 as shown. In our example, what separates the two probability density\nfunctions is the value of $\\mu$. In a real situation, this would be determined\nby signal processing methods that include many complicated trade-offs. The key\nidea is that whatever those trade-offs are, the test itself boils down to the\nseparation between these two density functions --- good tests separate the two\ndensity functions and bad tests do not. Indeed, when there is no separation, we\narrive at the diagonal-line coin-flipping situation we just discussed.\n\nWhat values for $P_D$ and $P_{FA}$ are considered *acceptable* depends on the\napplication. For example, suppose you are testing for a fatal disease. It could\nbe that you are willing to except a relatively high $P_{FA}$ value if that\ncorresponds to a good $P_D$ because the test is relatively cheap to administer\ncompared to the alternative of missing a detection. On the other hand,\nmay be a false alarm triggers an expensive response, so that minimizing\nthese alarms is more important than potentially missing a detection. These\ntrade-offs can only be determined by the application and design factors.\n\n\n\n
\n\n

The Receiver Operating Characteristic (ROC) corresponding to [Figure](#fig:Hypothesis_testing_003).

\n\n\n\n\n\n## P-Values\n\nThere are a lot of moving parts in hypothesis testing. What we need\nis a way to consolidate the findings. The idea is that we want to find\nthe minimum level at which the test rejects $H_0$. Thus, the p-value\nis the probability, under $H_0$, that the test-statistic is at least\nas extreme as what was actually observed. Informally, this means\nthat smaller values imply that $H_0$ should be rejected, although\nthis doesn't mean that large values imply that $H_0$ should be\nretained. This is because a large p-value can arise from either $H_0$\nbeing true or the test having low statistical power.\n\nIf $H_0$ is true, the p-value is uniformly distributed in the interval $(0,1)$.\nIf $H_1$ is true, the distribution of the p-value will concentrate closer to\nzero. For continuous distributions, this can be proven rigorously and implies\nthat if we reject $H_0$ when the corresponding p-value is less than $\\alpha$,\nthen the probability of a false alarm is $\\alpha$. Perhaps it helps to\nformalize this a bit before computing it. Suppose $\\tau(X)$ is a test\nstatistic that rejects $H_0$ as it gets bigger. Then, for each sample $x$,\ncorresponding to the data we actually have on-hand, we define\n\n$$\np(x) = \\sup_{\\theta \\in \\Theta_0} \\mathbb{P}_{\\theta}(\\tau(X) > \\tau(x))\n$$\n\n This equation states that the supremum (i.e., maximum)\nprobability that the test statistic, $\\tau(X)$, exceeds the value for\nthe test statistic on this particular data ($\\tau(x)$) over the\ndomain $\\Theta_0$ is defined as the p-value. Thus, this embodies a\nworst-case scenario over all values of $\\theta$.\n\nHere's one way to think about this. Suppose you rejected $H_0$, and someone\nsays that you just got *lucky* and somehow just drew data that happened to\ncorrespond to a rejection of $H_0$. What p-values provide is a way to address\nthis by capturing the odds of just a favorable data-draw. Thus, suppose that\nyour p-value is 0.05. Then, what you are showing is that the odds of just\ndrawing that data sample, given $H_0$ is in force, is just 5%. This means that\nthere's a 5% chance that you somehow lucked out and got a favorable draw of\ndata.\n\nLet's make this concrete with an example. Given, the majority-vote rule above,\nsuppose we actually do observe three of five heads. Given the $H_0$, the\nprobability of observing this event is the following:\n\n$$\np(x) =\\sup_{\\theta \\in \\Theta_0} \\sum_{k=3}^5\\binom{5}{k} \\theta^k(1-\\theta)^{5-k} = \\frac{1}{2}\n$$\n\n For the all-heads test, the corresponding computation is the following:\n\n$$\np(x) =\\sup_{\\theta \\in \\Theta_0} \\theta^5 = \\frac{1}{2^5} = 0.03125\n$$\n\nFrom just looking at these p-values, you might get the feeling that the second\ntest is better, but we still have the same detection probability issues we\ndiscussed above; so, p-values help in summarizing some aspects of our\nhypothesis testing, but they do *not* summarize all the salient aspects of the\n*entire* situation.\n\n## Test Statistics\n\nAs we have seen, it is difficult to derive good test statistics for hypothesis\ntesting without a systematic process. The Neyman-Pearson Test is derived from\nfixing a false-alarm value ($\\alpha$) and then maximizing the detection\nprobability. This results in the Neyman-Pearson Test,\n\n$$\nL(\\mathbf{x}) = \\frac{f_{X|H_1}(\\mathbf{x})}{f_{X|H_0}(\\mathbf{x})} \\stackrel[H_0]{H_1}{\\gtrless} \\gamma\n$$\n\n where $L$ is the likelihood ratio and where the threshold\n$\\gamma$ is chosen such that\n\n$$\n\\int_{x:L(\\mathbf{x})>\\gamma} f_{X|H_0}(\\mathbf{x}) d\\mathbf{x}=\\alpha\n$$\n\n The Neyman-Pearson Test is one of a family of tests that use\nthe likelihood ratio.\n\n**Example.** Suppose we have a receiver and we want to distinguish\nwhether just noise ($H_0$) or signal pluse noise ($H_1$) is received.\nFor the noise-only case, we have $x\\sim \\mathcal{N}(0,1)$ and for the\nsignal pluse noise case we have $x\\sim \\mathcal{N}(1,1)$. In other\nwords, the mean of the distribution shifts in the presence of the\nsignal. This is a very common problem in signal processing and\ncommunications. The Neyman-Pearson Test then boils down to the\nfollowing,\n\n$$\nL(x)= e^{-\\frac{1}{2}+x}\\stackrel[H_0]{H_1}{\\gtrless}\\gamma\n$$\n\n Now we have to find the threshold $\\gamma$ that solves the\nmaximization problem that characterizes the Neyman-Pearson Test. Taking\nthe natural logarithm and re-arranging gives,\n\n$$\nx\\stackrel[H_0]{H_1}{\\gtrless} \\frac{1}{2}+\\log\\gamma\n$$\n\n The next step is find $\\gamma$ corresponding to the desired\n$\\alpha$ by computing it from the following,\n\n$$\n\\int_{1/2+\\log\\gamma}^{\\infty} f_{X|H_0}(x)dx = \\alpha\n$$\n\n For example, taking $\\alpha=1/100$, gives\n$\\gamma\\approx 6.21$. To summarize the test in this case, we have,\n\n$$\nx\\stackrel[H_0]{H_1}{\\gtrless} 2.32\n$$\n\n Thus, if we measure $X$ and see that its value\nexceeds the threshold above, we declare $H_1$ and otherwise\ndeclare $H_0$. The following code shows how to\nsolve this example using Sympy and Scipy. First, we\nset up the likelihood ratio,\n\n\n```python\nimport sympy as S\nfrom sympy import stats\ns = stats.Normal('s',1,1) # signal+noise\nn = stats.Normal('n',0,1) # noise\nx = S.symbols('x',real=True)\nL = stats.density(s)(x)/stats.density(n)(x)\n```\n\n Next, to find the $\\gamma$ value,\n\n\n```python\ng = S.symbols('g',positive=True) # define gamma\nv=S.integrate(stats.density(n)(x),\n (x,S.Rational(1,2)+S.log(g),S.oo))\n```\n\n**Programming Tip.**\n\nProviding additional information regarding the Sympy variable by using the\nkeyword argument `positive=True` helps the internal simplification algorithms\nwork faster and better. This is especially useful when dealing with complicated\nintegrals that involve special functions. Furthermore, note that we used the\n`Rational` function to define the `1/2` fraction, which is another way of\nproviding hints to Sympy. Otherwise, it's possible that the floating-point\nrepresentation of the fraction could disguise the simple fraction and\nthereby miss internal simplification opportunities.\n\n\n\n We want to solve for `g` in the above expression. Sympy has some\nbuilt-in numerical solvers as in the following,\n\n\n```python\nprint S.nsolve(v-0.01,3.0) # approx 6.21\n```\n\n 6.21116124253284\n\n\n Note that in this situation it is better to use the numerical\nsolvers because Sympy `solve` may grind along for a long time to\nresolve this.\n\n### Generalized Likelihood Ratio Test\n\nThe likelihood ratio test can be generalized using the following statistic,\n\n$$\n\\Lambda(\\mathbf{x})= \\frac{\\sup_{\\theta\\in\\Theta_0} L(\\theta)}{\\sup_{\\theta\\in\\Theta} L(\\theta)}=\\frac{L(\\hat{\\theta}_0)}{L(\\hat{\\theta})}\n$$\n\n where $\\hat{\\theta}_0$ maximizes $L(\\theta)$ subject to\n$\\theta\\in\\Theta_0$ and $\\hat{\\theta}$ is the maximum likelihood estimator.\nThe intuition behind this generalization of the Likelihood Ratio Test is that\nthe denomimator is the usual maximum likelihood estimator and the numerator is\nthe maximum likelihood estimator, but over a restricted domain ($\\Theta_0$).\nThis means that the ratio is always less than unity because the maximum\nlikelihood estimator over the entire space will always be at least as maximal\nas that over the more restricted space. When this $\\Lambda$ ratio gets small\nenough, it means that the maximum likelihood estimator over the entire domain\n($\\Theta$) is larger which means that it is safe to reject the null hypothesis\n$H_0$. The tricky part is that the statistical distribution of $\\Lambda$ is\nusually eye-wateringly difficult. Fortunately, Wilks Theorem says that with\nsufficiently large $n$, the distribution of $-2\\log\\Lambda$ is approximately\nchi-square with $r-r_0$ degrees of freedom, where $r$ is the number of free\nparameters for $\\Theta$ and $r_0$ is the number of free parameters in\n$\\Theta_0$. With this result, if we want an approximate test at level\n$\\alpha$, we can reject $H_0$ when $-2\\log\\Lambda \\ge \\chi^2_{r-r_0}(\\alpha)$\nwhere $\\chi^2_{r-r_0}(\\alpha)$ denotes the $1-\\alpha$ quantile of the\n$\\chi^2_{r-r_0}$ chi-square distribution. However, the problem with this\nresult is that there is no definite way of knowing how big $n$ should be. The\nadvantage of this generalized likelihood ratio test is that it \ncan test multiple hypotheses simultaneously, as illustrated\nin the following example.\n\n**Example.** Let's return to our coin-flipping example, except now we have\nthree different coins. The likelihood function is then,\n\n$$\nL(p_1,p_2,p_3) = \\texttt{binom}(k_1;n_1,p_1)\\texttt{binom}(k_2;n_2,p_2)\\texttt{binom}(k_3;n_3,p_3)\n$$\n\n where $\\texttt{binom}$ is the binomial distribution with \nthe given parameters. For example,\n\n$$\n\\texttt{binom}(k;n,p) =\\sum_{k=0}^n \\binom{n}{k} p^k(1-p)^{n-k}\n$$\n\n The null hypothesis is that all three coins have the\nsame probability of heads, $H_0:p=p_1=p_2=p_3$. The alternative hypothesis is\nthat at least one of these probabilites is different. Let's consider the\nnumerator of the $\\Lambda$ first, which will give us the maximum likelihood\nestimator of $p$. Because the null hypothesis is that all the $p$ values are\nequal, we can just treat this as one big binomial distribution with\n$n=n_1+n_2+n_3$ and $k=k_1+k_2+k_3$ is the total number of heads observed for\nany coin. Thus, under the null hypothesis, the distribution of $k$ is binomial\nwith parameters $n$ and $p$. Now, what is the maximum likelihood estimator for\nthis distribution? We have worked this problem before and have the following,\n\n$$\n\\hat{p}_0= \\frac{k}{n}\n$$\n\n In other words, the maximum likelihood estimator under the null\nhypothesis is the proportion of ones observed in the sequence of $n$ trials\ntotal. Now, we have to substitute this in for the likelihood under the null\nhypothesis to finish the numerator of $\\Lambda$,\n\n$$\nL(\\hat{p}_0,\\hat{p}_0,\\hat{p}_0) = \\texttt{binom}(k_1;n_1,\\hat{p}_0)\\texttt{binom}(k_2;n_2,\\hat{p}_0)\\texttt{binom}(k_3;n_3,\\hat{p}_0)\n$$\n\nFor the denomimator of $\\Lambda$, which represents the case of maximizing over\nthe entire space, the maximum likelihood estimator for each separate binomial\ndistribution is likewise,\n\n$$\n\\hat{p}_i= \\frac{k_i}{n_i}\n$$\n\n which makes the likelihood in the denominator the following,\n\n$$\nL(\\hat{p}_1,\\hat{p}_2,\\hat{p}_3) = \\texttt{binom}(k_1;n_1,\\hat{p}_1)\\texttt{binom}(k_2;n_2,\\hat{p}_2)\\texttt{binom}(k_3;n_3,\\hat{p}_3)\n$$\n\n for each of the $i\\in \\lbrace 1,2,3 \\rbrace$ binomial distributions. Then, the\n$\\Lambda$ statistic is then the following,\n\n$$\n\\Lambda(k_1,k_2,k_3) = \\frac{L(\\hat{p}_0,\\hat{p}_0,\\hat{p}_0)}{L(\\hat{p}_1,\\hat{p}_2,\\hat{p}_3)}\n$$\n\n Wilks theorems states that $-2\\log\\Lambda$ is chi-square\ndistributed. We can compute this example with the statistics tools in Sympy and\nScipy.\n\n\n```python\nfrom scipy.stats import binom, chi2\nimport numpy as np\n# some sample parameters\np0,p1,p2 = 0.3,0.4,0.5\nn0,n1,n2 = 50,180,200\nbrvs= [ binom(i,j) for i,j in zip((n0,n1,n2),(p0,p1,p2))]\ndef gen_sample(n=1):\n 'generate samples from separate binomial distributions'\n if n==1:\n return [i.rvs() for i in brvs]\n else:\n return [gen_sample() for k in range(n)]\n```\n\n**Programming Tip.**\n\nNote the recursion in the definition of the `gen_sample` function where a\nconditional clause of the function calls itself. This is a quick way to reusing\ncode and generating vectorized output. Using `np.vectorize` is another way, but\nthe code is simple enough in this case to use the conditional clause. In\nPython, it is generally bad for performance to have code with nested recursion\nbecause of how the stack frames are managed. However, here we are only\nrecursing once so this is not an issue.\n\n\n\n Next, we compute the logarithm of the numerator of the $\\Lambda$\nstatistic,\n\n\n```python\nfrom __future__ import division\nnp.random.seed(1234)\n```\n\n\n```python\nk0,k1,k2 = gen_sample()\nprint k0,k1,k2\npH0 = sum((k0,k1,k2))/sum((n0,n1,n2))\nnumer = np.sum([np.log(binom(ni,pH0).pmf(ki)) \n for ni,ki in \n zip((n0,n1,n2),(k0,k1,k2))])\nprint numer\n```\n\n 12 68 103\n -15.5458638366\n\n\n Note that we used the null hypothesis estimate for the $\\hat{p}_0$.\nLikewise, for the logarithm of the denominator we have the following,\n\n\n```python\ndenom = np.sum([np.log(binom(ni,pi).pmf(ki)) \n for ni,ki,pi in \n zip((n0,n1,n2),(k0,k1,k2),(p0,p1,p2))])\nprint denom\n```\n\n -8.42410648079\n\n\n Now, we can compute the logarithm of the $\\Lambda$ statistic as\nfollows and see what the corresponding value is according to Wilks theorem,\n\n\n```python\nchsq=chi2(2)\nlogLambda =-2*(numer-denom)\nprint logLambda\nprint 1- chsq.cdf(logLambda)\n```\n\n 14.2435147116\n 0.000807346708329\n\n\n Because the value reported above is less than the 5% significance\nlevel, we reject the null hypothesis that all the coins have the same\nprobability of heads. Note that there are two degrees of freedom because the\ndifference in the number of parameters between the null hypothesis ($p$) and\nthe alternative ($p_1,p_2,p_3$) is two. We can build a quick Monte\nCarlo simulation to check the probability of detection for this example using\nthe following code, which is just a combination of the last few code blocks,\n\n\n```python\nc= chsq.isf(.05) # 5% significance level\nout = []\nfor k0,k1,k2 in gen_sample(100):\n pH0 = sum((k0,k1,k2))/sum((n0,n1,n2))\n numer = np.sum([np.log(binom(ni,pH0).pmf(ki)) \n for ni,ki in \n zip((n0,n1,n2),(k0,k1,k2))])\n denom = np.sum([np.log(binom(ni,pi).pmf(ki)) \n for ni,ki,pi in \n zip((n0,n1,n2),(k0,k1,k2),(p0,p1,p2))])\n out.append(-2*(numer-denom)>c)\n\nprint np.mean(out) # estimated probability of detection\n```\n\n 0.59\n\n\n The above simulation shows the estimated probability of\ndetection, for this set of example parameters. This relative low\nprobability of detection means that while the test is unlikely (i.e.,\nat the 5% significance level) to mistakenly pick the null hypothesis,\nit is likewise missing many of the $H_1$ cases (i.e., low probability\nof detection). The trade-off between which is more important is up to\nthe particular context of the problem. In some situations, we may\nprefer additional false alarms in exchange for missing fewer $H_1$\ncases.\n\n\n### Permutation Test\n\n\n\n\n\n\n\nThe Permutation Test is good way to test whether or not\nsamples samples come from the same distribution. For example, suppose that\n\n$$\nX_1, X_2, \\ldots, X_m \\sim F\n$$\n\n and also,\n\n$$\nY_1, Y_2, \\ldots, Y_n \\sim G\n$$\n\n That is, $Y_i$ and $X_i$ come from different distributions. Suppose\nwe have some test statistic, for example\n\n$$\nT(X_1,\\ldots,X_m,Y_1,\\ldots,Y_n) = \\vert\\overline{X}-\\overline{Y}\\vert\n$$\n\n Under the null hypothesis for which $F=G$, any of the\n$(n+m)!$ permutations are equally likely. Thus, suppose for\neach of the $(n+m)!$ permutations, we have the computed\nstatistic,\n\n$$\n\\lbrace T_1,T_2,\\ldots,T_{(n+m)!} \\rbrace\n$$\n\n Then, under the null hypothesis, each of these values is equally\nlikely. The distribution of $T$ under the null hypothesis is the *permutation\ndistribution* that puts weight $1/(n+m)!$ on each $T$-value. Suppose $t_o$ is\nthe observed value of the test statistic and assume that large $T$ rejects the\nnull hypothesis, then the p-value for the permutation test is the following,\n\n$$\nP(T>t_o)= \\frac{1}{(n+m)!} \\sum_{j=1}^{(n+m)!} I(T_j>t_o)\n$$\n\n where $I()$ is the indicator function. For large $(n+m)!$, we can\nsample randomly from the set of all permutations to estimate this p-value.\n\n**Example.** Let's return to our coin-flipping example from last time, but\nnow we have only two coins. The hypothesis is that both coins\nhave the same probability of heads. We can use the built-in\nfunction in Numpy to compute the random permutations.\n\n\n```python\nx=binom(10,0.3).rvs(5) # p=0.3\ny=binom(10,0.5).rvs(3) # p=0.5\nz = np.hstack([x,y]) # combine into one array\nt_o = abs(x.mean()-y.mean()) \nout = [] # output container\nfor k in range(1000):\n perm = np.random.permutation(z)\n T=abs(perm[:len(x)].mean()-perm[len(x):].mean())\n out.append((T>t_o))\n\nprint 'p-value = ', np.mean(out)\n```\n\n p-value = 0.0\n\n\n Note that the size of total permutation space is\n$8!=40320$ so we are taking relatively few (i.e., 100) random\npermutations from this space.\n\n### Wald Test\n\nThe Wald Test is an asympotic test. Suppose we have $H_0:\\theta=\\theta_0$ and\notherwise $H_1:\\theta\\ne\\theta_0$, the corresponding statistic is defined as\nthe following,\n\n$$\nW=\\frac{\\hat{\\theta}_n-\\theta_0}{\\texttt{se}}\n$$\n\n where $\\hat{\\theta}$ is the maximum likelihood estimator and\n$\\texttt{se}$ is the standard error,\n\n$$\n\\texttt{se} = \\sqrt{\\mathbb{V}(\\hat{\\theta}_n)}\n$$\n\n Under general conditions, $W\\overset{d}{\\to} \\mathcal{N}(0,1)$.\nThus, an asympotic test at level $\\alpha$ rejects when $\\vert W\\vert>\nz_{\\alpha/2}$ where $z_{\\alpha/2}$ corresponds to $\\mathbb{P}(\\vert\nZ\\vert>z_{\\alpha/2})=\\alpha$ with $Z \\sim \\mathcal{N}(0,1)$. For our favorite\ncoin-flipping example, if $H_0:\\theta=\\theta_0$, then\n\n$$\nW = \\frac{\\hat{\\theta}-\\theta_0}{\\sqrt{\\hat{\\theta}(1-\\hat{\\theta})/n}}\n$$\n\n We can simulate this using the following code at the usual\n5% significance level,\n\n\n```python\nfrom scipy import stats\ntheta0 = 0.5 # H0\nk=np.random.binomial(1000,0.3)\ntheta_hat = k/1000. # MLE\nW = (theta_hat-theta0)/np.sqrt(theta_hat*(1-theta_hat)/1000)\nc = stats.norm().isf(0.05/2) # z_{alpha/2}\nprint abs(W)>c # if true, reject H0\n```\n\n True\n\n\n This rejects $H_0$ because the true $\\theta=0.3$ and the null hypothesis\nis that $\\theta=0.5$. Note that $n=1000$ in this case which puts us well inside the\nasympotic range of the result. We can re-do this example to estimate\nthe detection probability for this example as in the following code,\n\n\n```python\ntheta0 = 0.5 # H0\nc = stats.norm().isf(0.05/2.) # z_{alpha/2}\nout = []\nfor i in range(100):\n k=np.random.binomial(1000,0.3)\n theta_hat = k/1000. # MLE\n W = (theta_hat-theta0)/np.sqrt(theta_hat*(1-theta_hat)/1000.)\n out.append(abs(W)>c) # if true, reject H0\n\nprint np.mean(out) # detection probability\n```\n\n 1.0\n\n\n## Testing Multiple Hypotheses\n\nThus far, we have focused primarily on two competing hypotheses. Now, we\nconsider multiple comparisons. The general situation is the following. We test\nthe null hypothesis against a sequence of $n$ competing hypotheses $H_k$. We\nobtain p-values for each hypothesis so now we have multiple p-values to\nconsider $\\lbrace p_k \\rbrace$. To boil this sequence down to a single\ncriterion, we can make the following argument. Given $n$ independent hypotheses\nthat are all untrue, the probability of getting at least one false alarm is the\nfollowing,\n\n$$\nP_{FA} = 1-(1-p_0)^n\n$$\n\n where $p_0$ is the individual p-value threshold (say, 0.05). The\nproblem here is that $P_{FA}\\rightarrow 1$ as $n\\rightarrow\\infty$. If we want\nto make many comparisons at once and control the overall false alarm rate the\noverall p-value should be computed under the assumption that none of the\ncompeting hypotheses is valid. The most common way to address this is with the\nBonferroni correction which says that the individual significance level should\nbe reduced to $p/n$. Obviously, this makes it much harder to declare\nsignificance for any particular hypothesis. The natural consequence of this\nconservative restriction is to reduce the statistical power of the experiment,\nthus making it more likely the true effects will be missed.\n\nIn 1995, Benjamini and Hochberg devised a simple method that tells which\np-values are statistically significant. The procedure is to sort the list of\np-values in ascending order, choose a false-discovery rate (say, $q$), and then\nfind the largest p-value in the sorted list such that $p_k \\le k q/n$, where\n$k$ is the p-value's position in the sorted list. Finally, declare that $p_k$\nvalue and all the others less than it statistically significant. This procedure\nguarantees that the proportion of false-positives is less than $q$ (on\naverage). The Benjamini-Hochberg procedure (and its derivatives) is fast and\neffective and is widely used for testing hundreds of primarily false hypotheses\nwhen studying genetics or diseases. Additionally, this\nprocedure provides better statistical power than the Bonferroni correction.\n\n\n\n\n\n\n\n\nIn this section, we discussed the structure of statistical hypothesis testing\nand defined the various terms that are commonly used for this process, along\nwith the illustrations of what they mean in our running coin-flipping example.\nFrom an engineering standpoint, hypothesis testing is not as common as\nconfidence-intervals and point estimates. On the other hand, hypothesis testing\nis very common in social and medical science, where one must deal with\npractical constraints that may limit the sample size or other aspects of the\nhypothesis testing rubric. In engineering, we can usually have much more\ncontrol over the samples and models we employ because they are typically\ninanimate objects that can be measured repeatedly and consistently. This is\nobviously not so with human studies, which generally have other ethical and\nlegal considerations.\n", "meta": {"hexsha": "ea9fc47243b93ce83e5659b44cf062289c621b45", "size": 200169, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/statistics/notebooks/Hypothesis_Testing.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/statistics/notebooks/Hypothesis_Testing.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/statistics/notebooks/Hypothesis_Testing.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 111.6391522588, "max_line_length": 114721, "alphanum_fraction": 0.8507061533, "converted": true, "num_tokens": 10876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15367901160492622}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n 100%|██████████| 10000/10000 [00:02<00:00, 4511.50it/s]\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\n```\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\n```\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\n```\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4c4a88a4953d11d67758c6d67ae0f3aa2082f6a0", "size": 325451, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "Ryanglambert/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "03f1a7ef12e189ec524c496ad227d3184dc8b683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "Ryanglambert/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "03f1a7ef12e189ec524c496ad227d3184dc8b683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "Ryanglambert/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "03f1a7ef12e189ec524c496ad227d3184dc8b683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-04-24T21:10:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-24T21:10:49.000Z", "avg_line_length": 309.6584205519, "max_line_length": 89164, "alphanum_fraction": 0.892871738, "converted": true, "num_tokens": 11147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.15360783114514617}} {"text": "```python\n\"\"\"\nIPython Notebook v4.0 para python 2.7\nLibrerías adicionales: numpy, matplotlib\nContenido bajo licencia CC-BY 4.0. Código bajo licencia MIT. (c) Sebastian Flores.\n\"\"\"\n\n# Configuracion para recargar módulos y librerías \n%reload_ext autoreload\n%autoreload 2\n\nfrom IPython.core.display import HTML\n\nHTML(open(\"style/mat281.css\", \"r\").read())\n```\n\n\n\n\n\n\n\n\n\n
\n\n\n
\n




\n# MAT281\n## Aplicaciones de la Matemática en la Ingeniería\n\n### Sebastián Flores\n\nhttps://www.github.com/sebastiandres/mat281\n\n\n## Clase anterior\n\n* Conjeturas razonables\n* Análisis dimensional\n\n## ¿Qué contenido aprenderemos hoy?\n\n* Teorema $\\Pi$\n\n## ¿Porqué aprenderemos ese contenido?\n\n* Teorema $\\Pi$\n\nPorque el análisis dimensional es parte esencial del estudio de un problema. \nPermite reducir un problema complejo a sus mínimos componentes.\n\n## Pregunta crucial\n\n* ¿Porqué en física e ingeniería las potencias de las fórmulas son siempre números enteros? \n* ¿Porqué no existen formulas donde la potencia sea un número irracional?\n\nPorque área y volumen tienen potencias enteras, y las leyes son conservativas. Al integrar sobre un área o volumen, se deben obtener constantes.\n\n## Análisis Dimensional\n\n#### Definición\nAnálisis Dimensional es una forma de\nsimplificar un modelo físico utilizando la necesidad de homogeneidad\ndimensional para disminuir el número de variables.\n\n## Análisis Dimensional\n\n#### Utilidad\n* Chequear las ecuaciones.\n* Analizar problemas que no admiten solución teórica directa.\n* Establecer la importancia relativa de distintos componentes de un fenómeno físico.\n* Presentar e interpretar datos experimentales\n* Diseñar experimentos de laboratorio o numéricos.\n\n#### Análisis Dimensional\n\n## Dimensión vs Unidad\n#### Dimensión\nTipo de cantidad física.\n\n#### Unidad\nForma de asignar valor numérico a una cantidad de dimensión.\n\n#### Preguntas\n* ¿Cuántas dimensiones físicas existen?\n* ¿Cuántas unidades físicas existen?\n\n#### Análisis Dimensional\n## Dimensiones físicas\nExisten 7 dimensiones fundamentales, cuyas unidades básicas\nson definidas por el SI (Sistema Internacional de Unidades):\n\n* $L$ Longitud. \n * Unidad: metro, [m].\n* $M$ Masa. \n * Unidad: kilogramo, [kg].\n* $T$ Tiempo. \n * Unidad: segundo, [s].\n* $\\theta$ Temperatura. \n * Unidad: Kelvin, [K].\n\n\n\n#### Análisis Dimensional\n## Dimensiones físicas\nExisten 7 dimensiones fundamentales, cuyas unidades b asicas\nson\ndefinidas por el SI (Sistema Internacional de Unidades):\n\n* $I$ Intensidad de Corriente Eléctrica. \n * Unidad: Amperio, [A].\n* $\\mu$ Cantidad de Sustancia. \n * Unidad: Mol, [mol].\n* $lv$ Intensidad Luminosa. \n * Unidad: Candela, [cd].\n\n\n\n#### Análisis Dimensional\n## Repaso de FIS100\n\n¿Dimensiones de Fuerza? ¿Dimensiones de Torque?\n\n\n#### Fuerza:\n* Unidades: $M L T^{-2}$\n* Recordar: Fuerza = masa x aceleración\n\n#### Torque:\n* Unidades: $M L^2 T^{-2}$\n* Recordar: Torque = fuerza x largo\n\n#### Análisis Dimensional\n## Repaso de FIS100\n¿Dimensiones de Energía? \n¿Dimensiones de Presión?\n\n\n\n#### Energía:\n* Unidades: $M L^2 T^{-2}$\n* Recordar: Energia Cinética = masa x velocidad al cuadrado\n\n#### Presión:\n* Unidades: $M L^{-1} T^{-2}$\n* Recordar: Presión = Fuerza sobre area\n\n\n\n#### Análisis Dimensional\n## Teorema $\\Pi$ o teorema Buckingham\n\nSi un problema requiere $n$ variables dimensionales con $k$ dimensiones independientes, entonces puede reducirse a una relación entre $n − k$ parámetros\nno dimensionales $\\Pi_1 ,\\Pi_2 , ..., \\Pi_{n-k}$\n\n\n$$\\Phi(\\Pi_1 ,\\Pi_2 , ..., \\Pi_{n-k}) = 0$$\n\n#### Teorema $\\Pi$ o teorema Buckingham\n\nPara construir estos parámetros no-dimensionales:\n1. Elegir $k$ variables de escalamiento que contengan en conjunto las $k$ dimensiones del problema: $s_1 , ..., s_k$.\n2. Para cada una de las restantes $n − k$ variables $v_i$ construir una\nvariable adimensional $\\Pi_i$ de la forma\n$$\\Pi_i = v_i (s_1 )^{m_1} (s_2 )^{m_2} ...(s_k )^{m_k}$$\ndonde $m_1$, $m_2$ , ... $m_k$ se resuelven para hacer cada $\\Pi_i$ adimensional.\n\n#### Análisis Dimensional\n## Teorema $\\Pi$ o teorema Buckingham\n\n* La elección de la \"base\" $s_i$ no es única.\n* Una vez elegida la \"base\" $s_i$, los parámetros quedan únicamente definidos.\n* El teorema permite determinar cuales serán los parámetros adimensionales, a pesar que la ecuación sea todavía desconocida.\n\n\n\n## Ejemplo 1: Caída libre\nConsideremos el caso de la caída libre de un objeto. \n\n¿Cuales son las variables físicas involucradas?\n\n* Masa del objeto: $m$\n* Altura de la caída: $h$\n* Tiempo de caída: $t$\n* Constante de gravedad: $g$\n\n#### Ejemplo 1: Caída libre\n## Dimensiones\n* Masa del objeto: $[m] = M$\n* Altura de la caída: $[h] = L$\n* Tiempo de caída: $[t] = T$\n* Constante de gravedad: $[g] = L/T^2$\n\n**Conclusión**: La masa no es importante en la caída libre: no puede relacionarse con las otras variables, pues no sería posible adimensionalizarla.\n\n#### Ejemplo 1: Caída libre\n## Teorema $\\Pi$\n* Datos:\n * 3 variables: $h$, $t$, $g$\n * 2 dimensiones: $L$ y $T$\n\n* Se tiene $3-2=1$ variables adimensionales.\n\n* Elección de variables escalamiento: \n * $g$, $t$\n\n\n#### Ejemplo 1: Caída libre\n## Teorema $\\Pi$\nAdimensionalizando tenemos:\n$$\\Pi_1 = h g^x t^y$$\nLuego se tiene la siguiente relación entre las dimensiones\n$$\\begin{align}[\\Pi_1] &= [h g^x t^y] = [h] [g]^x [t]^y \\\\ \n&= L \\ L^x \\ T^{-2x} \\ T^y = L^0 T^0\n\\end{align}$$\nEs decir, debemos resolver el sistema:\n$$\\begin{align} 1 + x & = 0 \\\\ −2x + y &= 0 \\end{align}$$\n\nSe obtiene: $x = −1$ e $y = −2$, con lo cual\n$$ \\Pi_1 = h g^x t^y = \\frac{h}{gt^2}$$\n\n#### Ejemplo 1: Caída libre\nEl teorema de Buckingham nos dice que existe por tanto una relación\ndel tipo:\n$$\\Phi(\\Pi_1) = 0$$\nes decir, $\\Pi_1$ debe ser una constante:\n$$\\Pi_1 =\\frac{h}{gt^2} = c$$\n\nA partir de eso, podemos establecer las siguientes relaciones:\n$$ \\begin{align}\nh &= c g t^2 \\\\\ng &= \\frac{1}{c} \\frac{h}{t^2} \\\\\nt &= \\sqrt{\\frac{1}{c}\\frac{h}{g}}\n\\end{align}$$\nY todo eso **¡sin ningún conocimiento físico excepto las unidades!**\n\n\n## Ejemplo 2: Explosión Nuclear\nConsideremos la explosión de una bomba atómica.\n\n¿Cuales son las variables físicas involucradas?\n\n* Energía de la Bomba: $E$\n* Radio de la explosión: $r$\n* Tiempo : $t$\n* Densidad del medio: $\\rho$\n\n#### Ejemplo 2: Explosión Nuclear\n## Dimensiones\n* Energía de la Bomba: $[E] = ML^2 /T^2$\n* Radio de la explosión: $[r] = L$\n* Tiempo : $[t] = T$\n* Densidad del medio: $[\\rho] = M / L^3$\n\n**Conclusión**: Necesitamos la densidad pues de otra forma no podemos\nadimensionalizar la energía.\n\n#### Ejemplo 2: Explosión Nuclear\n## Teorema $\\Pi$\n* Datos:\n * 4 variables: $E$, $r$ , $t$ y $\\rho$\n * 3 dimensiones: $M$, $L$ y $T$\n\n* Se tiene $4-3=1$ variables adimensionales.\n\n* Elección de variables escalamiento: \n * $r$, $t$, $\\rho$\n\n\n#### Ejemplo 2: Caída libre\n\nAdimensionalizando la energía $E$ tenemos:\n$$\\Pi_1 = E r^x t^y \\rho^z$$\nLuego se tiene la siguiente relación entre las dimensiones\n$$\\begin{align}\n[\\Pi_1] &= [E r^x t^y \\rho^z] = [E] [r]^x [t]^y [\\rho]^y \\\\\n&= \\Big(M L^2/ T^2 \\Big) \\ L^x \\ T^y \\Big(M/ L^3 \\Big)^z= M^0 L^0 T^0\n\\end{align}$$\nEs decir, debemos resolver el sistema:\n$$\\begin{align} 1 + z & = 0 \\\\ 2 + x -3z &= 0 \\\\ -2 + y &= 0 \\end{align}$$\n\nSe obtiene: $x = −5$, $y = 2$ y $z = −1$, con lo cual\n$$ \\Pi_1 = E r^x t^y \\rho^z = \\frac{E t^2}{r^5 \\rho}$$\n\n#### Ejemplo 2: Explosión Nuclear\nEl teorema de Buckingham nos dice que existe por tanto una relación\ndel tipo:\n$$\\Phi(\\Pi_1) = 0$$\nes decir, $\\Pi_1$ debe ser una constante:\n$$\\Pi_1 =\\frac{E t^2}{r^5 \\rho} = c$$\n\nA partir de eso, podemos establecer las siguientes relaciones:\n$$ \\begin{align}\nE &= c_E \\frac{r^5\\rho}{t^2} \\\\\nr &= c_r \\sqrt[5]{\\frac{E t^2}{\\rho}}\n\\end{align}$$\nY todo eso **¡sin ningún conocimiento físico excepto las unidades!**\n\n#### Ejemplo 2: Explosión Nuclear\nLa anécdota cuenta que en 1945 Estados Unidos hizo explotar una bomba (nombre clave Trinity) en el desierto de Nuevo México. Luego en 1947, se liberó una secuencia de fotos de la explosión. Utilizando las fotos y el análisis dimensional, el científico británico Goeffrey Taylor estimó la energía liberarada con sólo un 10% de error.\n\n\n## Ejemplo 3: Distancia de Detención\nConsideremos la distancia de detención de un vehículo en una carretera.\n\n¿Cuales son las variables físicas involucradas?\n\n* Distancia de detención: $d$\n* Velocidad del vehículo: $v$\n* Masa del vehículo: $m$\n* Tiempo de reacción: $t$\n* Fuerza de frenado: $f$\n* Coeficiente de fricción de los frenos: $\\mu$\n\n#### Ejemplo 3 - Distancia de Detención\n## Dimensiones\n* Distancia de detención: $[d] = L$\n* Velocidad del vehículo: $[v] = L/T$\n* Masa del vehículo: $[m] = M$\n* Tiempo de reacción: $[t] = T$\n* Fuerza de frenado: $[f] = M L/T^2$\n* Coeficiente de fricción de los frenos: $[\\mu] = 1$\n\n**Conclusión**: Coeficiente de fricción ya es un coeficiente adimensional.\n\n#### Ejemplo 3: Distancia de Detención\n## Teorema $\\Pi$\n* Datos:\n * 6 variables: $d$, $v$ , $t$, $f$, $m$ y $\\mu$\n * 3 dimensiones: $M$, $L$ y $T$\n\n* Se tiene $6-3=3$ variables adimensionales.\n\n* Elección de variables escalamiento: \n * $m$, $t$, $v$\n\n#### Ejemplo 4: Distancia de Detención\n## Teorema $\\Pi$\nAdimensionalizando $\\mu$ tenemos:\n$$\\Pi_1 = \\mu $$\n\n#### Ejemplo 3: Distancia de Detención\nAdimensionalizando ***la distancia de detención $d$*** tenemos:\n$$\\Pi_2 = d m^x t^y v^z$$\nLuego se tiene la siguiente relación entre las dimensiones\n$$\\begin{align}\n[\\Pi_2] &= [d m^x t^y v^z] = [d] [m]^x [t]^y [v]^y \\\\\n&= L M^x \\ T^y \\Big(L/T\\Big)^z= M^0 L^0 T^0\n\\end{align}$$\nEs decir, debemos resolver el sistema:\n$$\\begin{align} x & = 0 \\\\ 1 + z &= 0 \\\\ y -z &= 0 \\end{align}$$\n\nSe obtiene: $x = 0$, $y = z$ y $z = −1$, con lo cual\n$$ \\Pi_2 = d m^x t^y v^z = \\frac{d}{v t}$$\n\n#### Ejemplo 3: Distancia de Detención\nAdimensionalizando ***la fuerza de frenado $f$*** tenemos:\n$$\\Pi_3 = f m^x t^y v^z$$\nLuego se tiene la siguiente relación entre las dimensiones\n$$[\\Pi_3] = [f m^x t^y v^z] = [f] [m]^x [t]^y [v]^y = M L/T^2 M^x \\ T^y \\Big(L/T\\Big)^z= M^0 L^0 T^0$$\nEs decir, debemos resolver el sistema:\n$$\\begin{align} 1+x & = 0 \\\\ 1 + z &= 0 \\\\ y -z -2 &= 0 \\end{align}$$\n\nSe obtiene: $x = -1$, $y = 1$ y $z = −1$, con lo cual\n$$ \\Pi_3 = f m^x t^y v^z = \\frac{f t}{mv}$$\n\n#### Ejemplo 3: Distancia de Detención\n## Teorema $\\Pi$\nEl teorema de Buckingham nos dice que existe por tanto una relación\ndel tipo:\n$$\\Phi(\\Pi_1,\\Pi_2,\\Pi_3) = 0$$\nes decir, podemos encontrar una relación para $\\Pi_2$ del tipo :\n$$\\Pi_2 =\\phi(\\Pi_1, \\Pi_3)$$\nEs decir\n$$\\frac{d}{vt} =\\phi(\\mu, \\frac{ft}{mv})$$\npor lo tanto\n$$ d= vt \\ \\phi(\\mu, \\frac{ft}{mv})$$\n\n#### Ejemplo 3: Distancia de Detención\n## Teorema $\\Pi$\n¿Cómo debería ser $\\phi$?\n$$ \\begin{align}\n\\phi(x,y) &= c_1 x + c_2 y \\\\\n\\phi(x,y) &= c x y \\\\\n\\phi(x,y) &= c_1 x + c_2 \\frac{1}{y} \\\\\n\\phi(x,y) &= c \\frac{x}{y} \\\\\n\\phi(x,y) &= c \\frac{x^n}{y^m} \\\\\n\\end{align}$$\n\n***Análisis dimensional no nos dice nada más. ¡¡Necesitamos datos!!***\n\n## Ejemplo 5: Aplicación a modelamiento de datos\n\nConsidere el clásico Cherry Tree Dataset, descargable desde http://www.statsci.org/data/general/cherry.html.\n\n#### Fuentes\n\n* Atkinson, A. C. (1982) Regression diagnostics, transformations and constructed variables (with discussion). Journal of the Royal Statistical Society, Series B, 44, 1-36.\n\n* Ryan, T. A. Jr., Joiner, B. L. and Ryan, B. F. (1985) The Minitab Student Handbook, Boston: Duxbury Press, 328-329.\n\n* Hand D. J., Daly F., Lunn A. D., McConway K. J., Ostrowski E. (1994) A Handbook of Small Data Sets. Chapman and Hall, London. Data set 210.\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Descripción\nLos datos son:\n* volumen en pies cúbicos\n* Altura en pies\n* Diámetros en pulgadas.\n\nLos datos corresponden a una muestra de 31 arboles de black cherry, en Allegheny National Forest, Pennsylvania. \nLos datos fueron recolectados para estimar el volumen de un árbol en función de su altura y diámetro.\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Exploración de datos\nMiremos los datos utilizando el terminal de comandos (bash): head, tail, cat y wc.\n\n\n```bash\n%%bash\nhead data/cherry.txt\n```\n\n Diam\tHeight\tVolume\n 8.3\t70\t10.3\n 8.6\t65\t10.3\n 8.8\t63\t10.2\n 10.5\t72\t16.4\n 10.7\t81\t18.8\n 10.8\t83\t19.7\n 11.0\t66\t15.6\n 11.0\t75\t18.2\n 11.1\t80\t22.6\n\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Exploracion de datos\nMiremos los datos graficando con matplotlib:\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nfig = plt.figure(figsize=(16,8))\nplt.plot(D,H,'o')\nplt.ylim(ymin=0)\nplt.show()\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nfig = plt.figure(figsize=(16,8))\nplt.subplot(3,1,1)\nplt.plot(D,V,'r>')\nplt.xlabel(\"Diametro\")\nplt.ylabel(\"Volumen\")\nplt.ylim(ymin=0)\nplt.subplot(3,1,2)\nplt.plot(H,V,'bo')\nplt.xlabel(\"Altura\")\nplt.ylabel(\"Volumen\")\nplt.ylim(ymin=0)\nplt.subplot(3,1,3)\nplt.plot(D,H,'bs')\nplt.xlabel(\"Diametro\")\nplt.ylabel(\"Altura\")\nplt.ylim(ymin=0)\nfig.tight_layout()\nplt.show()\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nfig = plt.figure(figsize=(16,8))\nax = fig.add_subplot(111, projection='3d')\nax.scatter(D, H, V, s=60)\nplt.xlabel(\"Diametro [pulgadas]\")\nplt.ylabel(\"Altura [pies]\")\nplt.title(\"Volumen [pies cubicos]\")\nplt.show()\n```\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Cherry Tree Dataset\n\n¿Qué tipo de modelamiento es posible realizar con los datos? \n\n$$¿v = c_0 + c_1 h^1 + c_2 h^2 + c_3 h^3 + c_4 d + c_5 d^2 + c_6 d^3 ?$$\n$$¿v = c_0 h d^2 ?$$\n$$¿v = c_0 h^2 d?$$\n$$¿v = c_0 h^3 d^3 ?$$\n$$¿v = c_0 + c_1 h^3 + c_2 d^3 ?$$\n$$¿v = c_0 d_3 h^0 + c_1 d^{5/2} h^{1/2} + ... + c_2 d^{1/2} h^{5/2} + c_3 d^0 h^3 ?$$\n\n#### Ejemplo 5 : Cherry Tree Dataset\nUtilizando el teorema $\\Pi$:\n* Volumen $v$, diámetro $d$ y altura $h$ tienen dimensiones de largo.\n* Se tienen 3 variables y 1 dimensión, por lo que se tendrán $3 − 1 = 2$ variables adimensionales.\n* Utilizaremos $h$ como la variable base de escalamiento.\n* Para que $\\Pi_1$ = $v h^x$ sea adimensional, $x = −3$.\n * Por tanto $\\Pi_1 = \\frac{v}{h^3}$\n* Para que $\\Pi_2 = dh^x$ sea adimensional, $x = −1$. \n * Por tanto $\\Pi_2 = \\frac{d}{h}$\n\nEl teorema de Buckingham permite por tanto establecer la siguiente relación:\n$$ \\Pi_1 = f(\\Pi_2)$$\nes decir\n$$ \\frac{v}{h^3} = f\\Big( \\frac{d}{h}\\Big)$$\n\n#### Ejemplo 5 : Cherry Tree Dataset\n\nEl teorema de Buckingham establece:\n$$ \\Pi_1 = f(\\Pi_2)$$\n**PERO NADA MÁS**.\n\n* Podemos suponer que la relación es lineal, $f(x) = m x + b$, y buscar los coeficientes $m$ y $b$ utilizando los datos.\n* Podemos suponer que la relación es no lineal y de tipo potencia, $f(x) = k x^n$, y buscar los coeficientes $k$ y $n$ utilizando los datos.\n\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Exploración visual reducida\n\nAntes de proseguir, podemos graficar la relación. Como ahora estamos en 2D, resulta más fácil.\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nPi_1 = V/H**3\nPi_2 = D/H\nfig = plt.figure(figsize=(16,8))\nplt.plot(Pi_2,Pi_1,'ob', alpha=0.5, ms=12)\nplt.ylim(ymin=0)\nplt.xlabel('$\\Pi_2$', fontsize=20)\nplt.ylabel('$\\Pi_1$', fontsize=20)\nplt.show()\n```\n\n#### Ejemplo 5 : Aplicación a modelamiento de datos\n## Cherry Tree Dataset - Relación Lineal\nAplicamos regresión lineal a los datos.\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nPi_1 = V/H**3\nPi_2 = D/H\n# Regresion lineal\nm, b = np.polyfit(Pi_2, Pi_1, 1)\n# Plotting\nfig = plt.figure(figsize=(16,8))\nplt.plot(Pi_2,Pi_1,'ob', alpha=0.5, ms=12)\nx = np.sort(Pi_2)\nlabel = \"y = {0:.6f} + {1:.4} x\".format(b,m)\nplt.plot(x,m*x+b,'r', lw=2, label=label)\nplt.xlabel('$\\Pi_2$', fontsize=20)\nplt.ylabel('$\\Pi_1$', fontsize=20)\nplt.ylim(ymin=0)\nplt.legend()\nplt.show()\n```\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Cherry Tree Dataset - Relación no Lineal\nPara obtener los coeficientes de la relación no lineal de tipo \"potencia\", utilizamos el clásico truco de laboratorio de física: tomar logaritmos y luego obtener los coeficientes de una relación lineal.\nTomando logaritmo a:\n$$ \\Pi_1 = k (\\Pi_2)^n$$\nObtenemos\n$$ \\log \\Pi_1 = \\log k + n \\log \\Pi_2$$\n\nEs decir, podemos realizar una regresión lineal a $\\log \\Pi_1$ y $\\log \\Pi_2$, de modo de encontrar\n$\\log \\Pi_1 = b + m \\log \\Pi_2$ y luego calcular $n=m$ y $k=e^b$.\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\ndata = np.loadtxt(\"data/cherry.txt\", skiprows=1)\nD, H, V = data.T\nPi_1 = V/H**3\nPi_2 = D/H\n# Regresion de potencia\nx = np.log(Pi_2)\ncm, cb = np.polyfit(np.log(Pi_2), np.log(Pi_1), 1)\nn, k = cm, np.exp(cb)\n# Plotting\nfig = plt.figure(figsize=(16,8))\nplt.plot(Pi_2,Pi_1,'ob', alpha=0.5, ms=12)\nx = np.sort(Pi_2)\nlabel = \"y = {0:.6f} x^{1:.4}\".format(k,n)\nplt.plot(x,k*x**n,'r', lw=2, label=label)\n#plt.plot(x,b + m*x,'g', lw=2, label=label)\nplt.xlabel('$\\Pi_2$', fontsize=20)\nplt.ylabel('$\\Pi_1$', fontsize=20)\nplt.ylim(ymin=0)\nplt.legend()\nplt.show()\n```\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Análisis del error\n¿Que relación modela mejor los datos?\n\nSólo podemos saberlo analizando el error de nuestro modelo.\n* Modelo lineal:\n$$ v_{lineal} = \\Big(b + m \\ \\frac{d}{h} \\Big) h^3$$\n* Modelo no lineal:\n$$ v_{potencia} = k \\ \\Big(\\frac{d}{h}\\Big)^n \\ h^3$$\n\n#### Ejemplo 5 : Cherry Tree Dataset\n## Análisis del error\n\n\n```python\n# Error modelo lineal\nV_pred_lineal = (b + m*Pi_2) * H**3\nerror_pred_lineal = V - V_pred_lineal\nprint \"Predicción Lineal de Volumen\"\nprint \"\\tError promedio:\", np.abs(error_pred_lineal).mean()\nprint \"\\tError cuadrático medio:\", (error_pred_lineal**2).sum()**(0.5)/len(error_pred_lineal)\nprint \"\\tError máximo:\", np.abs(error_pred_lineal).max()\n```\n\n Predicción Lineal de Volumen\n \tError promedio: 2.03807360201\n \tError cuadrático medio: 0.467568459874\n \tError máximo: 5.3407996336\n\n\n\n```python\n# Error modelo no lineal\nV_pred_potencia = (k*Pi_2**n) * H**3\nerror_pred_potencia = V - V_pred_potencia\nprint \"Predicción No Lineal de Volumen\"\nprint \"\\tError promedio:\", np.abs(error_pred_potencia).mean()\nprint \"\\tError cuadrático medio:\", (error_pred_potencia**2).sum()**(0.5)/len(error_pred_potencia)\nprint \"\\tError máximo:\", np.abs(error_pred_potencia).max()\n```\n\n Predicción No Lineal de Volumen\n \tError promedio: 1.84565953758\n \tError cuadrático medio: 0.437336519611\n \tError máximo: 4.78745790459\n\n\n#### Ejemplo 5: Cherry Tree Dataset\n## Cherry Tree Dataset - Conclusión\nNuestro análisis indica que\n$$\\Pi_1 = k (\\Pi_2 )^n$$\no equivalentemente\n$$ \\frac{v}{h^3}= k \\frac{d^n}{h^n}\n$$\ncon $k=0.002059$ y $n=1.991$.\n\nSe tiene $v = k d^n h^{3-n} \\approx k d^2 h$\nlo cual a posteriori parece bastante obvio. \n\n## Resumen Teorema $\\Pi$:\n* Más simple, imposible.\n* Sólo require buen juicio y un poco de trabajo algebraico.\n* Permite pasar de un problema de $n$ variables y $k$ dimensiones, a un problema de $n-k$ variables adimensionales.\n* Reduce de manera sencilla las dimensiones de un problema físico.\n", "meta": {"hexsha": "1678105b41cf439f5a977a354992428f68a7a0b8", "size": 264488, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase02-TeoremaPI/TeoremaPi.ipynb", "max_stars_repo_name": "sebastiandres/mat281", "max_stars_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-07-12T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-12T19:23:25.000Z", "max_issues_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase02-TeoremaPI/TeoremaPi.ipynb", "max_issues_repo_name": "sebastiandres/mat281", "max_issues_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clases/Unidad2-HerramientasTransversalesEnIngenieria/Clase02-TeoremaPI/TeoremaPi.ipynb", "max_forks_repo_name": "sebastiandres/mat281", "max_forks_repo_head_hexsha": "52f7c6a2c64181434865e8ce2f1b61b7386901bd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-06T15:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-06T15:01:54.000Z", "avg_line_length": 181.1561643836, "max_line_length": 95442, "alphanum_fraction": 0.8906037325, "converted": true, "num_tokens": 7091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.15360609383855178}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\nimport scipy.stats as stats\n```\n\n\n```python\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nprint(len(data))\n```\n\n 500\n\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=True)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25]\ncolours = [\"#348ABD\", \"#A60628\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\n#count_data = np.random.rand(74)\n#count_data = np.array([10.] * 74)\nprint(count_data)\nprint(len(count_data))\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n /Users/andrew.chang/miniconda3/lib/python3.8/site-packages/pymc3/sampling.py:465: FutureWarning: In an upcoming release, pm.sample will return an `arviz.InferenceData` object instead of a `MultiTrace` by default. You can pass return_inferencedata=True or return_inferencedata=False to be safe and silence this warning.\n warnings.warn(\n Multiprocess sampling (4 chains in 4 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n\n\n\n\n
\n \n \n 100.00% [60000/60000 00:08<00:00 Sampling 4 chains, 0 divergences]\n
\n\n\n\n Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 16 seconds.\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nprint(N)\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n #print(tau_samples)\n #print(ix)\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\n#type your code here.\nprint(lambda_1_samples.shape)\nprint(lambda_2_samples.shape)\n\nprint(lambda_1_samples.mean())\nprint(lambda_2_samples.mean())\n```\n\n (40000,)\n (40000,)\n 17.759728443586994\n 22.70833099730656\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n#type your code here.\nprint(lambda_1_samples.mean()/lambda_2_samples.mean())\nprint((lambda_1_samples/lambda_2_samples).mean())\n```\n\n 0.7820798651249834\n 0.7832908130265642\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\n#type your code here.\nix = tau_samples < 45\nprint(lambda_1_samples[ix].mean())\n```\n\n 17.758955289346453\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "eb8b6182933a0c3c71d850b4ee64607ef62b8788", "size": 305061, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "agchang-cgl/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "2ceadbdf564420da56e06e678db1d5b60dfdb0c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "agchang-cgl/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "2ceadbdf564420da56e06e678db1d5b60dfdb0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "agchang-cgl/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "2ceadbdf564420da56e06e678db1d5b60dfdb0c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 230.5827664399, "max_line_length": 88936, "alphanum_fraction": 0.8920478199, "converted": true, "num_tokens": 11951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.15295311562644778}} {"text": "\n\n\n```python\n# Mount Google Drive\nfrom google.colab import drive # import drive from google colab\n\nROOT = \"/content/drive\" # default location for the drive\nprint(ROOT) # print content of ROOT (Optional)\n\ndrive.mount(ROOT,force_remount=True) \n```\n\n /content/drive\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /content/drive\n\n\n# Neuromatch Academy: Week 1, Day 3, Tutorial 1\n# Model Fitting: Linear regression with MSE\n\n**Content creators**: Pierre-Étienne Fiquet, Anqi Wu, Alex Hyafil with help from Byron Galbraith\n\n**Content reviewers**: Lina Teichmann, Saeed Salehi, Patrick Mineault, Ella Batty, Michael Waskom\n\n\n\n\n\n___\n#Tutorial Objectives\n\nThis is Tutorial 1 of a series on fitting models to data. We start with simple linear regression, using least squares optimization (Tutorial 1) and Maximum Likelihood Estimation (Tutorial 2). We will use bootstrapping to build confidence intervals around the inferred linear model parameters (Tutorial 3). We'll finish our exploration of regression models by generalizing to multiple linear regression and polynomial regression (Tutorial 4). We end by learning how to choose between these various models. We discuss the bias-variance trade-off (Tutorial 5) and Cross Validation for model selection (Tutorial 6).\n\nIn this tutorial, we will learn how to fit simple linear models to data.\n- Learn how to calculate the mean-squared error (MSE) \n- Explore how model parameters (slope) influence the MSE\n- Learn how to find the optimal model parameter using least-squares optimization\n\n---\n\n**acknowledgements:** \n- we thank Eero Simoncelli, much of today's tutorials are inspired by exercises asigned in his mathtools class.\n\n---\n# Setup\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n#@title Figure Settings\nimport ipywidgets as widgets # interactive display\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")\n```\n\n\n```python\n#@title Helper functions\n\ndef plot_observed_vs_predicted(x, y, y_hat, theta_hat):\n \"\"\" Plot observed vs predicted data\n\n Args:\n x (ndarray): observed x values\n y (ndarray): observed y values\n y_hat (ndarray): predicted y values\n\n \"\"\"\n fig, ax = plt.subplots()\n ax.scatter(x, y, label='Observed') # our data scatter plot\n ax.plot(x, y_hat, color='r', label='Fit') # our estimated model\n # plot residuals\n ymin = np.minimum(y, y_hat)\n ymax = np.maximum(y, y_hat)\n ax.vlines(x, ymin, ymax, 'g', alpha=0.5, label='Residuals')\n ax.set(\n title=fr\"$\\hat{{\\theta}}$ = {theta_hat:0.2f}, MSE = {mse(x, y, theta_hat):.2f}\",\n xlabel='x',\n ylabel='y'\n )\n ax.legend()\n\n```\n\n---\n# Section 1: Mean Squared Error (MSE)\n\n\n```python\n#@title Video 1: Linear Regression & Mean Squared Error\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"HumajfjJ37E\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n```\n\n Video available at https://youtube.com/watch?v=HumajfjJ37E\n\n\n\n\n\n\n\n\n\n\n\n**Linear least squares regression** is an old but gold optimization procedure that we are going to use for data fitting. Least squares (LS) optimization problems are those in which the objective function is a quadratic function of the\nparameter(s) being optimized.\n\nSuppose you have a set of measurements, $y_{n}$ (the \"dependent\" variable) obtained for different input values, $x_{n}$ (the \"independent\" or \"explanatory\" variable). Suppose we believe the measurements are proportional to the input values, but are corrupted by some (random) measurement errors, $\\epsilon_{n}$, that is:\n\n$$y_{n}= \\theta x_{n}+\\epsilon_{n}$$\n\nfor some unknown slope parameter $\\theta.$ The least squares regression problem uses **mean squared error (MSE)** as its objective function, it aims to find the value of the parameter $\\theta$ by minimizing the average of squared errors:\n\n\\begin{align}\n\\min _{\\theta} \\frac{1}{N}\\sum_{n=1}^{N}\\left(y_{n}-\\theta x_{n}\\right)^{2}\n\\end{align}\n\nWe will now explore how MSE is used in fitting a linear regression model to data. For illustrative purposes, we will create a simple synthetic dataset where we know the true underlying model. This will allow us to see how our estimation efforts compare in uncovering the real model (though in practice we rarely have this luxury).\n\nFirst we will generate some noisy samples $x$ from [0, 10) along the line $y = 1.2x$ as our dataset we wish to fit a model to.\n\n\n```python\n# @title \n\n# @markdown Execute this cell to generate some simulated data\n\n# setting a fixed seed to our random number generator ensures we will always\n# get the same psuedorandom number sequence\nnp.random.seed(121)\n\n# Let's set some parameters\ntheta = 1.2\nn_samples = 30\n\n# Draw x and then calculate y\nx = 10 * np.random.rand(n_samples) # sample from a uniform distribution over [0,10)\nnoise = np.random.randn(n_samples) # sample from a standard normal distribution\ny = theta * x + noise\n\n# Plot the results\nfig, ax = plt.subplots()\nax.scatter(x, y) # produces a scatter plot\nax.set(xlabel='x', ylabel='y');\n```\n\nNow that we have our suitably noisy dataset, we can start trying to estimate the underlying model that produced it. We use MSE to evaluate how successful a particular slope estimate $\\hat{\\theta}$ is for explaining the data, with the closer to 0 the MSE is, the better our estimate fits the data.\n\n## Exercise 1: Compute MSE\n\nIn this exercise you will implement a method to compute the mean squared error for a set of inputs $x$, measurements $y$, and slope estimate $\\hat{\\theta}$. We will then compute and print the mean squared error for 3 different choices of theta\n\n\n```python\ndef mse(x, y, theta_hat):\n \"\"\"Compute the mean squared error\n\n Args:\n x (ndarray): An array of shape (samples,) that contains the input values.\n y (ndarray): An array of shape (samples,) that contains the corresponding\n measurement values to the inputs.\n theta_hat (float): An estimate of the slope parameter\n \n Returns:\n float: The mean squared error of the data with the estimated parameter.\n \"\"\"\n ####################################################\n ## TODO for students: compute the mean squared error\n # Fill out function and remove\n #raise NotImplementedError(\"Student exercise: compute the mean squared error\")\n ####################################################\n\n # Compute the estimated y \n y_hat = x*theta_hat\n\n # Compute mean squared error\n mse = np.mean((y-y_hat)**2)\n\n return mse\n\n\n# Uncomment below to test your function\ntheta_hats = [0.75, 1.0, 1.5]\nfor theta_hat in theta_hats:\n print(f\"theta_hat of {theta_hat} has an MSE of {mse(x, y, theta_hat):.2f}\")\n```\n\n theta_hat of 0.75 has an MSE of 9.08\n theta_hat of 1.0 has an MSE of 3.01\n theta_hat of 1.5 has an MSE of 4.52\n\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial1_Solution_e5ee9b3d.py)\n\n\n\nThe result should be:\n\ntheta_hat of 0.75 has an MSE of 9.08\\\ntheta_hat of 1.0 has an MSE of 3.0\\\ntheta_hat of 1.5 has an MSE of 4.52\n\n\n\n\n\nWe see that $\\hat{\\theta} = 1.0$ is our best estimate from the three we tried. Looking just at the raw numbers, however, isn't always satisfying, so let's visualize what our estimated model looks like over the data. \n\n\n\n\n```python\n#@title\n\n#@markdown Execute this cell to visualize estimated models\n\nfig, axes = plt.subplots(ncols=3, figsize=(18, 4))\nfor theta_hat, ax in zip(theta_hats, axes):\n\n # True data\n ax.scatter(x, y, label='Observed') # our data scatter plot\n\n # Compute and plot predictions\n y_hat = theta_hat * x\n ax.plot(x, y_hat, color='r', label='Fit') # our estimated model\n\n ax.set(\n title= fr'$\\hat{{\\theta}}$= {theta_hat}, MSE = {mse(x, y, theta_hat):.2f}',\n xlabel='x',\n ylabel='y' \n );\n\naxes[0].legend()\n```\n\n## Interactive Demo: MSE Explorer\n\nUsing an interactive widget, we can easily see how changing our slope estimate changes our model fit. We display the **residuals**, the differences between observed and predicted data, as line segments between the data point (observed response) and the corresponding predicted response on the model fit line.\n\n\n```python\n#@title \n\n#@markdown Make sure you execute this cell to enable the widget!\n\n@widgets.interact(theta_hat=widgets.FloatSlider(1.0, min=0.0, max=2.0))\ndef plot_data_estimate(theta_hat):\n y_hat = theta_hat * x\n plot_observed_vs_predicted(x, y, y_hat, theta_hat)\n\n```\n\n\n interactive(children=(FloatSlider(value=1.0, description='theta_hat', max=2.0), Output()), _dom_classes=('widg…\n\n\nWhile visually exploring several estimates can be instructive, it's not the most efficient for finding the best estimate to fit our data. Another technique we can use is choose a reasonable range of parameter values and compute the MSE at several values in that interval. This allows us to plot the error against the parameter value (this is also called an **error landscape**, especially when we deal with more than one parameter). We can select the final $\\hat{\\theta}$ ($\\hat{\\theta}_{MSE}$) as the one which results in the lowest error.\n\n\n```python\n# @title\n\n# @markdown Execute this cell to loop over theta_hats, compute MSE, and plot results\n\n# Loop over different thetas, compute MSE for each\ntheta_hat_grid = np.linspace(-2.0, 4.0)\nerrors = np.zeros(len(theta_hat_grid))\nfor i, theta_hat in enumerate(theta_hat_grid):\n errors[i] = mse(x, y, theta_hat)\n\n# Find theta that results in lowest error\nbest_error = np.min(errors)\ntheta_hat = theta_hat_grid[np.argmin(errors)]\n\n\n# Plot results\nfig, ax = plt.subplots()\nax.plot(theta_hat_grid, errors, '-o', label='MSE', c='C1')\nax.axvline(theta, color='g', ls='--', label=r\"$\\theta_{True}$\")\nax.axvline(theta_hat, color='r', ls='-', label=r\"$\\hat{{\\theta}}_{MSE}$\")\nax.set(\n title=fr\"Best fit: $\\hat{{\\theta}}$ = {theta_hat:.2f}, MSE = {best_error:.2f}\",\n xlabel=r\"$\\hat{{\\theta}}$\",\n ylabel='MSE')\nax.legend();\n```\n\nWe can see that our best fit is $\\hat{\\theta}=1.18$ with an MSE of 1.45. This is quite close to the original true value $\\theta=1.2$!\n\n\n---\n# Section 2: Least-squares optimization\n\n\nWhile the approach detailed above (computing MSE at various values of $\\hat\\theta$) quickly got us to a good estimate, it still relied on evaluating the MSE value across a grid of hand-specified values. If we didn't pick a good range to begin with, or with enough granularity, we might miss the best possible estimator. Let's go one step further, and instead of finding the minimum MSE from a set of candidate estimates, let's solve for it analytically.\n\nWe can do this by minimizing the cost function. Mean squared error is a convex objective function, therefore we can compute its minimum using calculus. Please see video or appendix for this derivation! After computing the minimum, we find that:\n\n\\begin{align}\n\\hat\\theta = \\frac{\\vec{x}^\\top \\vec{y}}{\\vec{x}^\\top \\vec{x}}\n\\end{align}\n\nThis is known as solving the normal equations. For different ways of obtaining the solution, see the notes on [Least Squares Optimization](https://www.cns.nyu.edu/~eero/NOTES/leastSquares.pdf) by Eero Simoncelli.\n\n### Exercise 2: Solve for the Optimal Estimator\n\nIn this exercise, you will write a function that finds the optimal $\\hat{\\theta}$ value using the least squares optimization approach (the equation above) to solve MSE minimization. It shoud take arguments $x$ and $y$ and return the solution $\\hat{\\theta}$.\n\nWe will then use your function to compute $\\hat{\\theta}$ and plot the resulting prediction on top of the data. \n\n\n```python\ndef solve_normal_eqn(x, y):\n \"\"\"Solve the normal equations to produce the value of theta_hat that minimizes\n MSE. \n \n Args:\n x (ndarray): An array of shape (samples,) that contains the input values.\n y (ndarray): An array of shape (samples,) that contains the corresponding\n measurement values to the inputs.\n\n Returns:\n float: the value for theta_hat arrived from minimizing MSE\n \"\"\"\n\n ################################################################################\n ## TODO for students: solve for the best parameter using least squares \n # Fill out function and remove\n #raise NotImplementedError(\"Student exercise: solve for theta_hat using least squares\")\n ################################################################################\n\n # Compute theta_hat analytically\n theta_hat = (x.T @ y)/(x.T @x)\n\n return theta_hat\n\n\n# Uncomment below to test your function\ntheta_hat = solve_normal_eqn(x, y)\ny_hat = theta_hat * x\nplot_observed_vs_predicted(x, y, y_hat, theta_hat)\n\n```\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial1_Solution_cb582fbb.py)\n\n*Example output:*\n\n\n\n\n\nWe see that the analytic solution produces an even better result than our grid search from before, producing $\\hat{\\theta} = 1.21$ with MSE = 1.43!\n\n---\n# Summary\n\n- Linear least squares regression is an optimization procedure that can be used for data fitting:\n - Task: predict a value for $y$ given $x$\n - Performance measure: $\\textrm{MSE}$\n - Procedure: minimize $\\textrm{MSE}$ by solving the normal equations\n- **Key point**: We fit the model by defining an *objective function* and minimizing it. \n- **Note**: In this case, there is an *analytical* solution to the minimization problem and in practice, this solution can be computed using *linear algebra*. This is *extremely* powerful and forms the basis for much of numerical computation throughout the sciences.\n\n---\n# Appendix\n\n## Least Squares Optimization Derivation\n\nWe will outline here the derivation of the least squares solution.\n\nWe first set the derivative of the error expression with respect to $\\theta$ equal to zero, \n\n\\begin{align}\n\\frac{d}{d\\theta}\\frac{1}{N}\\sum_{i=1}^N(y_i - \\theta x_i)^2 = 0 \\\\\n\\frac{1}{N}\\sum_{i=1}^N-2x_i(y_i - \\theta x_i) = 0\n\\end{align}\n\nwhere we used the chain rule. Now solving for $\\theta$, we obtain an optimal value of:\n\n\\begin{align}\n\\hat\\theta = \\frac{\\sum_{i=1}^N x_i y_i}{\\sum_{i=1}^N x_i^2}\n\\end{align}\n\nWhich we can write in vector notation as:\n\n\\begin{align}\n\\hat\\theta = \\frac{\\vec{x}^\\top \\vec{y}}{\\vec{x}^\\top \\vec{x}}\n\\end{align}\n\n\nThis is known as solving the *normal equations*. For different ways of obtaining the solution, see the notes on [Least Squares Optimization](https://www.cns.nyu.edu/~eero/NOTES/leastSquares.pdf) by Eero Simoncelli.\n", "meta": {"hexsha": "d397d57b2f93a2d9db8b9173c7ebee0e59c7b916", "size": 331352, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W1D3_ModelFitting/student/W1D3_Tutorial1.ipynb", "max_stars_repo_name": "hnoamany/course-content", "max_stars_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W1D3_ModelFitting/student/W1D3_Tutorial1.ipynb", "max_issues_repo_name": "hnoamany/course-content", "max_issues_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W1D3_ModelFitting/student/W1D3_Tutorial1.ipynb", "max_forks_repo_name": "hnoamany/course-content", "max_forks_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 331352.0, "max_line_length": 331352, "alphanum_fraction": 0.9434136507, "converted": true, "num_tokens": 3976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15247841875278748}} {"text": "# Game Theory: Introduction to the course\n\nThis course will cover the following aspects of Game Theory:\n\n- Normal form games and Nash equilibrium\n- Evolutionary Game Theory\n- Some contemporary research\n\nAll course materials are available online at [vknight.org/gt/](http://vknight.org/gt/). You can also find all the source files that create that website at [github.com/drvinceknight/gt/](https://github.com/drvinceknight/gt/).\n\n## Course notes\n\nThe course notes are written using Jupyter notebooks, you will see mathematics but also Python code used to illustrate and confirm certain results.\n\nFor example here is some code verifying the simple identity:\n\n$$\n(a + b) ^ 2 = a^2 + 2ab + b ^2.\n$$\n\n\n```python\nimport sympy as sym # A library used for symbolic computations\nsym.init_printing() # Use LaTeX to clean up the output\na, b = sym.symbols('a, b')\n((a + b) ** 2).expand()\n```\n\nIn class we will not follow the course notes: these are there for you to read on your own time. Instead we will use activities and other examples to illustrate the concepts. I have my own notes for those (which are also available to you): http://vkgt.readthedocs.io/en/latest/. \n\nIf you would like some information about the pedagogic approach:\n\n- You can find my \"teaching philosophy\" here: https://vknight.org/tch-phi/\n- Here is a paper describing some of the pedagogic rational for this approach: https://journals.gre.ac.uk/index.php/msor/article/view/254/254\n\nIt is possible that the course notes will change: **for things like typos and clarifications**, all of the notes are hosted openly on github and if you're interested you can find a list of all changes here: https://github.com/drvinceknight/gt/commits/master\n\n## Technology in class\n\nPlease use whatever resources you need to be successful in this class. Let me know if I can help with anything.\n\n## Office hours\n\nI will hold 2-3 hours a week for office hours during which you may come and get help. Specific hours will be determined collaboratively as a class during the first class meeting.\n\n## Assessment\n\nThere are two piece of assessment in this course:\n\n- Individual coursework (50%)\n- Group coursework (50%)\n", "meta": {"hexsha": "fe70636b0dcd86488a9dabf37305fee696197da5", "size": 4998, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nbs/chapters/00-Introduction-to-the-course.ipynb", "max_stars_repo_name": "drvinceknight/gt", "max_stars_repo_head_hexsha": "2ca6b2db59ecfc811d949a1a086ab8c11d63fca9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2017-05-25T08:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T21:01:51.000Z", "max_issues_repo_path": "nbs/chapters/00-Introduction-to-the-course.ipynb", "max_issues_repo_name": "drvinceknight/gt", "max_issues_repo_head_hexsha": "2ca6b2db59ecfc811d949a1a086ab8c11d63fca9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 65, "max_issues_repo_issues_event_min_datetime": "2017-05-23T16:12:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:42:25.000Z", "max_forks_repo_path": "nbs/chapters/00-Introduction-to-the-course.ipynb", "max_forks_repo_name": "drvinceknight/gt", "max_forks_repo_head_hexsha": "2ca6b2db59ecfc811d949a1a086ab8c11d63fca9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10, "max_forks_repo_forks_event_min_datetime": "2017-06-19T11:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T11:28:00.000Z", "avg_line_length": 45.8532110092, "max_line_length": 1428, "alphanum_fraction": 0.7014805922, "converted": true, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.15236289986401666}} {"text": "Probabilistic Programming\n=====\nand Bayesian Methods for Hackers \n========\n\n##### Version 0.1\n\n`Original content created by Cam Davidson-Pilon`\n\n`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`\n___\n\n\nWelcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n\nChapter 1\n======\n***\n\nThe Philosophy of Bayesian Inference\n------\n \n> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...\n\nIf you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives. \n\n\n### The Bayesian state of mind\n\n\nBayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians. \n\nThe Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability. \n\nFor this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability. \n\nBayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?\n\nNotice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n\n- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result. \n\n- Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug. \n\n- A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs. \n\n\nThis philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist. \n\nTo align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.\n\nJohn Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n\n1\\. $P(A): \\;\\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\\;\\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n\n2\\. $P(A): \\;\\;$ This big, complex code likely has a bug in it. $P(A | X): \\;\\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n\n3\\. $P(A):\\;\\;$ The patient could have any number of diseases. $P(A | X):\\;\\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n\n\nIt's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others). \n\nBy introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*. \n\n\n\n### Bayesian Inference in Practice\n\n If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.\n\nFor example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a *YES*. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of *YES* and *NO*. The function might return:\n\n\n> *YES*, with probability 0.8; *NO*, with probability 0.2\n\n\n\nThis is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: *\"Often my code has bugs\"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences. \n\n\n#### Incorporating evidence\n\nAs we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n\n\nDenote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \\rightarrow \\infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset. \n\nOne may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:\n\n> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n\n### Are frequentist methods incorrect then? \n\n**No.**\n\nFrequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n\n\n#### A note on *Big Data*\nParadoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n\nThe much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets. \n\n\n### Our Bayesian framework\n\nWe are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n\nSecondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n\n\\begin{align}\n P( A | X ) = & \\frac{ P(X | A) P(A) } {P(X) } \\\\\\\\[5pt]\n& \\propto P(X | A) P(A)\\;\\; (\\propto \\text{is proportional to })\n\\end{align}\n\nThe above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.\n\n##### Example: Mandatory coin-flip example\n\nEvery statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be. \n\nWe begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data. \n\nBelow we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).\n\n\n```python\n\"\"\"\nThe book uses a custom matplotlibrc file, which provides the unique styles for\nmatplotlib plots. If executing this book, and you wish to use the book's\nstyling, provided are two options:\n 1. Overwrite your own matplotlibrc file with the rc-file provided in the\n book's styles/ dir. See http://matplotlib.org/users/customizing.html\n 2. Also in the styles is bmh_matplotlibrc.json file. This can be used to\n update the styles in only this notebook. Try running the following code:\n\n import json\n s = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\n matplotlib.rcParams.update(s)\n\n\"\"\"\nimport json\nimport matplotlib\ns = json.load(open(\"../styles/bmh_matplotlibrc.json\"))\nmatplotlib.rcParams.update(s)\n#matplotlib.rcParams.update(matplotlib.rcParamsDefault)\n\n# The code below can be passed over, as it is currently not important, plus it\n# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!\n%matplotlib inline\nfrom IPython.core.pylabtools import figsize\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfigsize(11, 9)\n\nimport scipy.stats as stats\n\ndist = stats.beta\nn_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]\ndata = stats.bernoulli.rvs(0.5, size=n_trials[-1])\nx = np.linspace(0, 1, 100)\n\n# For the already prepared, I'm using Binomial's conj. prior.\nfor k, N in enumerate(n_trials):\n sx = plt.subplot(len(n_trials)/2, 2, k+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if k in [0, len(n_trials)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n heads = data[:N].sum()\n y = dist.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label=\"observe %d tosses,\\n %d heads\" % (N, heads))\n plt.fill_between(x, 0, y, color=\"#348ABD\", alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\",\n y=1.02,\n fontsize=14)\n\nplt.tight_layout()\n```\n\nThe posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line). \n\nNotice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n\nThe next example is a simple demonstration of the mathematics of Bayesian inference. \n\n##### Example: Bug, or just sweet, unintended feature?\n\n\nLet $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$. \n\nWe are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n\nWhat is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests. \n\n$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\\sim A\\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:\n\n\\begin{align}\nP(X ) & = P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\\\\[5pt]\n & = P(X|A)P(A) + P(X | \\sim A)P(\\sim A)\\\\\\\\[5pt]\n& = P(X|A)p + P(X | \\sim A)(1-p)\n\\end{align}\n\nWe have already computed $P(X|A)$ above. On the other hand, $P(X | \\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A) = 0.5$. Then\n\n\\begin{align}\nP(A | X) & = \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\\\\\n& = \\frac{ 2 p}{1+p}\n\\end{align}\nThis is the posterior probability. What does it look like as a function of our prior, $p \\in [0,1]$? \n\n\n```python\nfigsize(12.5, 4)\np = np.linspace(0, 1, 50)\nplt.plot(p, 2*p/(1+p), color=\"#348ABD\", lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=\"#348ABD\")\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(\"Prior, $P(A) = p$\")\nplt.ylabel(\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(\"Are there bugs in my code?\");\n```\n\nWe can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33. \n\nRecall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.\n\nSimilarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities. \n\n\n\n```python\nfigsize(12.5, 4)\ncolours = [\"#348ABD\", \"#A60628\"]\n\nprior = [0.20, 0.80]\nposterior = [1./3, 2./3]\nplt.bar([0, .7], prior, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\n\nplt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,\n width=0.25, color=colours[1],\n label=\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n```\n\nNotice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n\nThis was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n_______\n\n## Probability Distributions\n\n\n**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter. \n\nWe can divide random variables into three classifications:\n\n- **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n\n- **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n\n- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories. \n\n### Discrete Case\nIf $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n\n$$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n\n$\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n\nUnlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n\nIf a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n\n$$Z \\sim \\text{Poi}(\\lambda) $$\n\nOne useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n\n$$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n\nWe will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n\n```python\nfigsize(12.5, 4)\n\nimport scipy.stats as stats\na = np.arange(16)\npoi = stats.poisson\nlambda_ = [1.5, 4.25, 8.1]\ncolours = [\"#348ABD\", \"#A60628\", \"#44bb44\"]\n\nplt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],\n label=\"$\\lambda = %.1f$\" % lambda_[0], alpha=0.60,\n edgecolor=colours[0], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],\n label=\"$\\lambda = %.1f$\" % lambda_[1], alpha=0.60,\n edgecolor=colours[1], lw=\"3\")\n\nplt.bar(a, poi.pmf(a, lambda_[2]), color=colours[2],\n label=\"$\\lambda = %.1f$\" % lambda_[2], alpha=0.60,\n edgecolor=colours[2], lw=\"3\")\n\nplt.xticks(a + 0.4, a)\nplt.legend()\nplt.ylabel(\"probability of $k$\")\nplt.xlabel(\"$k$\")\nplt.title(\"Probability mass function of a Poisson random variable; differing \\\n$\\lambda$ values\");\n```\n\n### Continuous Case\nInstead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n\n$$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n\nLike a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n\nWhen a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n\n$$Z \\sim \\text{Exp}(\\lambda)$$\n\nGiven a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n\n$$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n\n```python\na = np.linspace(0, 4, 100)\nexpo = stats.expon\nlambda_ = [0.5, 1, 1.5]\n\nfor l, c in zip(lambda_, colours):\n plt.plot(a, expo.pdf(a, scale=1./l), lw=3,\n color=c, label=\"$\\lambda = %.1f$\" % l)\n plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)\n\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(\"Probability density function of an Exponential random variable;\\\n differing $\\lambda$\");\n```\n\n\n### But what is $\\lambda \\;$?\n\n\n**This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n\nBayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n\nThis might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n\n\n\n##### Example: Inferring behaviour from text-message data\n\nLet's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n\n> You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n\n\n\n```python\nfigsize(12.5, 3.5)\ncount_data = np.loadtxt(\"data/txtdata.csv\")\nn_count_data = len(count_data)\nplt.bar(np.arange(n_count_data), count_data, color=\"#348ABD\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data);\n```\n\nBefore we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n\nHow can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n\n$$ C_i \\sim \\text{Poisson}(\\lambda) $$\n\nWe are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n\nHow can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n\n$$\n\\lambda = \n\\begin{cases}\n\\lambda_1 & \\text{if } t \\lt \\tau \\cr\n\\lambda_2 & \\text{if } t \\ge \\tau\n\\end{cases}\n$$\n\n\nIf, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n\nWe are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n\n\\begin{align}\n&\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\\\n&\\lambda_2 \\sim \\text{Exp}( \\alpha )\n\\end{align}\n\n$\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n\n$$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n\nAn alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n\nWhat about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n\n\\begin{align}\n& \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\\\\\n& \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n\\end{align}\n\nSo after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n\nWe next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created. \n\n\nIntroducing our first hammer: PyMC3\n-----\n\nPyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.\n\nWe will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework. \n\nB. Cronin [5] has a very motivating description of probabilistic programming:\n\n> Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n\nBecause of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n\nPyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n\n```python\nimport pymc3 as pm\nimport theano.tensor as tt\n\nwith pm.Model() as model:\n alpha = 1.0/count_data.mean() # Recall count_data is the\n # variable that holds our txt counts\n lambda_1 = pm.Exponential(\"lambda_1\", alpha)\n lambda_2 = pm.Exponential(\"lambda_2\", alpha)\n \n tau = pm.DiscreteUniform(\"tau\", lower=0, upper=n_count_data - 1)\n```\n\nIn the code above, we create the PyMC3 variables corresponding to $\\lambda_1$ and $\\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.\n\n\n```python\nwith model:\n idx = np.arange(n_count_data) # Index\n lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)\n```\n\nThis code creates a new function `\\lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n\nNote that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n\n\n```python\nwith model:\n observation = pm.Poisson(\"obs\", lambda_, observed=count_data)\n```\n\nThe variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword. \n\nThe code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n\n```python\n### Mysterious code to be explained in Chapter 3.\nwith model:\n step = pm.Metropolis()\n trace = pm.sample(10000, tune=5000,step=step)\n```\n\n Multiprocess sampling (2 chains in 2 jobs)\n CompoundStep\n >Metropolis: [tau]\n >Metropolis: [lambda_2]\n >Metropolis: [lambda_1]\n Sampling 2 chains: 100%|██████████| 30000/30000 [00:07<00:00, 4169.40draws/s]\n The number of effective samples is smaller than 25% for some parameters.\n\n\n\n```python\nlambda_1_samples = trace['lambda_1']\nlambda_2_samples = trace['lambda_2']\ntau_samples = trace['tau']\n```\n\n\n```python\nfigsize(12.5, 10)\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_1$\", color=\"#A60628\", normed=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables\n $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,\n label=\"posterior of $\\lambda_2$\", color=\"#7A68A6\", density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)\nplt.hist(tau_samples, bins=n_count_data, alpha=1,\n label=r\"posterior of $\\tau$\",\n color=\"#467821\", weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(\"probability\");\n```\n\n### Interpretation\n\nRecall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n\nWhat other observations can you make? If you look at the original data again, do these results seem reasonable? \n\nNotice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n\nOur analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n\n### Why would I want samples from the posterior, anyways?\n\n\nWe will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n\nWe'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n\nIn the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n\n\n```python\nfigsize(12.5, 5)\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tau_samples.shape[0]\nexpected_texts_per_day = np.zeros(n_count_data)\nfor day in range(0, n_count_data):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day[day] = (lambda_1_samples[ix].sum()\n + lambda_2_samples[~ix].sum()) / N\n\n\nplt.plot(range(n_count_data), expected_texts_per_day, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data)\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data)), count_data, color=\"#348ABD\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n```\n\nOur analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n\n\n##### Exercises\n\n1\\. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n\n\n```python\nprint(f'Mean lambda_1_samples: {lambda_1_samples.mean():.2f}\\nMean lambda_2_samples: {lambda_2_samples.mean():.2f}')\n```\n\n Mean lambda_1_samples: 17.77\n Mean lambda_2_samples: 22.70\n\n\n2\\. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.\n\n\n```python\n(lambda_1_samples/lambda_2_samples).mean()\n```\n\n\n\n\n 0.7837805402613217\n\n\n\n3\\. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45. That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)\n\n\n```python\nlambda_1_samples[tau_samples < 42].mean()\n```\n\n\n\n\n 18.452514938489703\n\n\n\n### References\n\n\n- [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).\n- [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 \n- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n- [5] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n\n```python\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n```\n\n\n\n\n\n\n\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "db1f1fb7b6c2573e85cbec2e5ded7b0f9862595b", "size": 330332, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_stars_repo_name": "gjcooper/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "0082bb1183c114c5f99d88e743150a9612dc65de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_issues_repo_name": "gjcooper/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "0082bb1183c114c5f99d88e743150a9612dc65de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_PyMC3.ipynb", "max_forks_repo_name": "gjcooper/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "0082bb1183c114c5f99d88e743150a9612dc65de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 284.0343938091, "max_line_length": 87956, "alphanum_fraction": 0.903382052, "converted": true, "num_tokens": 11635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.15136698461601691}} {"text": "\n< [Version Control with Git](03-Git.ipynb) | [Main Contents](Index.ipynb) | [Biological Computing in Python I](05-Python_I.ipynb)>\n\n# Scientific documents with $\\LaTeX$ \n\n

Table of Contents

\n\n\n\n## What’s $\\LaTeX$?\n\nIn your research, you will produce papers, reports and – very importantly – your thesis. These documents can be written using a WYSIWYG (What You See Is What You Get) editor (e.g., Word). However, an alternative especially suited for scientific publications is LaTeX. In LaTeX, the document is written in a text file (`.tex`) with certain typesetting (tex) syntax. Text formatting is done using markups (like HTML). The file is then \"compiled\"\n(like source code of a programming language) into a file – typically `.pdf`.\n\n## Why $\\LaTeX$?\n\nA number of reasons: \n\n1. The input is a small, portable text file\n* LaTeX compilers are freely available for all OS'\n* Exactly the same result on any computer (not true for Word, for example)\n* LaTeX produces beautiful, professional looking docs\n* Images are easy to embed and annotate \n* Mathematical formulas (esp complex ones) are easy to write\n* LaTeX is very stable – current version basically same since 1994! (9 major versions of MS Word since 1994 – with compatibility issues)\n* LaTeX is free!\n* You can focus on content, and not worry so much about formatting while writing \n* An increasing number of Biology journals provide $\\LaTeX$ templates, making formatting quicker. \n* Referencing (bibliography) is easy (and can also be version controlled) and works with tools like Mendeley and Zotero\n* Plenty of online support available – your question has probably already been answered\n* You can integrate LaTeX into a workflow to auto-generate lengthy and complex documents (like your thesis).\n\n
\n\n
Source: [Marko Pinteric](http://www.pinteric.com/miktex.html)
Large, complex word documents crash, or are a heculean task to open and edit.
\n
\n\n### Limitations of $\\LaTeX$\n\n1. It has a steeper learning curve.\n* Can be difficult to manage revisions with multiple authors – especially if they don't use LaTeX! (Cue: Windows on a virtual machine!)\n* Tracking changes are not available out of the box (but can be enabled using a suitable package) \n* Typesetting tables can be a bit complex.\n* Images and floats are easy to embed, and won't jump around like Word, but if you don't use the right package, they can be difficult to place where you want!\n\n## Installing LaTeX\n\nType this in terminal: \n\n```bash\nsudo apt-get install texlive-full texlive-fonts-recommended texlive-pictures texlive-latex-extra imagemagick\n```\nIt's a large installation - will take some time. \n\nWe will use a text editor in this lecture, but you can use one of a number of dedicated editors (e.g., texmaker,\nGummi, TeXShop, etc.) There are also WYSIWYG frontends (e.g., Lyx, TeXmacs). \n\n[Overleaf](https://www.overleaf.com/) is also very good (and works with git), especially for collaborating with non LaTeX-ers (your university may have a blanket license for the pro version).\n\n## A first LaTeX example\n\n$\\star$ In your code editor type the following in a file called `FirstExample.tex` and save it in a suitable location in your coursework directory (e.g, `/Week1/Code/`:\n\n```\n\\documentclass[12pt]{article}\n\\title{A Simple Document}\n\\author{Your Name}\n\\date{}\n\\begin{document}\n \\maketitle\n \n \\begin{abstract}\n This paper must be cool!\n \\end{abstract}\n \n \\section{Introduction}\n Blah Blah!\n \n \\section{Materials \\& Methods}\n One of the most famous equations is:\n \\begin{equation}\n E = mc^2\n \\end{equation}\n This equation was first proposed by Einstein in 1905 \n \\cite{einstein1905does}.\n \n \\bibliographystyle{plain}\n \\bibliography{FirstBiblio}\n\\end{document}\n```\n\nNow, let's get a citation for this paper:\n\n$\\star$ In Google Scholar, go to \"settings\" (upper right corner) and choose BibTeX as bibliography manager. Then type \"energy of a body einstein 1905\"\n\nThe paper should be the one on the top.\n\nClick \"Import into BibTeX\" should show the following text, that you will save in the file `FirstBiblio.bib` (in the same directory as `FirstExample.tex`):\n\n```bash\n@article{einstein1905does,\n title={Does the inertia of a body depend upon its energy-content?},\n author={Einstein, A.},\n journal={Annalen der Physik},\n volume={18},\n pages={639--641},\n year={1905}\n}\n```\nNow we can create a `.pdf` of the article.\n\n$\\star$ In the terminal type (make sure you are the right directory!):\n\n``` bash\n$ pdflatex FirstExample.tex\n$ pdflatex FirstExample.tex\n$ bibtex FirstExample\n$ pdflatex FirstExample.tex\n$ pdflatex FirstExample.tex\n```\nThis should produce the file `FirstExample.pdf`:\n\n
\n\n
\n\n\n### A bash script to compile LaTeX\n\nYou can of course write a useful little bash script to compile latex with bibtex!\n\nType the following script and call it `CompileLaTeX.sh` (you know where to put it!):\n\n```bash\n#!/bin/bash\npdflatex $1.tex\npdflatex $1.tex\nbibtex $1\npdflatex $1.tex\npdflatex $1.tex\nevince $1.pdf &\n\n## Cleanup\nrm *~\nrm *.aux\nrm *.dvi\nrm *.log\nrm *.nav\nrm *.out\nrm *.snm\nrm *.toc\n```\nHow do you run this script? The same as your previous bash scripts, so:\n\n\n```python\nbash CompileLaTeX.sh FirstExample\n```\n\n*Why have I not written the `.tex` extension of `FirstExample` in the command above? Can you make this bash script more convenient to use?*\n\n## A few $\\LaTeX$ basics\n\n### Spaces, new lines and special characters\n\n* Several spaces in your text editor are treated as one space in the typeset document\n* Several empty lines are treated as one empty line\n* One empty line defines a new paragraph\n* Some characters are \"special\": # $ % ^ & _ { } ~ \\\n\nTo type these special characters, you have to add a \"backslash\" in front, e.g., \\\\\\$ produces $\\$$.\n\n### Document structure:\n\n* Each LaTeX command starts with \\\\ . For example, to get $\\LaTeX$, you need `\\LaTeX`\n* The first command is always `\\\\`documentclass`` defining the type of document (e.g., `article, book, report, letter`).\n* You can set several options. For example, to set size of text to 10 points and the letter paper size: \n`\\documentclass[10pt,letterpaper]{article}`.\n* After having declared the type of document, you can specify packages you want to use. The most useful are:\n \n `\\usepackage{color}`: use colors for text in your document.\n\n `\\usepackage{amsmath,amssymb}`: American Mathematical Society formats and commands for typesetting mathematics.\n\n `\\usepackage{fancyhdr}`: fancy headers and footers.\n\n `\\usepackage{graphicx}`: include figures in pdf, ps, eps, gif and jpeg.\n\n `\\usepackage{listings}`: typeset source code for various programming languages.\n\n `\\usepackage{rotating}`: rotate tables and figures.\n\n `\\usepackage{lineno}`: line numbers.\n\n* Once you select the packages, you can start your document with `\\begin{document}`, and end it with `\\end{document}`.\n\n### Typesetting math\n\nThere are two ways to display math\n\n1. Inline mathematics (i.e., within the text).\n\n2. Stand-alone, numbered equations and formulae.\n\nFor inline math, the \"dollar\" sign flanks the math to be typeset. For example, the code:\n\n```\n$\\int_0^1 p^x (1-p)^y dp$\n```\n\nbecomes $\\int_0^1 p^x (1-p)^y dp$\n\nFor numbered equations (almost always a great idea), LaTeX provides the\n`equation` environment:\n\n```\n\\begin{equation}\n \\int_0^1 \\left(\\ln \\left( \\frac{1}{x} \\right) \n \\right)^y dx = y!\n\\end{equation}\n```\n\nbecomes \n\n$$\\int_0^1 \\left(\\ln \\left( \\frac{1}{x} \\right) \\right)^y dx = y!$$\n\n## LaTeX templates\n\nThere a lots of useful LaTeX templates out there. I have added some templates in the `TheMulQuaBio` repo that you should have a look and play around with. Or just google \"latex template\" along with the name of a journal you want! \n\n## A few more tips\n\nThe following tips might prove handy:\n\n* LaTeX has a full set of symbols and operators (plenty of lists online)\n* Long documents can be split into separate `.tex` documents and combined using `input`\n* Long documents can be split into separate `.tex` documents and Figures can be included using the `graphicx` package\n* You can use Mendeley or Zotero to export and maintain `.bib` files\n* You can redefine environments and commands in the preamble\n\n## Practicals\n\nTest `CompileLaTeX.sh` with `FirstExample.tex` and bring it under verson control under`Week1` in your repository. Make sure that `CompileLaTeX.sh` will work if I ran it from my computer using `FirstExample.tex` as an input.\n\n#### Practicals wrap-up\n\nMake sure you have your `Week 1` directory organized with `Data`, `Sandbox` and `Code` with the necessary files and this week's (functional!) scripts in there. Every script should run without errors on my computer. This includes the five solutions (single-line commands you came up with) in `UnixPrac1.txt`.\n\n*Commit and push everything by next Wednesday 5 PM.*\n\n## Readings & Resources\n\n* [The Visual LaTeX FAQ: sometimes it is difficult to describe what you want to do!](http://get-software.net/info/visualFAQ/visualFAQ.pdf)\n* Myriad online resources for LaTeX, including: \n * [www.http://en.wikibooks.org/wiki/LaTeX/Introduction](www.http://en.wikibooks.org/wiki/LaTeX/Introduction)\n * [www.ctan.org/tex-archive/info/lshort/english/](www.ctan.org/tex-archive/info/lshort/english/)\n * [http://ftp.uni-erlangen.de/mirrors/CTAN/info/lshort/english/lshort.pdf](http://ftp.uni-erlangen.de/mirrors/CTAN/info/lshort/english/lshort.pdf)\n* [Beautiful presentations in LaTeX](http://tug.org/pracjourn/2005-2/miller/miller.pdf)\n* [Bibliographies in LaTeX](http://schneider.ncifcrf.gov/latex.html)\n* [$\\LaTeX$ table generator](http://www.tablesgenerator.com/)\n", "meta": {"hexsha": "851735aee1b76643cc8ec58e12fda2b5a2de0425", "size": 17503, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/04-LaTeX.ipynb", "max_stars_repo_name": "mathemage/TheMulQuaBio", "max_stars_repo_head_hexsha": "63a0ad6803e2aa1b808bc4517009c18a8c190b4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-12T13:33:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-12T13:33:14.000Z", "max_issues_repo_path": "notebooks/04-LaTeX.ipynb", "max_issues_repo_name": "OScott19/TheMulQuaBio", "max_issues_repo_head_hexsha": "197d710f76163469dfc7fa9d2d95ba3a739eccc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/04-LaTeX.ipynb", "max_forks_repo_name": "OScott19/TheMulQuaBio", "max_forks_repo_head_hexsha": "197d710f76163469dfc7fa9d2d95ba3a739eccc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8671679198, "max_line_length": 2894, "alphanum_fraction": 0.6082957207, "converted": true, "num_tokens": 3478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. YES", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.1510587724466118}} {"text": "Notebook is a useful tool for data scientists: It allows us to use coding and presentation tools together. \n\n\n```python\n# we can code\n\nprint(\"Welcome to DATA601!\")\n```\n\n Welcome to DATA601!\n\n\n__we can create headers of different sizes__\n\n# Header\n\n## Header\n\n### Header\n\n#### Header\n\n__we can create bullet points__\n\n- Item\n- item\n\n__we can order items__\n\n1. item 1\n1. item 2\n\n__we can write mathematical formulas__\n\nsimple ones:\n\n$$ X^{n} = Y^{n} + Z^{n} $$\n\nor a litte bit complicated ones:\n\n\\begin{align}\n\\nabla \\times \\vec{\\mathbf{B}} -\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{E}}}{\\partial t} & = \\frac{4\\pi}{c}\\vec{\\mathbf{j}} \\\\ \\nabla \\cdot \\vec{\\mathbf{E}} & = 4 \\pi \\rho \\\\\n\\nabla \\times \\vec{\\mathbf{E}}\\, +\\, \\frac1c\\, \\frac{\\partial\\vec{\\mathbf{B}}}{\\partial t} & = \\vec{\\mathbf{0}} \\\\\n\\nabla \\cdot \\vec{\\mathbf{B}} & = 0\n\\end{align}\n\n__we can create links__\n\n[Jupyter notebook Documentation](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html)\n\n__we can embed codes into text__\n\n```python\n\nfor i in range(10):\n if i%5 == 0:\n print(\"{} is divisible by 5\".format(i))\n else:\n print(\"{} is not divisible by 5\".format(i))\n```\n\n\n__we can write html__\n\n\n\n__we can create tables__\n\n| Column 1 | Column 2 | Column 3 |\n| :------------- | :----------: | -----------: |\n| Cell Contents | More Stuff | And Again |\n| You Can Also | Put Pipes In | Like this |\n| More | Items | Added |\n\n\n__we can create colored boxes for tips and notes__\n\n
\nTip: Use blue boxes (alert-info) for tips and notes. \nIf it’s a note, you don’t have to include the word “Note”.\n
\n\n
\nExample: Use yellow boxes for examples that are not \ninside code cells, or use for mathematical formulas if needed.\n
\n\n ***\n\nFor more on what you can do with jupyter-notebook markdowns check out online tutorials and documentation. I find this blog post particularly interesting.\n\n[IBM - Markdown Tutorial](https://www.ibm.com/support/knowledgecenter/SSHGWL_1.2.3/analyze-data/markd-jupyter.html)\n\n\n```python\n!ls /Users/mguner/Desktop/\n```\n\n Screen Shot 2020-08-28 at 1.10.56 PM.png\r\n Screen Shot 2020-08-28 at 6.40.19 PM.png\r\n Screen Shot 2020-08-28 at 6.40.35 PM.png\r\n Screen Shot 2020-08-29 at 6.54.04 PM.png\r\n USG.png\r\n git_logo.jpeg\r\n git_logo.png\r\n\n\n\n\n\n\nMore button examples\n\n\n```python\nimport pandas as pd\n```\n\n\n```python\npd.DataFrame({\"Data601\": [\"Murat\", \"Marry\", \"Stu\"], \"Data602\":[\"John\", \"Mike\", \"Alice\"]})\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Data601Data602
0MuratJohn
1MarryMike
2StuAlice
\n
\n\n\n\n\n\n
\n

Basic Table

\n

The .table class adds basic styling (light padding and only horizontal dividers) to a table:

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
FirstnameLastnameEmail
JohnDoejohn@example.com
MaryMoemary@example.com
JulyDooleyjuly@example.com
\n
\n\n
\n Success! You should read this message.\n
\n", "meta": {"hexsha": "0609a76653a801866547b4cfb674e22a43af96b4", "size": 8236, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week-1/Prep/Notebook_Tools.ipynb", "max_stars_repo_name": "jaredfincke/UMBC_Data601", "max_stars_repo_head_hexsha": "0507d287391f8e857f2f4aa52e0131f4f893879a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-09-03T20:35:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-05T00:57:25.000Z", "max_issues_repo_path": "week-1/Prep/Notebook_Tools.ipynb", "max_issues_repo_name": "jaredfincke/UMBC_Data601", "max_issues_repo_head_hexsha": "0507d287391f8e857f2f4aa52e0131f4f893879a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-10-15T20:36:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:31:45.000Z", "max_forks_repo_path": "week-1/Prep/Notebook_Tools.ipynb", "max_forks_repo_name": "jaredfincke/UMBC_Data601", "max_forks_repo_head_hexsha": "0507d287391f8e857f2f4aa52e0131f4f893879a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:34:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T16:05:56.000Z", "avg_line_length": 26.5677419355, "max_line_length": 211, "alphanum_fraction": 0.4602962603, "converted": true, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758367247085, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.1508838951146712}} {"text": "```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import YouTubeVideo\nfrom functools import partial\nYouTubeVideo_formato = partial(YouTubeVideo, modestbranding=1, disablekb=0,\n width=640, height=360, autoplay=0, rel=0, showinfo=0)\n```\n\n(unit2-linear-2)=\n\n# Regresión lineal, Sobreajuste y Validación\n\n## Introducción\n\nUna **regresión** consiste en **ajustar** un modelo paramétrico del tipo\n\n$$\nf_\\theta: x \\rightarrow y\n$$\n\nEl ajuste de este modelo nos permite\n\n- Entender como dos o más variables se relacionan\n- Predecir una variable en función de otras\n\nEstos son los objetivos del **análisis de regresión**\n\nHablamos particularmente de **regresión lineal** cuando el modelo $f_\\theta$ es **lineal en sus parámetros**. Es decir que lo podemos escribir como\n\n$$\n\\begin{align}\nf_\\theta(x) &= \\langle x, \\theta \\rangle \\nonumber \\\\\n&= \\begin{pmatrix} x_1 & x_2 & \\ldots & x_M \\end{pmatrix} \\begin{pmatrix} \\theta_1 \\\\ \\theta_2 \\\\ \\vdots \\\\ \\theta_M \\end{pmatrix} \n\\end{align}\n$$\n\ndonde $x$ representa los atributos (variables independientes) y $\\theta$ los parámetros a ajustar. Ajustar el modelo se refiere a encontrar el valor óptimo de $\\theta$. Como vimos la clase pasada\n\n- Si nuestro sistema es cuadrado podemos usar inversión\n- Si nuestro sistema es rectangular podemos usar **mínimos cuadrados**\n\nEl ajuste del modelo se realiza en base a **datos**, que podemos visualizar como un conjunto de $N$ tuplas $(\\vec x_i, y_i)$ con $i=1,2,\\ldots,N$. Por otro lado la cantidad parámetros del modelo es $M$, es decir el largo del vector $\\theta$. \n\nLuego\n\n- Cada tupla o ejemplo aporta una ecuación al sistema\n- Cada parámetro aporta una incognita al sistema\n\nA continuación generalizaremos algunos conceptos vistos en {ref}`unit2-linear-1`\n\n## Regresión lineal multivariada\n\nEn la lección anterior ajustamos el modelo\n\n$$\nf_\\theta(x) = \\theta_0 + \\theta_1 x,\n$$\n\ncon dos parámetros y una variable independiente. El modelo anterior corresponde al modelo lineal más básico: una recta. \n\nEn un caso más general podríamos querer ajustar un modelo con un $x$ multidimensional\n\nSi tenemos $d$ atributos podemos construir un vector $\\vec x = (x_1, x_2, \\ldots, x_d)$ y considerar el siguiente modelo lineal\n\n$$\n\\begin{align}\nf_\\theta(\\vec x) &= \\theta_0 + \\theta_1 x_1 + \\theta_2 x_2 + \\ldots \\theta_d x_d \\nonumber \\\\\n&= \\theta_0 + \\sum_{k=1}^d \\theta_k x_k \\nonumber \\\\\n\\end{align}\n$$\n\nEsto corresponde a ajustar un **hiperplano**\n\n### Ejercicio práctico\n\nPara los datos de consumo de helados, encuentre los parámetros del **hiperplano** que ajuste mejor los datos \n\n$$\n\\text{consumo} = \\theta_0 + \\theta_1 \\cdot \\text{temperatura} + \\theta_2 \\cdot \\text{precio}\n$$\n\n- Identifique y construya el vector $b$ y la matriz $A$ ¿Cuánto vale $N$ y $M$?\n- ¿Es este un sistema cuadrado o rectangular? ¿ Es sobre o infra-determinado?\n- Encuentre $\\theta$ que minimiza la suma de errores cuadráticos\n- Grafique el plano encontrado\n\n**Solución paso a paso con comentarios**\n\n\n```python\nYouTubeVideo_formato('h6KrwiQv5qU')\n```\n\n## Modelos lineales en sus parámetros pero no en sus entradas\n\nUna regresión lineal puede considerar transformaciones \"no lineales\" sobre la entrada $x$. Llamaremos función base $\\phi_j(\\cdot)$ a estas transformaciones. \n\nLuego el modelo más general de regresión lineal en sus parámetros es\n\n$$\ny = f_\\theta (x) = \\sum_{j=0}^N \\theta_j \\phi_j (x)\n$$\n\nEl modelo sigue siendo lineal en sus parámetros. Por ende lo podemos ajustarnos con las mismas herramientas que vimos anteriormente. La ventaja de usar funciones base es que el modelo es más flexible, es decir que podemos modelar comportamientos más diversos en los datos. \n\nVeamos algunos ejemplos concretos de regresión lineal con funciones base\n\n**Ejemplo 1: Regresión polinomial**\n\nSi usamos $\\phi_j(x) = x^j$ tendríamos\n\n$$\ny = f_\\theta (x) = \\theta_0 + \\theta_1 x + \\theta_2 x^2 + \\ldots,\n$$\n\nque nos puede servir cuando la relación entre las variables es cuadrática, cúbica o de orden superior\n\n\n**Ejemplo 2: Regresión trigonométrica**\n\nSi usamos $\\phi_j(x) = \\cos(2\\pi j x)$ tendríamos\n\n$$\ny = f_\\theta (x) = \\theta_0 + \\theta_1 \\cos(2\\pi x) + \\theta_2 \\cos(4 \\pi x) + \\ldots,\n$$\n\nque nos puede servir si queremos modelar funciones periódicas pares. Si usamos seno en lugar de coseno podríamos modelar funciones periódicas impares. Si usamos una combinación de seno y coseno podríamos modelar cualquier función periódica (serie de Fourier)\n\n\n### Ejercicio práctico\n\nConsidere los siguientes datos:\n\n\n```python\nnp.random.seed(1234)\nx = np.linspace(0, 2, num=10)\ny = 2*np.cos(2.0*np.pi*x) + np.sin(4.0*np.pi*x) + 0.4*np.random.randn(len(x))\nx_plot = np.linspace(np.amin(x), np.amax(x), num=100)\n```\n\n- Realice una regresión polinomial sobre $(x, y)$ \n- Muestre graficamente los datos y el resultado de $f_\\theta(x_{plot})$ \n- Use Jupyter widgets para modificar dinamicamente el grado del polinomio entre $M\\in[1, 15]$\n\n**Solución paso a paso con comentarios**\n\n\n\n```python\nYouTubeVideo_formato('KvIyri8lVq4')\n```\n\n¿Qué ocurre cuando $N\\geq M$?\n\n> Nuestro modelo se sobre ajusta a los datos\n\nEstudiaremos esto en detalle más adelante\n\n## Sistema infradeterminado (caso $N>M$)\n\nEl caso del sistema infradeterminado es aquel que tiene más incognitas (parámetros) que ecuaciones. Este tipo de sistema tiene infinitas soluciones\n\n\nConsidere por ejemplo las soluciones posibles de ajustar un sistema polinomial de segundo orden (tres parámetros) con sólo dos ejemplos\n\n\n```python\nx = np.array([-2, 2])\ny = np.array([4, 4])\nfig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)\nx_plot = np.linspace(-3, 3, num=100)\nthetas = np.zeros(shape=(200, 3))\nfor i, a in enumerate(np.linspace(-10, 10, num=thetas.shape[0])):\n ax.plot(x_plot, a + (1 - a/4)*x_plot**2)\n thetas[i:] = [a, 0, (1-a/4)]\nax.scatter(x, y, s=100, c='k', zorder=10);\n```\n\nMás en la práctica, la consecuencia de que el sistema sea infradeterminado es que $A^T A$ no es invertible. \n\nPara resolver el problema infradeterminado se debe una restricción adicional. La más típica es que el vector solución tenga norma mínima, por ejemplo\n\n$$\n\\min_\\theta \\| x \\|_2^2 ~\\text{s.a.}~ Ax =b\n$$\n\nque se resuelve usando $M$ [multiplicadores de Lagrange](https://es.wikipedia.org/wiki/Multiplicadores_de_Lagrange) $\\lambda$ como sigue\n\n$$\n\\begin{align}\n\\frac{d}{dx} \\| x\\|_2^2 + \\lambda^T (b - Ax) &= 2x - \\lambda^T A \\nonumber \\\\\n&= 2Ax - A A^T \\lambda \\nonumber \\\\\n&= 2b - A A^T \\lambda = 0 \n\\end{align}\n$$\n\nDe donde obtenemos que $\\lambda = 2(AA^T)^{-1}b$ y por lo tanto $x = \\frac{1}{2} A^T \\lambda = A^T (A A^T)^{-1} b$, donde $A^T (A A^T)^{-1}$ se conoce como la pseudo-inversa \"por la derecha\"\n\nLa función `np.linalg.lstsq` usa la pseudo inversa izquierda automáticamente si $NM$\n\nEs decir que NumPy asume que la mejor solución del sistema infradeterminado es la de **mínima norma euclidiana**\n\n## Complejidad, sobreajuste y generalización\n\nUn modelo con más parámetros es más flexible pero también más complejo\n\n**Complejidad:** grados de libertad de un modelo\n\nComo vimos en el ejercicio práctico anterior un exceso de flexibilidad puede producir un \"ajuste perfecto\". Un ajuste perfecto es generalmente una mala idea pues nuestros datos casi siempre tendrán ruido\n\n**Sobreajuste:** Ocurre cuando el modelo se ajusta al ruido de los datos\n\nConsidere los siguientes datos ajustados con tres modelos de distinta complejidad\n\n\n```python\nx = np.linspace(-3, 3, num=10)\nx_plot = np.linspace(np.amin(x), np.amax(x), num=100)\ny_clean = np.poly1d([2, -4, 20]) # 2*x**2 -4*x +20\nnp.random.seed(1234)\ny = y_clean(x) + 3*np.random.randn(len(x))\npoly_basis = lambda x, M : np.vstack([x**k for k in range(M)]).T\nfig, ax = plt.subplots(1, 3, figsize=(8, 3), \n tight_layout=True, sharex=True, sharey=True)\n\nfor i, (M, title) in enumerate(zip([2, 3, 10], [\"muy simple\", \"adecuado\", \"muy complejo\"])):\n ax[i].plot(x_plot, y_clean(x_plot), lw=2, alpha=.5, label='Modelo real')\n ax[i].scatter(x, y, label='observaciones'); \n theta = np.linalg.lstsq(poly_basis(x, M), y, rcond=None)[0]\n ax[i].plot(x_plot, np.dot(poly_basis(x_plot, M), theta), 'k-', label='Modelo apredido')\n ax[0].legend()\n ax[i].set_title(title)\n```\n\nDel ejemplo podemos ver que cuando el modelo se sobreajusta pierde capacidad de generalización\n\n**Generalización:** Capacidad de predecir adecuadamente los datos que no se usan en el ajuste\n\nLos siguientes mecanísmos se pueden usar para evitar el sobreajuste y mejorar la capacidad de generalización\n\n- Validación: Escoger la complejidad mediante pruebas de validación \n- Regularización: Penalizar la complejidad de forma adicional\n\nSe revisará en detalle la primera opción\n\n### Introducción a las técnicas de validación cruzada\n\nValidación cruzada es un conjunto de técnicas donde se busca dividir el conjunto de datos en tres subconjuntos\n\n1. Entrenamiento: Datos que se ocupan para **ajustar el modelo**\n1. Validación: Datos que se ocupan para **calibrar el modelo**\n1. Prueba: Datos que se ocupan para **comparar distintos modelos**\n\nLa forma más simple de crear estos subconjuntos es permutar aleatoriamente los índices de los elementos y dividir los índices en distintas proporciones. Tipicamente se usa una proporción 60/20/20 o 80/10/10 dependiendo del tamaño de la base de datos original. Este tipo de validación cruzada se llama **hold-out**.\n\n\n\nEl permutar produce un particionamiento aleatorio que busca que cada subconjunto sea **representativo** de la base de datos original. Más adelante veremos técnicas de validación cruzada más sofisticadas.\n\nPara evaluar la calidad de nuestro modelo medimos el error en cada uno de estos subconjuntos\n\n1. El ajuste de los parámetros se realiza minimizando el **error de entrenamiento**\n1. Calibrar el modelo, es decir seleccionar los mejores hiperparámetros del modelo, se realiza minimizando el **error de validación**. En el caso particular de la regresión polinomial el hiperparámetro que debemos calibrar es el grado del polinomio. \n1. La capacidad de generalización del modelo final se mide usando el **error de prueba**\n\nLa siguiente figura muestra un esquema iterativo de validación\n\n\n\nUsando este esquema podemos detectar facilmente un modelo sobreajustado ya que presentará un buen desempeño en entrenamiento pero un desempeño deficiente en validación\n\n\n\n### Ejercicio práctico\n\nConsidere los siguientes datos\n\n\n```python\nx = np.linspace(-5, 5, num=30)\nx_plot = np.linspace(np.amin(x), np.amax(x), num=100)\ny_clean = np.poly1d([0.1, -0.3, -2, 10]) \nnp.random.seed(1234)\ny = y_clean(x) + 1.5*np.random.randn(len(x))\npoly_basis = lambda x, M : np.vstack([x**k for k in range(M)]).T\n```\n\nConsidere el modelo de regresión polinomial\n\n- Separé los datos $(x,y)$ aleatoriamente para crear conjuntos de entrenamiento y validación. Se recomienda usar la función `np.random.permutation` \n- Entrene con el conjunto de entrenamiento\n- Encuentre el grado de polinomio que mejor ajusta los datos del conjunto de validación en base al error cuadrático medio:\n\n$$\n\\text{MSE} = \\frac{1}{N} \\sum_{i=1}^N e_i^2\n$$\n\ndonde $e_i = y_i - f_\\theta(x_i)$\n\n**Solución paso a paso con comentarios**\n\n\n```python\nYouTubeVideo_formato('Ydl2g6w3Wog')\n```\n\n### (Extra) ¿En qué consiste la regularización?\n\nConsiste en agregar una penalización adicional al problema \n\nEl ejemplo clásico es agregar que la solución tenga norma mínima\n\n$$\n\\min_x \\|Ax-b\\|_2^2 + \\lambda \\|x\\|_2^2\n$$\n\nEn este caso la solución es\n\n$$\n\\hat x = (A^T A + \\lambda I)^{-1} A^T b\n$$\n\nque se conoce como **ridge regression** o **regularización de Tikhonov**\n\n$\\lambda$ es un hiper-parámetro del modelo y debe ser escogido por el usuario (usando validación)\n\n## Resumen de la lección\n\nEn esta lección hemos aprendido a:\n\n- Resolver la regresión lineal multivariada\n- Generalizar la regresión lineal con funciones base (polinomios)\n- Calibrar nuestros modelos usando técnicas de validación\n\n\n```python\n\n```\n", "meta": {"hexsha": "ef730ced8843ee014607b0d46ae0e3db343dd13a", "size": 19835, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "contents/sklearn/2_linear_regression.ipynb", "max_stars_repo_name": "phuijse/PythonBook", "max_stars_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contents/sklearn/2_linear_regression.ipynb", "max_issues_repo_name": "phuijse/PythonBook", "max_issues_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contents/sklearn/2_linear_regression.ipynb", "max_forks_repo_name": "phuijse/PythonBook", "max_forks_repo_head_hexsha": "16792e9cc3717ebb7f3603cd8bb39613dd66521b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1135225376, "max_line_length": 323, "alphanum_fraction": 0.5891605747, "converted": true, "num_tokens": 3657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.1508838838527251}} {"text": "|

Name

|

Date

|\n| ---------------------------------------------------| ------------------------------------- |\n|

Diaaeldin SHALABY

| 23.05.2021 |\n\n

Hands-on AI II

\n

Unit 4 — Recurrent Neural Networks (Assignment)

\n\nAuthors: B. Schäfl, S. Lehner, J. Brandstetter
\nDate: 30-04-2021\n\nThis file is part of the \"Hands-on AI II\" lecture material. The following copyright statement applies to all code within this file.\n\nCopyright statement:
\nThis material, no matter whether in printed or electronic form, may be used for personal and non-commercial educational use only. Any reproduction of this manuscript, no matter whether as a whole or in parts, no matter whether in printed or in electronic form, requires explicit prior acceptance of the authors.\n\n

Table of contents

\n
    \n
  1. The Latch Sequence Data Set
  2. \n
      \n
    1. Visualizing data set statistics
    2. \n
    3. Splitting and preparing
    4. \n
    \n
  3. Tackling Sequence Data with CNNs
  4. \n
      \n
    1. Approximating performances of random models
    2. \n
    3. Applying 1D convolutions to sequences
    4. \n
    5. Analyzing gradients of a CNN model
    6. \n
    \n
  5. Tackling Sequence Data with LSTMs
  6. \n
      \n
    1. Applying LSTMs to sequences
    2. \n
    3. Analyzing gradients of an initialized LSTM model
    4. \n
    5. Analyzing gradients of a trained LSTM model
    6. \n
    7. The effect of the forget gate in an LSTM
    8. \n
    \n
\n\n

How to use this notebook

\nThis notebook is designed to run from start to finish. There are different tasks (displayed in orange boxes) which require your contribution (in form of code, plain text, ...). Most/All of the supplied functions are imported from the file u4_utils.py which can be seen and treated as a black box. However, for further understanding, you can look at the implementations of the helper functions. In order to run this notebook, the packages which are imported at the beginning of u4_utils.py need to be installed.\n\n\n```python\n# Import pre-defined utilities specific to this notebook.\nimport u4_utils as u4\n\n# Import additional utilities needed in this notebook.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport torch\n\n# Setup Jupyter notebook (warning: this may affect all Jupyter notebooks running on the same Jupyter server).\nu4.setup_jupyter()\n```\n\n\n\n\n\n\n

Setting up notebook ... finished.

\n\n\n\n\n

Module versions

\nAs mentioned in the introductiory slides, specific minimum versions of Python itself as well as of used modules is recommended.\n\n\n```python\nu4.check_module_versions()\n```\n\n Installed Python version: 3.8 (✓)\n Installed numpy version: 1.19.1 (✓)\n Installed pandas version: 1.1.3 (✓)\n Installed PyTorch version: 1.7.1 (✓)\n Installed scikit-learn version: 0.23.2 (✓)\n Installed scipy version: 1.5.0 (✓)\n Installed matplotlib version: 3.3.1 (✓)\n Installed seaborn version: 0.11.0 (✓)\n Installed PIL version: 8.0.0 (✓)\n Installed rdkit version: 2020.09.1 (✓)\n\n\n

The Latch Sequence Data Set

\n

In the accompanying excercise class, the latch task was presented. You'll be working with the same data set in this assignment. The original latch task was introduced by Hochreiter and Mozer:\n

\n Sepp Hochreiter, Michael Mozer, 2001. A discrete probabilistic memory model for discovering dependencies in time. Artificial Neural Networks -- ICANN 2001, 13, pp.661-668.\n

\n\n

The essence of this task is that a sequence of inputs is presented, beginning with one of two symbols, A or B, and after a variable number of time steps, the model has to output a corresponding symbol. Thus, the task requires memorizing the original input over time. It has to be noted, that in the original task desription, both class-defining symbols must only appear at the first position of an instance.

\n\n

The modified version of this task used in this assignment is identical to the one discussed during the accompanying exercise, with the difference of a higher amount of possible targets. Defining arguments are:\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ArgumentValue (used in this assignment)Description
num_samples4096Amount of samples of the full dataset.
num_instances48Amount of instances per sample (sample length).
num_characters26Amount of different characters (size of the one-hot encoded vector).
num_targets25Amount of different characters used as possible targets.
seed42Random seed used to generate the samples of the data set.

\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Generate a latch sequence data set with the properties as described in the table above.
  • \n
  • Visualize the last sequence of the data set in tabular form, with all $1$ \n in bold magenta and all $0$ in lighter.
  • \n
  • Visualize the first $32$ samples in a heatmap, once without and once with a corresponding prefix-mask.
  • \n
  • Interpreting the previous visualizations, which character of the chosen alphabet determines the prefix?
  • \n
\n
\n\n\n```python\ndata_latch = u4.LatchSequenceSet(\n num_samples=4096,\n num_instances=48,\n num_characters=26,\n num_targets=25,\n seed=42)\n\n# Visualize the last generated sequence of the latch data set.\ndata_sample = pd.DataFrame(data_latch[-1][0].transpose(0, 1).numpy()).astype(int)\n\n# data_sample.style.applymap(lambda _: f'color: {r\"magenta\" if _ == 1.0 else r\"lighter\"};font-weight: bold')\n```\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Specify batch as well as test size.\nbatch_size = 32\n\n# Create data loader of training set.\nsampler_train = torch.utils.data.SubsetRandomSampler(list(range(32)))\n\n```\n\n\n```python\n# Set default plotting style as well as random seed for reproducibility.\nsns.set()\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Prepare mini-batch of latch sequence data set for plotting.\ndata_heatmap = iter(data_loader_train).next()[0]\ndata_heatmap = pd.DataFrame(map(lambda _: torch.argmax(_, dim=1).numpy(), data_heatmap))\n\n# Plot heatmap of a mini-batch of the latch sequence data set w.r.t. the comprised characters.\nu4.plot_heatmap(data=data_heatmap, prefix_mask=True, prefix_index=data_latch.num_targets, figsize=(14, 7))\nu4.plot_heatmap(data=data_heatmap, prefix_mask=False, prefix_index=data_latch.num_targets, figsize=(14, 7))\n```\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Linearly split the data set into a training and a test set in a ratio of $3:1$ (use a SubsetRandomSampler and a batch size of $48$).
  • \n
  • Compute and print the amount of samples of each of the respective sets and verify the $3 : 1$ split.
  • \n
  • Visualize the character counts of the first training mini-batch appropriately. What is the count of the prefix character?
  • \n
\n
\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Specify batch as well as test size.\nbatch_size = 48\ntest_size = min(max(1, data_latch.num_samples // 4), len(data_latch) - 1)\n\n# Create data loader of training set.\nsampler_train = torch.utils.data.SubsetRandomSampler(list(range(\n test_size, data_latch.num_samples)))\ndata_loader_train = torch.utils.data.DataLoader(\n dataset=data_latch, batch_size=batch_size, sampler=sampler_train)\n\n# Create data loader of test set.\nsampler_test = torch.utils.data.SubsetRandomSampler(list(range(test_size)))\ndata_loader_test = torch.utils.data.DataLoader(\n dataset=data_latch, batch_size=batch_size, sampler=sampler_test)\n```\n\n\n```python\nprint(f'The training set consists of \"{len(sampler_train)}\" samples, '\n f'whereas the test set comprises \"{len(sampler_test)}\" samples.')\n```\n\n The training set consists of \"3072\" samples, whereas the test set comprises \"1024\" samples.\n\n\n\n```python\n# Set default plotting style as well as random seed for reproducibility.\nsns.set()\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Prepare mini-batch of latch sequence data set for plotting.\ndata_histogram = iter(data_loader_train).next()[0]\ndata_histogram = pd.DataFrame(map(lambda _: torch.argmax(_, dim=1).numpy(), data_histogram))\ndata_histogram = data_histogram.to_numpy().flatten()\n\n# Plot heatmap of a mini-batch of the latch sequence data set w.r.t. the comprised characters.\nfig, ax = plt.subplots(figsize=(14, 7))\ncount_plot = sns.countplot(x=data_histogram, ax=ax)\n_ = count_plot.set(xlabel=r'Character', ylabel=r'Count')\n```\n\n

Tackling Sequence Data with CNNs

\n

During the accompanying exercise class, a dense feed-forward network was presented as some kind of baseline. Afterwards, recurrent architectures were applied. In this exercise, you'll be tasked with implementing a convolutional architecture for handling sequence data.

\n\n
\n The following code snippet is taken from the accompanying exercise notebook. You do not need to modify it for this assignment.\n
\n\n\n```python\nclass TheMightyDice(torch.nn.Module):\n \"\"\"\n Dice roll \"network\" tailored to deliver random outcomes.\n \"\"\"\n \n def __init__(self, output_size: int):\n super(TheMightyDice, self).__init__()\n self.__output_size = output_size\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return torch.rand(size=(x.shape[0], self.__output_size))\n```\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Test a TheMightyDice instance on the latch sequence test set. Do you expect this result? Comment on your answer.
  • \n
  • Assume uniformly distributed targets. If a model would always predict the same class, what would the accuracy be?
  • \n
\n
\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Evaluate dice model on test data set.\n\nperformance = u4.test_network(\n model=TheMightyDice(25), data_loader=data_loader_test)\nprint(f'\\nFinal loss: {performance[0]:.4f} / Final accuracy: {performance[1]:.4f}')\n```\n\n \n Final loss: 0.0701 / Final accuracy: 0.0420\n\n\nThe accuracy is very low as expected for a random function.\n\nIf a model would always predict the same class, I think the accuracy would be 50%.\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Implement a function for computing the output size of a convolution operation. Hint: have a look at the PyTorch documentation. You may also use your implementation from the first assignment.
  • \n
  • Implement a class CNN with the following architecture:
  • \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PositionElementComment
0input-
11D convolution$256$ output channels and a configurable kernel size (specified as an argument to \\_\\_init\\_\\_)
2ReLU-
31D convolution$256$ output channels and the same kernel size as the 1D convolution at position $1$
4ReLU-
5fully connectednum_targets output features (as specified during the data set creation)
6output-
\n
    \n
  • Train a CNN network for $15$ epochs, print the training accuracy as well as the loss per epoch and report the final test set loss and accuracy. Use a kernel size of $1$.
  • \n
  • Repeat the same procedure with a second CNN but a kernel size of $3$. Do you observe any differences? Comment and interpret your results.
  • \n
\n
\n\n\n```python\nclass CNN(torch.nn.Module):\n \"\"\"\n CNN tailored to process Fashion-MNIST data.\n \"\"\"\n \n def __init__(self,kernel_size):\n super(CNN, self).__init__()\n self.kernel_size = kernel_size\n self.output_features = data_latch.num_targets\n self.network = torch.nn.Sequential(\n torch.nn.Conv1d(48, 256, self.kernel_size),\n torch.nn.ReLU(True),\n torch.nn.Conv1d(256, 256, self.kernel_size),\n torch.nn.ReLU(True),\n torch.nn.Flatten(),\n torch.nn.Linear(6656, self.output_features)\n )\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \n return self.network(x)\n```\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create DenseFNN instance and the corresponding optimizer to use.\ntarget_device = torch.device(r'cpu')\ninput_size = data_latch.num_instances * data_latch.num_characters\n\ncnn_model = CNN(kernel_size=1).to(target_device)\noptimizer = torch.optim.Adam(cnn_model.parameters(), lr=1e-3)\n\n# Print the architecture of the DenseFNN instance.\nprint(cnn_model, end='\\n\\n')\n\n# Train and evaluate DenseFNN instance on the latch sequence training set.\nnum_epochs = 15\nfor epoch in range(num_epochs):\n \n # Train DenseFNN instance for one epoch.\n u4.train_network(\n model=cnn_model, data_loader=data_loader_train, device=target_device, optimizer=optimizer)\n \n # Evaluate current DenseFNN instance.\n performance = u4.test_network(\n model=cnn_model, data_loader=data_loader_train, device=target_device)\n \n # Print result of current epoch to standard out.\n print(f'Epoch: {str(epoch + 1).zfill(len(str(num_epochs)))} ' +\n f'/ Loss: {performance[0]:.4f} / Accuracy: {performance[1]:.4f}')\n\n# Evaluate final model on test data set.\nperformance = u4.test_network(\n model=cnn_model, data_loader=data_loader_test, device=target_device)\nprint(f'\\nFinal loss: {performance[0]:.4f} / Final accuracy: {performance[1]:.4f}')\n```\n\n CNN(\n (network): Sequential(\n (0): Conv1d(48, 256, kernel_size=(1,), stride=(1,))\n (1): ReLU(inplace=True)\n (2): Conv1d(256, 256, kernel_size=(1,), stride=(1,))\n (3): ReLU(inplace=True)\n (4): Flatten(start_dim=1, end_dim=-1)\n (5): Linear(in_features=6656, out_features=25, bias=True)\n )\n )\n \n Epoch: 01 / Loss: 0.0663 / Accuracy: 0.0833\n Epoch: 02 / Loss: 0.0583 / Accuracy: 0.1777\n Epoch: 03 / Loss: 0.0463 / Accuracy: 0.4072\n Epoch: 04 / Loss: 0.0323 / Accuracy: 0.6257\n Epoch: 05 / Loss: 0.0198 / Accuracy: 0.8076\n Epoch: 06 / Loss: 0.0112 / Accuracy: 0.9271\n Epoch: 07 / Loss: 0.0065 / Accuracy: 0.9714\n Epoch: 08 / Loss: 0.0028 / Accuracy: 0.9967\n Epoch: 09 / Loss: 0.0015 / Accuracy: 0.9997\n Epoch: 10 / Loss: 0.0008 / Accuracy: 1.0000\n Epoch: 11 / Loss: 0.0006 / Accuracy: 1.0000\n Epoch: 12 / Loss: 0.0004 / Accuracy: 1.0000\n Epoch: 13 / Loss: 0.0003 / Accuracy: 1.0000\n Epoch: 14 / Loss: 0.0003 / Accuracy: 1.0000\n Epoch: 15 / Loss: 0.0002 / Accuracy: 1.0000\n \n Final loss: 0.1828 / Final accuracy: 0.0547\n\n\n\n```python\nclass CNN(torch.nn.Module):\n \"\"\"\n CNN tailored to process Fashion-MNIST data.\n \"\"\"\n \n def __init__(self,kernel_size):\n super(CNN, self).__init__()\n self.kernel_size = kernel_size\n self.output_features = data_latch.num_targets\n self.network = torch.nn.Sequential(\n torch.nn.Conv1d(48, 256, self.kernel_size),\n torch.nn.ReLU(True),\n torch.nn.Conv1d(256, 256, self.kernel_size),\n torch.nn.ReLU(True),\n torch.nn.Flatten(),\n torch.nn.Linear(5632, self.output_features)\n )\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \n return self.network(x)\n```\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create DenseFNN instance and the corresponding optimizer to use.\ntarget_device = torch.device(r'cpu')\ninput_size = data_latch.num_instances * data_latch.num_characters\n\ncnn_model = CNN(kernel_size=3).to(target_device)\noptimizer = torch.optim.Adam(cnn_model.parameters(), lr=1e-3)\n\n# Print the architecture of the DenseFNN instance.\nprint(cnn_model, end='\\n\\n')\n\n# Train and evaluate DenseFNN instance on the latch sequence training set.\nnum_epochs = 15\nfor epoch in range(num_epochs):\n \n # Train DenseFNN instance for one epoch.\n u4.train_network(\n model=cnn_model, data_loader=data_loader_train, device=target_device, optimizer=optimizer)\n \n # Evaluate current DenseFNN instance.\n performance = u4.test_network(\n model=cnn_model, data_loader=data_loader_train, device=target_device)\n \n # Print result of current epoch to standard out.\n print(f'Epoch: {str(epoch + 1).zfill(len(str(num_epochs)))} ' +\n f'/ Loss: {performance[0]:.4f} / Accuracy: {performance[1]:.4f}')\n\n# Evaluate final model on test data set.\nperformance = u4.test_network(\n model=cnn_model, data_loader=data_loader_test, device=target_device)\nprint(f'\\nFinal loss: {performance[0]:.4f} / Final accuracy: {performance[1]:.4f}')\n```\n\n CNN(\n (network): Sequential(\n (0): Conv1d(48, 256, kernel_size=(3,), stride=(1,))\n (1): ReLU(inplace=True)\n (2): Conv1d(256, 256, kernel_size=(3,), stride=(1,))\n (3): ReLU(inplace=True)\n (4): Flatten(start_dim=1, end_dim=-1)\n (5): Linear(in_features=5632, out_features=25, bias=True)\n )\n )\n \n Epoch: 01 / Loss: 0.0669 / Accuracy: 0.0895\n Epoch: 02 / Loss: 0.0644 / Accuracy: 0.1904\n Epoch: 03 / Loss: 0.0552 / Accuracy: 0.2604\n Epoch: 04 / Loss: 0.0445 / Accuracy: 0.4502\n Epoch: 05 / Loss: 0.0324 / Accuracy: 0.6178\n Epoch: 06 / Loss: 0.0241 / Accuracy: 0.7116\n Epoch: 07 / Loss: 0.0174 / Accuracy: 0.8271\n Epoch: 08 / Loss: 0.0111 / Accuracy: 0.9141\n Epoch: 09 / Loss: 0.0064 / Accuracy: 0.9769\n Epoch: 10 / Loss: 0.0047 / Accuracy: 0.9889\n Epoch: 11 / Loss: 0.0027 / Accuracy: 0.9997\n Epoch: 12 / Loss: 0.0017 / Accuracy: 1.0000\n Epoch: 13 / Loss: 0.0011 / Accuracy: 1.0000\n Epoch: 14 / Loss: 0.0008 / Accuracy: 1.0000\n Epoch: 15 / Loss: 0.0007 / Accuracy: 1.0000\n \n Final loss: 0.1524 / Final accuracy: 0.0703\n\n\nfinal accuracy is surprisingly very low for both.\n\n
\n The following code snippet is taken from the accompanying exercise notebook. You do not need to modify it for this assignment.\n
\n\n\n```python\ndef collect_gradients(model: torch.nn.Module, loader: torch.utils.data.DataLoader) -> pd.DataFrame:\n \"\"\"\n Auxiliary function for collecting gradient magnitudes of a corresponding model w.r.t. the network input.\n \n :param model: model instance to be used for collecting gradients\n :param device: device to use for gradient collection\n :param loader: data loader supplying the samples used for collecting gradients\n :return: data frame comprising the gradient magnitudes of the loss function w.r.t. each input element\n \"\"\"\n model_state = model.training\n model.train()\n model.zero_grad()\n\n # Iterating over the data set and computing the corresponding gradients.\n device, gradients = next(model.parameters())[0].device, []\n criterion = torch.nn.CrossEntropyLoss()\n for batch_index, (data, target) in enumerate(loader):\n data, target = data.float().to(device), target.long().to(device)\n \n # Prepare network input for gradient recording.\n data.requires_grad_(True)\n data.register_hook(lambda _: gradients.append(_.cpu().abs()))\n\n # One forward\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n model.zero_grad()\n \n # Reset model state and return collected gradients.\n model.train(mode=model_state)\n return pd.DataFrame(torch.cat(gradients, dim=0).mean(dim=2).numpy())\n```\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Create a fresh instance of CNN and collect its gradients w.r.t. the network input using the latch sequence training set.
  • \n
  • Visualize the collected gradients accordingly. What do you observe? Comment on your results.
  • \n
\n
\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create DenseFNN instance and the corresponding optimizer to use.\ntarget_device = torch.device(r'cpu')\ninput_size = data_latch.num_instances * data_latch.num_characters\n\ncnn_model_2 = CNN(kernel_size=1).to(target_device)\n\n```\n\n\n```python\ngradient_data_CNN = collect_gradients(model=cnn_model_2, loader=data_loader_train)\n```\n\n\n```python\n# Set default plotting style.\nsns.set()\n\n# Prepare collected gradients for plotting.\ngradients_prepared = pd.melt(gradient_data_CNN, value_vars=gradient_data_CNN.columns)\ngradients_prepared.columns = (r'Timestep', r'Gradient Magnitude')\n\n# Define plotting figure and corresponding attributes.\nfig, ax = plt.subplots(figsize=(14, 7))\nax.set_title(r'CNN Gradient Magnitudes', fontsize=14)\nax.set(yscale=r'log')\n\n# Plot pre-processed gradients.\n_ = sns.boxplot(x=r'Timestep', y=r'Gradient Magnitude', data=gradients_prepared, ax=ax)\n```\n\n

Tackling Sequence Data with LSTMs

\n

During the accompanying exercise class, the Long Short-Term Memory (LSTM) was presented as a quite prominent and often used architecture in the recurrent case. It was designed and published by Hochreiter and Schmidhuber:\n

\n \n Hochreiter, S. and Schmidhuber, J., 1997. Long short-term memory. Neural computation, 9(8), pp.1735-1780.\n \n

\n\n

It has to be noted, that the most crucial part of the LSTM, the constant error carousel (CEC), was already discussed during Hochreiter's diploma thesis (in German):\n

\n \n Hochreiter, S., 1991. Untersuchungen zu dynamischen neuronalen Netzen. Diploma, Technische Universität München, 91(1).\n \n

\n\n

In contrast to most other recurrent architectures like the Elman RNN, the LSTM is a bit more complex, but equally more powerful:\n

\n \\begin{equation}\n \\begin{split}\n i_{t} &= \\sigma{\\left(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi}\\right)} \\\\\n \\color{red}{f_{t}} &\\color{red}{= \\sigma{\\left(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf}\\right)}} \\\\\n g_{t} &= \\tanh{\\left(W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg}\\right)} \\\\\n o_{t} &= \\sigma{\\left(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho}\\right)} \\\\\n c_{t} &= \\color{red}{f_{t}\\odot{}}c_{t-1} + i_{t}\\odot{}g_{t} \\\\\n h_{t} &= o_{t}\\odot{}\\tanh{\\left(c_{t}\\right)}\n \\end{split}\n \\end{equation}\n

\n\n

We are using the implementation provided by PyTorch, more information may be found in the official documentation. It has to be noted, the the original formulation did not contain an additional forget gate $f_{t}$ (see equations above), as this completely destroys the constant error carousel – it was introduced by Gers et al.:\n

\n Gers, F.A., Schmidhuber, J. and Cummins, F., 1999. Learning to forget: Continual prediction with LSTM.\n \n

\n

Nonetheless, for some tasks, the forget gate seems to provide a useful addition. Hence, in this exercise you'll be tasked with activating the forget gate and interpreting the results.

\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Implement a class LSTM with the following architecture:
  • \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
PositionElementComment
0input-
1LSTM$256$ memory cells and a configurable initial forget gate bias (specified as an argument to \\_\\_init\\_\\_)
2fully connectednum_targets output features (as specified during the data set creation)
3output-
\n
    \n
  • Train an LSTM network for $15$ epochs, print the training accuracy as well as the loss per epoch and report the final test set loss and accuracy. Use an initial forget gate bias of $0.0$. Do you expect the resulting performance?
  • \n
\n
\n\n\n```python\nclass LSTM(torch.nn.Module):\n \"\"\"\n LSTM tailored to process latch sequence data.\n \"\"\"\n \n def __init__(self, input_size: int, hidden_size: int = 256, output_size: int = 2, forget_gate_bias: int = 0.0):\n super(LSTM, self).__init__()\n self.lstm1 = torch.nn.LSTM(input_size, hidden_size, batch_first=True)\n self.fc1 = torch.nn.Linear(self.lstm1.hidden_size, data_latch.num_targets)\n \n # Deactivate forget gate to be in line with the original definition.\n def _reset_forget_gate_hook(_gradients: torch.Tensor) -> torch.Tensor:\n _gradients[_gradients.shape[0] // 4:_gradients.shape[0] // 2].fill_(forget_gate_bias)\n return _gradients\n \n for name, parameter in self.lstm1.named_parameters():\n if r'bias' in name:\n parameter.data[(parameter.shape[0] // 4):(parameter.shape[0] // 2)].fill_(1e6)\n parameter.register_hook(_reset_forget_gate_hook)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x = self.lstm1(x)[0][:, -1, :]\n return self.fc1(x)\n```\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create LSTM instance and the corresponding optimizer to use.\ntarget_device = torch.device(r'cuda' if torch.cuda.is_available() else r'cpu')\ninput_size = data_latch.num_characters\noutput_size = data_latch.num_targets\nlstm_model = LSTM(input_size=input_size, output_size=output_size).to(target_device)\noptimizer = torch.optim.Adam(lstm_model.parameters(), lr=1e-2)\n\n# Print the architecture of the LSTM instance.\nprint(lstm_model, end='\\n\\n')\n\n# Train and evaluate LSTM instance on the latch sequence training set.\nnum_epochs = 15\nfor epoch in range(num_epochs):\n \n # Train LSTM instance for one epoch.\n u4.train_network(\n model=lstm_model, data_loader=data_loader_train, device=target_device, optimizer=optimizer)\n \n # Evaluate current LSTM instance.\n performance = u4.test_network(\n model=lstm_model, data_loader=data_loader_train, device=target_device)\n \n # Print result of current epoch to standard out.\n print(f'Epoch: {str(epoch + 1).zfill(len(str(num_epochs)))} ' +\n f'/ Loss: {performance[0]:.4f} / Accuracy: {performance[1]:.4f}')\n\n# Evaluate final model on test data set.\nperformance = u4.test_network(\n model=lstm_model, data_loader=data_loader_test, device=target_device)\nprint(f'\\nFinal loss: {performance[0]:.4f} / Final accuracy: {performance[1]:.4f}')\n```\n\n LSTM(\n (lstm1): LSTM(26, 256, batch_first=True)\n (fc1): Linear(in_features=256, out_features=25, bias=True)\n )\n \n Epoch: 01 / Loss: 0.0677 / Accuracy: 0.0381\n Epoch: 02 / Loss: 0.0676 / Accuracy: 0.0352\n Epoch: 03 / Loss: 0.0674 / Accuracy: 0.0508\n Epoch: 04 / Loss: 0.0667 / Accuracy: 0.0492\n Epoch: 05 / Loss: 0.0667 / Accuracy: 0.0547\n Epoch: 06 / Loss: 0.0663 / Accuracy: 0.0674\n Epoch: 07 / Loss: 0.0662 / Accuracy: 0.0752\n Epoch: 08 / Loss: 0.0655 / Accuracy: 0.0804\n Epoch: 09 / Loss: 0.0651 / Accuracy: 0.0872\n Epoch: 10 / Loss: 0.0644 / Accuracy: 0.0931\n Epoch: 11 / Loss: 0.0637 / Accuracy: 0.1090\n Epoch: 12 / Loss: 0.0403 / Accuracy: 0.4307\n Epoch: 13 / Loss: 0.0186 / Accuracy: 0.6706\n Epoch: 14 / Loss: 0.0012 / Accuracy: 0.9974\n Epoch: 15 / Loss: 0.0005 / Accuracy: 0.9997\n \n Final loss: 0.0008 / Final accuracy: 0.9961\n\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Create a fresh instance of LSTM and collect its gradients w.r.t. the network input using the latch sequence training set.
  • \n
  • Visualize the collected gradients accordingly. What do you observe? Comment on your results.
  • \n
\n
\n\n\n```python\ndef collect_gradients(model: torch.nn.Module, loader: torch.utils.data.DataLoader) -> pd.DataFrame:\n \"\"\"\n Auxiliary function for collecting gradient magnitudes of a corresponding model w.r.t. the network input.\n \n :param model: model instance to be used for collecting gradients\n :param device: device to use for gradient collection\n :param loader: data loader supplying the samples used for collecting gradients\n :return: data frame comprising the gradient magnitudes of the loss function w.r.t. each input element\n \"\"\"\n model_state = model.training\n model.train()\n model.zero_grad()\n\n # Iterating over the data set and computing the corresponding gradients.\n device, gradients = next(model.parameters())[0].device, []\n criterion = torch.nn.CrossEntropyLoss()\n for batch_index, (data, target) in enumerate(loader):\n data, target = data.float().to(device), target.long().to(device)\n \n # Prepare network input for gradient recording.\n data.requires_grad_(True)\n data.register_hook(lambda _: gradients.append(_.cpu().abs()))\n\n # One forward\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n model.zero_grad()\n \n # Reset model state and return collected gradients.\n model.train(mode=model_state)\n return pd.DataFrame(torch.cat(gradients, dim=0).mean(dim=2).numpy())\n```\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create ElmanRNN instance for gradient recording.\ntarget_device = torch.device(r'cuda' if torch.cuda.is_available() else r'cpu')\ninput_size = data_latch.num_characters\noutput_size = data_latch.num_targets\nnew_lstm_model = LSTM(input_size=input_size, output_size=output_size).to(target_device)\n```\n\n\n```python\ngradient_data = collect_gradients(model=new_lstm_model, loader=data_loader_train)\n# Set default plotting style.\nsns.set()\n\n# Prepare collected gradients for plotting.\ngradients_prepared = pd.melt(gradient_data, value_vars=gradient_data.columns)\ngradients_prepared.columns = (r'Timestep', r'Gradient Magnitude')\n\n# Define plotting figure and corresponding attributes.\nfig, ax = plt.subplots(figsize=(14, 7))\nax.set_title(r'LSTM Gradient Magnitudes', fontsize=14)\nax.set(yscale=r'log')\n\n# Plot pre-processed gradients.\n_ = sns.boxplot(x=r'Timestep', y=r'Gradient Magnitude', data=gradients_prepared, ax=ax)\n```\n\nStrangely, exponentially decreasing gradient in LSTMs\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Use the already trained LSTM instance from the beginning of this section for collecting its gradients w.r.t. the network input using the latch sequence training set.
  • \n
  • Visualize the collected gradients together with the gradients of the freshly created LSTM instance accordingly. What do you observe? Comment on your results.
  • \n
\n
\n\n\n```python\ngradient_data = collect_gradients(model=lstm_model, loader=data_loader_train)\n```\n\n\n```python\n# Set default plotting style.\nsns.set()\n\n# Prepare collected gradients for plotting.\ngradients_prepared = pd.melt(gradient_data, value_vars=gradient_data.columns)\ngradients_prepared.columns = (r'Timestep', r'Gradient Magnitude')\n\n# Define plotting figure and corresponding attributes.\nfig, ax = plt.subplots(figsize=(14, 7))\nax.set_title(r'LSTM Gradient Magnitudes', fontsize=14)\nax.set(yscale=r'log')\n\n# Plot pre-processed gradients.\n_ = sns.boxplot(x=r'Timestep', y=r'Gradient Magnitude', data=gradients_prepared, ax=ax)\n```\n\nThe diffrences in the gradients of the trained model are negligible which proves even more strongly how powerful LSTMs are.\n\n
\n Execute the notebook until here and try to solve the following tasks:\n
    \n
  • Train an LSTM network for $15$ epochs, print the training accuracy as well as the loss per epoch and report the final test set loss and accuracy. Use an initial forget gate bias of $1.0$. Do you expect the resulting performance?
  • \n
  • Use the newly trained LSTM instance for collecting its gradients w.r.t. the network input using the latch sequence training set.
  • \n
  • Visualize the collected gradients together with the gradients of the freshly created LSTM instance accordingly. What do you observe? Comment on your results.
  • \n
\n
\n\n\n```python\n# Set random seed for reproducibility.\nnp.random.seed(seed=42)\ntorch.manual_seed(seed=42)\n\n# Create LSTM instance and the corresponding optimizer to use.\ntarget_device = torch.device(r'cuda' if torch.cuda.is_available() else r'cpu')\ninput_size = data_latch.num_characters\noutput_size = data_latch.num_targets\n\nlstm_model_2 = LSTM(input_size=input_size, output_size=output_size, forget_gate_bias=1.0).to(target_device)\noptimizer = torch.optim.Adam(lstm_model_2.parameters(), lr=1e-2)\n\n# Print the architecture of the LSTM instance.\nprint(lstm_model_2, end='\\n\\n')\n\n# Train and evaluate LSTM instance on the latch sequence training set.\nnum_epochs = 15\nfor epoch in range(num_epochs):\n \n # Train LSTM instance for one epoch.\n u4.train_network(\n model=lstm_mode_2, data_loader=data_loader_train, device=target_device, optimizer=optimizer)\n \n # Evaluate current LSTM instance.\n performance = u4.test_network(\n model=lstm_mode_2, data_loader=data_loader_train, device=target_device)\n \n # Print result of current epoch to standard out.\n print(f'Epoch: {str(epoch + 1).zfill(len(str(num_epochs)))} ' +\n f'/ Loss: {performance[0]:.4f} / Accuracy: {performance[1]:.4f}')\n```\n\n LSTM(\n (lstm1): LSTM(26, 256, batch_first=True)\n (fc1): Linear(in_features=256, out_features=25, bias=True)\n )\n \n Epoch: 01 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 02 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 03 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 04 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 05 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 06 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 07 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 08 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 09 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 10 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 11 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 12 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 13 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 14 / Loss: 0.0680 / Accuracy: 0.0358\n Epoch: 15 / Loss: 0.0680 / Accuracy: 0.0358\n \n Final loss: 0.0001 / Final accuracy: 0.9990\n\n\n\n```python\n# Evaluate final model on test data set.\nperformance = u4.test_network(\n model=lstm_model_2, data_loader=data_loader_test, device=target_device)\nprint(f'\\nFinal loss: {performance[0]:.4f} / Final accuracy: {performance[1]:.4f}')\n```\n\n \n Final loss: 0.0702 / Final accuracy: 0.0400\n\n\n\n```python\ngradient_data = collect_gradients(model=lstm_mode_2, loader=data_loader_train)\n```\n\n\n```python\n# Set default plotting style.\nsns.set()\n\n# Prepare collected gradients for plotting.\ngradients_prepared = pd.melt(gradient_data, value_vars=gradient_data.columns)\ngradients_prepared.columns = (r'Timestep', r'Gradient Magnitude')\n\n# Define plotting figure and corresponding attributes.\nfig, ax = plt.subplots(figsize=(14, 7))\nax.set_title(r'LSTM Gradient Magnitudes', fontsize=14)\nax.set(yscale=r'log')\n\n# Plot pre-processed gradients.\n_ = sns.boxplot(x=r'Timestep', y=r'Gradient Magnitude', data=gradients_prepared, ax=ax)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ce4281702bd579077db37cda30b353e86076af29", "size": 337765, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Recurrent Neural Networks.ipynb", "max_stars_repo_name": "diaa-shalaby/AI-microprojects", "max_stars_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Recurrent Neural Networks.ipynb", "max_issues_repo_name": "diaa-shalaby/AI-microprojects", "max_issues_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Recurrent Neural Networks.ipynb", "max_forks_repo_name": "diaa-shalaby/AI-microprojects", "max_forks_repo_head_hexsha": "536e72ddbf0bc329603d1428c1b6149afa4cadad", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 232.1408934708, "max_line_length": 54648, "alphanum_fraction": 0.8970793303, "converted": true, "num_tokens": 10994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.15080516794929963}} {"text": "# Macro 318: Lecture 4 - 6 / Tutorial 2 \n\n
\n\n## Data, Stats and Math with Julia \n\n\n#### Lecturer:
Dawie van Lill (dvanlill@sun.ac.za)
\n\n# Introduction\n\nIn this tutorial we will start our discussion of how to work with data in Julia. \n\nWe will then cover some basic statistics and in the last section move on to some fundamental ideas in mathematics (mostly related to calculus). \n\nPlease note that working with data in Julia is going to be different than working with data in Stata. \n\nI am just showing basic principles here so that you are aware of them. \n\nYou do not need to memorise everything in this notebook. It is simply here as a good reference to have if you want to do some useful data work for macroeconomics. \n\nIf you are more comfortable with Stata for working with data then you can continue on that path. I am simply offering an alternative. \n\nIn the job market there are a few languages that are used for data analysis. \n\nThe most popular ones are Stata, R, Python and Julia. \n\nAt this stage Julia is not the most popular for data work, but it shares similarities with Python. \n\nSo if you know Julia well, it will be easy to pick up Python. \n\nJulia is more popular for work related to numerical / scientific computation, which we will cover in some of the future tutorials. \n\nIf you are interested in Python as an alternative to Julia you can always contact me and I can refer you to some resources. However, for most students it is more important to get the programming principles right without worrying too much about the language that they are using. \n\n\n```julia\nimport Pkg\n```\n\n\n```julia\nPkg.add(\"CategoricalArrays\")\nPkg.add(\"CSV\")\nPkg.add(\"DataFrames\")\nPkg.add(\"DataFramesMeta\")\nPkg.add(\"Downloads\")\nPkg.add(\"ForwardDiff\")\nPkg.add(\"GLM\")\nPkg.add(\"LinearAlgebra\")\nPkg.add(\"Plots\")\nPkg.add(\"Random\")\nPkg.add(\"RDatasets\")\nPkg.add(\"Roots\")\nPkg.add(\"ShiftedArrays\")\nPkg.add(\"SparseArrays\")\nPkg.add(\"Statistics\")\nPkg.add(\"Symbolics\")\nPkg.add(\"Zygote\")\n```\n\n \u001b[32m\u001b[1m Updating\u001b[22m\u001b[39m registry at `C:\\Users\\andie\\.julia\\registries\\General.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n ┌ Warning: The active manifest file at `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml` has an old format that is being maintained.\n │ To update to the new format run `Pkg.upgrade_manifest()` which will upgrade the format without re-resolving.\n └ @ Pkg.Types C:\\buildbot\\worker\\package_win64\\build\\usr\\share\\julia\\stdlib\\v1.7\\Pkg\\src\\manifest.jl:287\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n ┌ Warning: The active manifest file is an older format with no julia version entry. Dependencies may have been resolved with a different julia version.\n └ @ nothing C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml:0\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n \u001b[32m\u001b[1m Resolving\u001b[22m\u001b[39m package versions...\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Project.toml`\n \u001b[32m\u001b[1m No Changes\u001b[22m\u001b[39m to `C:\\Users\\andie\\Documents\\Macro-318-andie\\Manifest.toml`\n\n\n\n```julia\nusing CategoricalArrays\nusing CSV\nusing DataFrames\nusing DataFramesMeta\nusing Downloads\nusing ForwardDiff\nusing GLM\nusing LinearAlgebra\nusing Plots\nusing Random\nusing RDatasets\nusing Roots\nusing ShiftedArrays\nusing SparseArrays\nusing Statistics\nusing Symbolics\nusing Zygote\n```\n\n# Working with data\n\nThe primary package for working with data in Julia is `DataFrames.jl`.\n\n For a comprehensive tutorial series on this package I would recommend Bogumił Kamiński's [Introduction to DataFrames](https://github.com/bkamins/Julia-DataFrames-Tutorial).\n\n# DataFrames basics\n\nIn this section we discuss basic principles from the DataFrames package. \n\nFor the first topic we look at how to construct and access DataFrames. \n\nThe fundamental object that we care about is the `DataFrame`. This is similar to a `dataframe` that you would find in R or in Pandas (Python).\n\nDataFrames are essentially matrices, with the rows being observations and the columns indicating the variables. \n\nBelow is some code that sets the maximum number of rows and columns to be printed in the notebook. \n\n\n```julia\nENV[\"LINES\"] = 10; # set the max number of lines that will be printed\nENV[\"COLUMNS\"] = 100; # set the max number of columns that will be printed\n```\n\n## Constructors\n\nThe easiest thing to construct is an empty DataFrame. \n\n\n```julia\nDataFrame() # empty DataFrame\n```\n\n\n\n\n

0 rows × 0 columns

\n\n\n\nYou could also construct a DataFrame with different keyword arguments. Notice the different types of the different columns. \n\n\n```julia\nDataFrame(A = 2:5, B = randn(4), C = \"Hello\")\n```\n\n\n\n\n

4 rows × 3 columns

ABC
Int64Float64String
12-1.05687Hello
23-1.22619Hello
34-1.04417Hello
45-0.723848Hello
\n\n\n\nOne of the most common ways to use constructors is through arrays. \n\n\n```julia\ncommodities = [\"crude\", \"gas\", \"gold\", \"silver\"] # commodities\nlast_price = [4.2, 11.3, 12.1, missing] # prices of the commodities (notice that the last value is missing)\n\ndf = DataFrame(commod = commodities, price = last_price) # give names to columns\n```\n\n\n\n\n

4 rows × 2 columns

commodprice
StringFloat64?
1crude4.2
2gas11.3
3gold12.1
4silvermissing
\n\n\n\nNotice above that the `commod` column contains only string values. \n\nIn the case of `price` we have decimal numbers with one missing number. \n\nThe `DataFrames` package infers that these are floating point numbers.\n\nThe question mark indicates the uncertainty about how to handle the missing value. \n\nOne can also easily add a new row to an existing `DataFrame` using the `push!` function. \n\nThis is equivalent to adding new observations (rows) to the variables. \n\n\n```julia\nnew_row = (commod = \"nickel\", price = 5.1)\npush!(df, new_row)\n```\n\n\n\n\n

5 rows × 2 columns

commodprice
StringFloat64?
1crude4.2
2gas11.3
3gold12.1
4silvermissing
5nickel5.1
\n\n\n\nOne could also use array comprehensions to generate values for the DataFrame, \n\n\n```julia\nDataFrame([rand(3) for i in 1:3], [:x1, :x2, :x3]) # see how we named the columns with the symbol notation [:x1, :x2, :x3]\n```\n\n\n\n\n

3 rows × 3 columns

x1x2x3
Float64Float64Float64
10.6650340.05631880.791727
20.0456030.9909040.960224
30.8809420.8240610.245943
\n\n\n\nYou can also create a DataFrame from a matrix, \n\n\n```julia\nx = DataFrame(rand(3, 3), :auto) # automatically assign column names with :auto\n```\n\n\n\n\n

3 rows × 3 columns

x1x2x3
Float64Float64Float64
10.6838780.8401280.352071
20.03158210.4776720.723665
30.5257030.2861440.73931
\n\n\n\nIncidentally, you can convert the DataFrame into a matrix or array if you so wished, \n\n\n```julia\nMatrix(x)\n```\n\n\n\n\n 3×3 Matrix{Float64}:\n 0.683878 0.840128 0.352071\n 0.0315821 0.477672 0.723665\n 0.525703 0.286144 0.73931\n\n\n\nIn the next section we talk about accessing the elements of a DataFrame as well as looking at some basic information about the DataFrame that we have on hand. \n\n## Accessing data\n\nOnce we have our data set up in a DataFrame, we are often going to want to know some basic things about the contents. Let us construct a relatively large DataFrame. Most of the time we will be working with large datasets in economics, with thousands of rows and columns. You might be used to working with data in Excel, so things might feel foreign right now. However, I promise that once you start working with data in a programming language such as R, Julia or Python, your productivity will greatly increase. You only need to get over that initial apprehension of learning something new. \n\n\n```julia\ny = DataFrame(rand(1:10, 1000, 10), :auto);\n```\n\nWe can get some basic summary statistics on the data in the DataFrame using the `describe` function. \n\n\n```julia\ndescribe(y)\n```\n\n\n\n\n

10 rows × 7 columns

variablemeanminmedianmaxnmissingeltype
SymbolFloat64Int64Float64Int64Int64DataType
1x15.59716.0100Int64
2x25.51916.0100Int64
3x35.59916.0100Int64
4x45.59816.0100Int64
5x55.45115.0100Int64
6x65.4716.0100Int64
7x75.40415.0100Int64
8x85.55116.0100Int64
9x95.35715.0100Int64
10x105.43515.0100Int64
\n\n\n\nIf we want to take a peak at the first few rows of the data we can use the `first` function. \n\n\n```julia\nfirst(y, 5) # first 5 rows\n```\n\n\n\n\n

5 rows × 10 columns

x1x2x3x4x5x6x7x8x9x10
Int64Int64Int64Int64Int64Int64Int64Int64Int64Int64
132710355918
241101289122
31014751083109
42892488857
5101775711015
\n\n\n\nThere are multiple ways to access particular columns of the DataFrame that we have created. The most obvious way is to to use `y.col` where `col` stands for the column name. This provides us the column in vector format. \n\n\n```julia\ny.x2; # get a single column\n```\n\nAnother interesting way to access the column is the following, \n\n\n```julia\ny[!, :x2]; # or y[!, 2] or y[:, :x2]\n```\n\nYou can access several columns (the first two in this case) with the following command, \n\n\n```julia\ny[:, [:x1, :x2]];\n```\n\nGetting rows is also quite easy (and similar to the way in which we access rows in arrays), \n\n\n```julia\ny[1, :]\n```\n\n\n\n\n

DataFrameRow (10 columns)

x1x2x3x4x5x6x7x8x9x10
Int64Int64Int64Int64Int64Int64Int64Int64Int64Int64
132710355918
\n\n\n\nWith the code above you can also easily change the values in the DataFrame. We could, for example, multiply each of the values in the second column by $2$ if we wanted. \n\n\n```julia\nfirst(y.x2, 2) # observe first two values in the column\n```\n\n\n\n\n 2-element Vector{Int64}:\n 2\n 1\n\n\n\n\n```julia\nz = y[!, :x2]; \nz *= 2; # multiply column by two\n\nfirst(z, 2) # observe newly mutated column\n```\n\n\n\n\n 2-element Vector{Int64}:\n 4\n 2\n\n\n\n\n```julia\nfirst(y.x2, 2) # important to note that this is unchanged\n```\n\n\n\n\n 2-element Vector{Int64}:\n 2\n 1\n\n\n\n# Importing data\n\nNow let us import some data and play around with it a bit. This is generally referred to as data wrangling. If you want to become a data scientist, then a significant portion of your work is going to involve gathering and cleaning data. The analysis part only makes up a small percentage. \n\nI have created a dataset that is hosted on github at the following location -- https://github.com/DawievLill/Macro-318/blob/main/data/tut2_data.csv\n\nNow let us download this data with Julia. This is one possible way to do it. \n\n\n```julia\nDownloads.download(\n \"https://raw.githubusercontent.com/DawievLill/Macro-318/main/data/tut2_data.csv\", \n \"tut2_data.csv\"\n)\n```\n\n\n\n\n \"tut2_data.csv\"\n\n\n\nNow get the data into Julia!\n\n\n```julia\nsa_data = DataFrame(CSV.File(\"tut2_data.csv\", dateformat = \"yyyy/mm/dd\")) # specify the date format\n```\n\n\n\n\n

71 rows × 5 columns

dategdprepocpiinflation
DateInt64Float64Float64Float64
12004-03-3115715808.051.1689-2.05565
22004-06-3016409538.051.4474-2.02507
32004-09-3016746997.6666751.5677-1.00851
42004-12-3117310007.551.84831.62524
52005-03-3117688287.552.17961.97509
62005-06-3018037837.052.4561.9603
72005-09-3018737437.052.81252.41398
82005-12-3119184237.052.93912.10385
92006-03-3119601507.053.2432.03793
102006-06-3020485347.1666753.75362.47365
112006-09-3021200137.8333354.77263.7114
122006-12-3122310308.6666755.32754.51158
132007-03-3122706679.055.95215.08817
142007-06-3023508489.1666756.94585.93869
152007-09-3024159889.8333358.15486.17488
162007-12-31246241210.666759.26467.11589
172008-03-31256980311.060.96678.96234
182008-06-30263314611.666762.63339.98761
192008-09-30272312012.064.611.0829
202008-12-31267351411.833365.03339.73391
212009-03-31274251710.566.06678.36523
222009-06-3027326478.1666767.46677.71687
232009-09-3028055947.1666768.76.34675
242009-12-3128539117.069.03336.15069
252010-03-3129362486.8333369.85.65086
262010-06-3030100516.570.53334.54545
272010-09-3030531476.3333371.13.49345
282010-12-3130811355.6666771.43.4283
292011-03-3131831465.572.46673.82044
302011-06-3032513165.573.84.63138
\n\n\n\nAlternatively, we could have done the following, since we know the data is located in the `data` folder, \n\n\n```julia\nsa_data_1 = DataFrame(CSV.File(\"../data/tut2_data.csv\")); # if you don't understand this piece of code, you can simply move on. \n```\n\nSo we have succesfully imported data into Julia. \n\nWhat can we do with this data? \n\nWe see that the data contains information on GDP, the repo rate, CPI and inflation. \n\nThe first thing that we might want to do is visualise the data. \n\nThis is always a good first step. \n\nAfter that we might want to look at some basic descriptive statistics, to get an idea of the properties of the data. \n\nHowever, before we do that, let us take a look at how to rename columns. \n\n## Renaming\n\nTwo functions can be used to rename columns. \n\nThe `names` function returns column names as a vector of strings, while the `propertynames` function returns a vector of symbols.\n\n\n```julia\nnames(sa_data)\n```\n\n\n 5-element Vector{String}:\n \"date\"\n \"gdp\"\n \"repo\"\n \"cpi\"\n \"inflation\"\n\n\n\n```julia\npropertynames(sa_data)\n```\n\n\n 5-element Vector{Symbol}:\n :date\n :gdp\n :repo\n :cpi\n :inflation\n\n\nWe use the `rename!` function to change column names. \n\nThis function can be used to rename all columns at once.\n\n\n```julia\nrename!(sa_data, [:date, :GDP, :interest, :CPI, :infl])\n```\n\n\n

71 rows × 5 columns

dateGDPinterestCPIinfl
DateInt64Float64Float64Float64
12004-03-3115715808.051.1689-2.05565
22004-06-3016409538.051.4474-2.02507
32004-09-3016746997.6666751.5677-1.00851
42004-12-3117310007.551.84831.62524
52005-03-3117688287.552.17961.97509
62005-06-3018037837.052.4561.9603
72005-09-3018737437.052.81252.41398
82005-12-3119184237.052.93912.10385
92006-03-3119601507.053.2432.03793
102006-06-3020485347.1666753.75362.47365
\n\n\nAnother option is to rename only some of the columns specified by their names,\n\n\n```julia\nrename!(sa_data, :GDP => :gdp, :interest => :repo, :CPI => :cpi, :infl => :inflation)\n```\n\n\n

71 rows × 5 columns

dategdprepocpiinflation
DateInt64Float64Float64Float64
12004-03-3115715808.051.1689-2.05565
22004-06-3016409538.051.4474-2.02507
32004-09-3016746997.6666751.5677-1.00851
42004-12-3117310007.551.84831.62524
52005-03-3117688287.552.17961.97509
62005-06-3018037837.052.4561.9603
72005-09-3018737437.052.81252.41398
82005-12-3119184237.052.93912.10385
92006-03-3119601507.053.2432.03793
102006-06-3020485347.1666753.75362.47365
\n\n\n## Plotting the data\n\nFor us to plot the data let us look at one of the variables in the dataset. \n\nLet us consider GDP, which is the second column in the dataset. We can access GDP by calling the variable name, but we can also use the fact that it is located in the second column of the table. \n\n\n```julia\ngdp_1 = sa_data.gdp;\ngdp_2 = sa_data[!, 2];\ngdp_3 = sa_data[!, :gdp];\n```\n\nWe can check whether these variables give the same result as follows, \n\n\n```julia\ngdp_1 == gdp_2 == gdp_3 # check that these give exactly the same result\n```\n\n\n\n\n true\n\n\n\nNow let us draw a basic plot of GDP and see if it aligns with your expectation of what GDP would look like in level terms. You can also compare this with US GDP in Chapter 2 of the Williamson textbook. I have used **nominal GDP** in this dataset. \n\nWe will compare nominal with real GDP soon, with a simple calculation involving the inflation rate (although technically we should be using the GDP deflator to move from nominal to real terms). \n\n\n```julia\ndate_sa = sa_data[!, :date]\nplot(date_sa, gdp_1, legend = false, lw = 2, color = :blue, alpha = 0.8)\n```\n\n\n\n\n \n\n \n\n\n\nOne of the most popular transformations of GDP data is to take a natural logarithm. The reason for this is that differences between adjacent values in the GDP series represent growth rates once the series is \"logged\". We will get back to this point at a later stage. If we take a natural log of the series then the plot of GDP looks as follows, \n\n\n```julia\nlog_gdp = log.(gdp_1); # remember the dot syntax, since we are broadcasting the log over all the values of GDP\n```\n\n\n```julia\nplot(date_sa, log_gdp, legend = false, lw = 2, color = :blue, alpha = 0.8)\n```\n\n\n\n\n \n\n \n\n\n\nYou will see that the scale on the y-axis has changed after this transformation. The slope of this graph indicates the growth rate. A point that we will touch on soon. \n\nWe can also plot some of the other variables in our dataset, such as the inflation rate. \n\n\n```julia\ninflation_rate = sa_data.inflation\nplot(date_sa, inflation_rate, legend = false, lw = 2, color = :blue, alpha = 0.8)\nplot!([0], legend = false, lw = 1.5, seriestype = :hline, color = :black, ls = :dash, alpha = 0.5)\n```\n\n\n\n\n \n\n \n\n\n\n### To do:\n\n1. Calculate real GDP\n\n### Hodrick-Prescott filter (technical)\n\nThe following section is for the more technically inclined students. However, you can quickly read through this section to get a feeling for the main result. \n\nThe Hodrick-Prescott filter is a tool that is used to remove the cyclical component of a time series. In other words it extracts the trend component of a time series.\n\nWe will provide a brief formal description of what the filter is doing, and provide some code for how to operate it. \n\nIt is not expected that you fully understand this process. \n\nThis is a topic that you will encounter again in the Honours program. \n\nFor now it is good enough to simply understand what the HP filter is doing. Please do not worry about the code. Those that are interested in the code can look at it, but it is a bit beyond what is expected of most of the students in this class, unless you have a background in programming and statistics. \n\nFormally, a time series $y_t$, such as GDP, is made up of a trend component $\\tau_t$, a cyclical component $c_t$ and an error component $\\varepsilon_t$ such that \n\n$$\ny_t = \\tau_t + c_t + \\varepsilon_{t}\n$$\n\nGiven some value of $\\lambda$, there is a trend component that will solve the following minimisation problem, \n$$\n\\min _{\\tau }\\left(\\sum _{t=1}^{T}{(y_{t}-\\tau _{t})^{2}}+\\lambda \\sum _{t=2}^{T-1}{[(\\tau _{t+1}-\\tau _{t})-(\\tau _{t}-\\tau _{t-1})]^{2}}\\right)\n$$\n\nThe first term $(y_{t}-\\tau _{t})^{2}$ represents the squared deviation of the trend from the series, which acts as a penalty on the cyclical component. The second term $[(\\tau _{t+1}-\\tau _{t})-(\\tau _{t}-\\tau _{t-1})]^{2}$, which is multiplied by $\\lambda$, represents the second difference of the squared trend component. This part penalises variations in the growth rate of the trend component. The higher the value of $\\lambda$, the higher this penalty.\n\nThe value for $\\lambda$ is normally set to $1600$ for quarterly data. \n\n\n```julia\nfunction hp_filter(y; w = 1600)\n\n # y is original series to be smoothed\n # w is smoothing parameter\n # s is the output / filtered series\n\n # ensure the correct shape (column vector)\n if size(y, 1) < size(y, 2)\n y = y'\n end\n\n t = size(y, 1)\n\n a = 6 * w + 1\n b = -4 * w\n c = w\n \n d = [c b a]\n\n d = ones(t, 1) * d\n\n m = spdiagm(d[:,3]) + spdiagm(1 => d[1:t-1, 2]) + spdiagm(-1 => d[1:t-1,2])\n m += spdiagm(2 => d[1:t-2, 1]) + spdiagm(-2 => d[1:t-2, 1])\n\n m[1, 1] = 1 + w \n m[1, 2] = -2 * w\n m[2, 1] = -2 * w \n m[2, 2] = 5 * w +1\n m[t-1, t-1] = 5 * w + 1 \n m[t-1, t] = -2 * w\n m[t, t-1] = -2 * w \n m[t, t] = 1 + w\n\n return s = m \\ y\nend\n```\n\n\n\n\n hp_filter (generic function with 1 method)\n\n\n\nBelow we see a plot with the trend in red and the original series in black. The trend is retrieved using the HP filter, with a value of $\\lambda = 1600$\n\n\n```julia\nhp_plot = plot(hp_filter(gdp_1), legend = false, lw = 2, alpha = 0.8, color = :red)\nplot!(hp_plot, gdp_1, lw = 2, alpha = 0.7, color = :black)\n```\n\n\n\n\n \n\n \n\n\n\nBelow is the detrended business cycle, which we retrieve by subtracting the trend from the original series. \n\n\n```julia\nbus_cycle = gdp_1 - hp_filter(gdp_1);\nplot(date_sa, bus_cycle, lw = 2, alpha = 0.7, color = :black, legend = false)\n```\n\n\n\n\n \n\n \n\n\n\nFinally, we can see what happens if we use different values of $\\lambda$ for the trend.\n\n\n```julia\nlambdas = [200, 1600, 10000]\n\np1 = plot()\n\nfor i in lambdas\n plot!(p1, hp_filter(gdp_1, w = i), label = \"lambda = $i\", legend = :topleft, lw = 2, alpha = 0.8)\nend\n\nplot(p1)\n```\n\n\n\n\n \n\n \n\n\n\n\n```julia\np2 = plot()\n\nfor i in lambdas\n plot!(p2, gdp_1 - hp_filter(gdp_1, w = i), label = \"lambda = $i\", legend = :bottomleft, lw = 2, alpha = 0.8)\nend\n\nplot(p2)\n```\n\n\n\n\n \n\n \n\n\n\n# Descriptive statistics\n\nSome of the most widely used statistics are the mean (average) and standard deviation. They can be easily computed with the computer as follows, \n\n\n```julia\ninflation_1 = sa_data[!, :inflation] # select the inflation column\nmean(inflation_1) # mean value of inflation\n```\n\n\n\n\n 4.830130044713535\n\n\n\n\n```julia\nstd(inflation_1) # standard deviation of inflation\n```\n\n\n\n\n 2.3122543025163282\n\n\n\nLet us plot a histogram for the data and also indicate where the mean is in this plot. \n\n\n```julia\nhistogram(inflation_1, legend = false, alpha = 0.5, bins = 20) # a histogram gives a general idea of what the distribution of values for inflation looks like.\nplot!([mean(inflation_1)], seriestype = :vline, lw = 3, colour = :black, ls = :dash) # plots the mean value\n```\n\n\n\n\n \n\n \n\n\n\nIn general, if we want descriptive statistics we can use the `describe()` function to give us some more information about the dataset. \n\n\n```julia\ndescribe(sa_data)\n```\n\n\n

5 rows × 7 columns

variablemeanminmedianmaxnmissingeltype
SymbolUnion…AnyAnyAnyInt64DataType
1date2004-03-312012-12-312021-09-300Date
2gdp3.72775e615715803.71359e658199830Int64
3interest6.737093.56.6666712.00Float64
4cpi82.266251.168980.0122.2330Float64
5infl4.83013-2.055654.8616311.08290Float64
\n\n\n# Growth rates\n\nMathematics is so much easier when we get to use a computer. In this section I will introduce some of the basic mathematical theory that you need as a macroeconomist and then we will show you how that relates to programming.\n\nComputing growth rates is quite important in macroeconomics. This is something that you will frequently encounter and it is important to know how to do this. The growth rate between two subsequent dates can be calculated as follows, \n\n$$\n\\left(\\frac{Y_{t} - Y_{t-1}}{Y_{t-1}}\\right) \\times 100 = \\left(\\frac{Y_{t}}{Y_{t-1}} - 1\\right) \\times 100 \n$$\n\n\nIf you are working with quarterly data and want to calculate the growth rate from one quarter to the same quarter next year then you should use, \n\n$$\n\\left(\\frac{Y_{t}}{Y_{t-4}} - 1\\right) \\times 100 \n$$\n\nIn addition, we can calculate the monthly or quarterly growth rate at an annual rate, \n\n$$\n\\left(\\left[\\frac{Y_{t}}{Y_{t-1}}\\right]^{n} - 1\\right) \\times 100 \n$$\nwhere $n = 4$ represents quarterly growth and $n = 12$ gives monthly growth. \n\nFinally, we can calculate the average growth rate over $n$ years with the following formula, \n\n$$\n\\left(\\left[\\frac{Y_{t}}{Y_{t-n}}\\right]^{1/n} - 1\\right) \\times 100 \n$$\n\n### Examples of growth rate calculations\n\nLet us try calculating some growth rates with the data at hand. We will focus on GDP growth rates for this example, \n\n\n```julia\ngdp_first = sa_data[1, :gdp]; # first value of the GDP series\ngdp_second = sa_data[2, :gdp]; # second value of the GDP series\n\ngdp_growth_1 = ((gdp_second - gdp_first)/gdp_first) * 100 # using the formula for growth between two periods. \n```\n\n\n\n\n 4.414220084246427\n\n\n\nThere is an alternative way to calculate an approximation to the growth rate from above. We can simply take the natural logarithm of the two values and subtract them from each other. In other words we have that, \n\n$$\n\\left(\\frac{Y_{t}}{Y_{t-1}} - 1\\right) \\times 100 \\approx \\log(Y_{t}) - \\log(Y_{t-1}) \\times 100\n$$\n\n\n\n```julia\n(log(gdp_second) - log(gdp_first)) * 100\n```\n\n\n\n\n 4.319568788852912\n\n\n\nThe values are not exactly the same. This is simply an approximation which is often used in practice. \n\nAs another example, let us calculate the quarterly growth rate of GDP and then plot the resulting values. This calculation is a bit more tricky since we are now going to apply it to the entire dataset. Let me explain the logic of what we are going to do here. \n\nFirst, we are going to create a new column that contains a lagged version of the original column for GDP. Why do we want to do this? The reason is that we want to be able to divide $Y_t$ by $Y_{t-4}$ from our formula above. However, we only have values for $Y_t$ in the $t$-th column and not $Y_{t-4}$. So for every row we need to create a corresponding lagged version of the original column. Before we do anything, let us take a look at the first few values of the dataset to see what we need to change. We only care about the first two columns, so we will only select those. \n\n\n```julia\nfirst(sa_data[!, 1:2], 8)\n```\n\n\n\n\n

8 rows × 2 columns

dategdp
DateInt64
12004-03-311571580
22004-06-301640953
32004-09-301674699
42004-12-311731000
52005-03-311768828
62005-06-301803783
72005-09-301873743
82005-12-311918423
\n\n\n\n\n```julia\nsa_data.lagged_gdp = lag(sa_data[!, 2], 4);\n```\n\nWe can see that the lagged GDP column has successfully been created and added to the DataFrame. \n\n\n```julia\nfirst(sa_data[!, :], 8) \n```\n\n\n\n\n

8 rows × 6 columns

dategdprepocpiinflationlagged_gdp
DateInt64Float64Float64Float64Int64?
12004-03-3115715808.051.1689-2.05565missing
22004-06-3016409538.051.4474-2.02507missing
32004-09-3016746997.6666751.5677-1.00851missing
42004-12-3117310007.551.84831.62524missing
52005-03-3117688287.552.17961.975091571580
62005-06-3018037837.052.4561.96031640953
72005-09-3018737437.052.81252.413981674699
82005-12-3119184237.052.93912.103851731000
\n\n\n\nNow we can calculate the growth rate, \n\n\n```julia\ngdp_growth_quarterly = (log.(sa_data.gdp) .- log.(sa_data.lagged_gdp)) .* 100; # log method\ngdp_growth_quarterly_1 = ((sa_data.gdp ./ sa_data.lagged_gdp) .- 1) .* 100; # formula method\n```\n\n\n```julia\nplot(date_sa, gdp_growth_quarterly, legend = false, lw = 2, alpha = 0.7) # log method\nplot!(date_sa, gdp_growth_quarterly_1, legend = false, lw = 2, ls = :dash, color = :black) # formula method\n```\n\n\n\n\n \n\n \n\n\n\nFor the other formulas you can perform similar calculations. As an exercise you can attempt to use the other formulas to calculate annualised growth rates. \n\n\n\n# Basic math for macroeconomics\n\nIn this section we will be discussing very basic mathematical concepts that relate to mathematical modeling. For this section we will be making heavy use of the notes on mathematics for economists by [Fan Wang](https://fanwangecon.github.io/Math4Econ/). Please go look at his website for more cool notes and give his repository a star. His code is mostly in Matlab, but he also has some Python and R code. You can easily translate Matlab to Julia, since the syntax of the languages are quite similar. \n\n\n\n## Functions\n\nA function is a **rule** that assigns to every element of $x \\in X$ a **single element** of the set $Y$. This is written as, \n\n$$\nf:X \\rightarrow Y\n$$\n\nThe arrow indicates the mapping from the one set to another. When we write $y = f(x)$ we are mapping from the argument $x$ in the domain $X$ to a value in the co-domain $Y$. \n\nIt is important to note that for a function we are assigning a single element from the set $X$ to the set $Y$.\n\nLet us illustrate this with some examples of functions and non-functions in Julia. \n\n\n```julia\nx = 0:π/100:2π\ny = sin.(x)\n\nplot(x, y, title = \"This is a function\", legend = false, lw = 2)\n```\n\n\n\n\n \n\n \n\n\n\nThe function above is a portion of the $\\sin$ function over the interval from $0$ to $2\\pi$. However, the following graph that depicts a circle is not a function. It is a relation, but NOT a function. Can you see why this is the case? What is the defining feature of a function?\n\n\n```julia\nx = 1; y = 1; r = 1\nθ = 0:π/50:2π\n\nx_unit = r .* cos.(θ) .+ x\ny_unit = r .* sin.(θ) .+ y\n\nplot(x_unit, y_unit, title = \"This is NOT a function\", legend = false, lw = 2)\n```\n\n\n\n\n \n\n \n\n\n\nA linear function, which is also known as polynomial of degree 1 has slope $m$ and intercept $b$. Linear functions have constant slope. We will encounter the idea of slope again later when we talk about derivatives. \n\n\n```julia\nm = 0.5 # slope\nb = 1 # intercept\n\nar_x = LinRange(-5, 10, 100)\nar_y = ar_x .* m .+ b\n\nplot(ar_x, ar_y, legend = false, title = \"Linear function with slope $m and intercept $b\", lw = 2)\n\nvline!([0], ls = :dash, color = :black, alpha = 0.5, xticks = ([-2]))\nhline!([0], ls = :dash, color = :red, alpha = 0.5, yticks = ([1]))\n```\n\n\n\n\n \n\n \n\n\n\nIn high school you probably determined the slope of this function using a the method of rise over run. In other words, the change in $y$ over the change in $x$. More \"formally\", you calculated $m = \\frac{\\Delta{y}}{\\Delta{x}}$. In this example, $\\Delta{y} = 1 - 0$ and $\\Delta{x} = 0 - (-2)$, so we have that $m = 1 / 2 = 0.5$. We will talk about this method of using a difference quotient again when we want to calculate the slope of a tangent line to a function in the section on derivatives. \n\n## Monomials and polynomials\n\n\nFunctions that take the form $a \\cdot x^{k}$ are considered **monomials**. In this case $a$ is any real number and $k$ is a positive integer. The value of $k$ represent the degree of the monomial. Monomials can be added together to form **polynomials**. A general formulation for a polynomial of degree four would be, \n\n$$\na + b\\cdot{x} + c \\cdot x^2 + d \\cdot x^3 + e \\cdot x^4\n$$\n\nwhere the coefficients $a, b, c, d, e$ could be positive or negative. In order to determine the degree of the polynomial, consider the monomials that constitute the polynomial. The monomial with the highest degree determines the degree of the whole polynomial. An explicit representation of a polynomial that you should all know quite well is something along the following lines, \n\n$$\ny = 2 + 5x^2\n$$\n\nCan you identify what the degree of this polynomial is? Let us plot some polynomials to get an idea of what they look like. \n\n\n\n```julia\nx = -1:0.01:1\ny = 2 .+ 5 .* x .^ 2\n\nplot(x, y, legend = false, title = \"Polynomial of degree two\", lw = 2)\n```\n\n\n\n\n \n\n \n\n\n\nLet us plot a polynomial of degree three to see how this might differ. \n\n\n```julia\nx = -3:0.01:3\ny = 2 .- 1 .* x .^ 2 .- 10 .* x .^ 3\n\nplot(x, y, legend = false, title = \"Polynomial of degree three\", lw = 2)\n```\n\n\n\n\n \n\n \n\n\n\n## Local and global maximum\n\nA function $f$ has a global maximum at $x^{*} \\in X$ if for all $x \\in X$, $f(x) \\leq f(x^{*})$. A function $f$ has a local maximum at $x^{*} \\in X$ if there exists and open interval $(a, b)$ such that $x^{*} \\in (a, b)$, and for all $x \\in (a, b), f(x) \\leq f(x^{x})$. Not all functions have a maximum. \n\nWe are going to be dealing with functions such as utility functions, production functions and budget constraints in many of our economics models. \n\nAs an example, in the case of a utility function the household is choosing the bundle of goods that provides the highest level of utility. \n\nMost production and utility functions will NOT have a local or global maximum. \n\nIn the case of a log-utility function, higher consumption will give higher levels of utility, so no maximum exists here either. \n\nIf we have a Cobb-Douglas production function, then output will increase with labour and capital. This means that the function is even increasing in its inputs and has no maximum. \n\n**NB**: It is only when we combine our preferences with a budget that we will be able to think about the optimal bundle choice given a fixed budget. The maximisation problem in this case will reveal some maximum. We will cover this example at length in the next tutorial. \n\n### Quadratic utility\n\nThere is one nice utility function that has a maximum, the quadratic utility function. \n\n$$\nU(x) = x - \\alpha \\cdot x^2\n$$\n\nWe can quickly draw a plot of this utility function and by inspection determine where the maximum is going to be. The most efficient way to determine the maximum would be using a derivative and setting it equal to zero. However, we haven't introduced derivatives yet, so let us use this inefficient way to determine the maximum for now. \n\n\n```julia\nnpoints = 100\na, b = (-10, 10)\nx = range(a, b, length = npoints)\nα = 0.2 \n\nU(x) = x .- α .* x .^ 2\n\nplot(x, U.(x), legend = false, lw = 2, title = \"Can you find the max?!\")\n```\n\n\n\n\n \n\n \n\n\n\nAs you can see, we can approximately guess from the graph where the highest value for this graph is going to be. It is somewhere in the interval between 10 and 15. However, this is not precise enough. We need some method to give us the exact answer, this is where derivatives will enter. Another approach is just to consider each of the utility values and then pick the maximum from the list. Luckily Julia has a function called `findmax()` that can do this for us. \n\nDon't worry too much about the code for now, this won't make too much sense at first. I will try and explain the basic idea, but if you don't get it don't worry. Try and come back to this code at a later stage once you are more familiar with programming in Julia. Then try and evaluate every line and see if you can make sense of what is happening here. \n\n\n```julia\nfmax, ix = findmax(U.(x))\t\n```\n\n\n\n\n (1.249872461993674, 63)\n\n\n\nWe can see from above that if we evaluate our utility function with the `findmax()` function a tuple is returned. The first value in the tuple is the function output at the maximum. In other words it is the value of utility where this function is maximised. It is the value on the y-axis. The second value in the tuple is the position in the list of $x$ values that we evaluated. If we go back in our code you will see that we created a range of $x$ values in the interval $-10$ to $10$. We created a grid of 100 points within the interval (generated 100 potential values for $x$) and inserted those $x$ values into the utility function at each of the given points. \n\nAccording to the `findmax()` function, the 63rd value in that grid of $x$ values was the one that maximised the function. This is also referred to as the $\\argmax$ in mathematics. We can then find the $x$ value by looking at `x[ix]`, which is basically the same as `x[63]` in this case. Remember how to access elements in an array from the previous tutorial. \n\n\n```julia\nx[ix] == x[63]\n```\n\n\n\n\n true\n\n\n\nThe maximum here is $2.52525252 \\ldots$. If we chose a finer grid for $x$ we would be able to get a better approximation for the true value that maximises this function.\n\n\n```julia\nx[ix] \n```\n\n\n\n\n 2.525252525252525\n\n\n\nIn the graph below we simply draw a scatter plot with the $x$ value being represented by the 63rd point in the $x$ vector.\n\n\n```julia\nscatter!([x[ix]], [fmax], color = :red, ms = 5)\nvline!([x[ix]], lw = 1.5, color = :black, ls = :dash, alpha = 0.5, xticks = ([x[ix]]))\n```\n\n\n\n\n \n\n \n\n\n\n## Derivatives\n\nLinear functions have a constant slope, as we have seen in one of the earlier examples. However, what about non-linear functions? What is the rate of change for a non-linear function as we move along its domain?\n\nLet $(x_0, f(x_0))$ be a point on the graph of $y = f(x)$. The derivative of $f$ at the point $x_0$ is the slope of the tangent line to the graph of $f$ at $(x_0, f(x_0))$. We can denote this derivative of a function $f$ at $x_0$ as\n\n$$\nf'(x_0) = \\frac{df(x_0)}{dx} = f_{x}(x_0)\n$$\n\nThe notation above is interchangeable. The derivative is defined formally as, \n\n$$\nf'(x_0) = \\lim_{h \\rightarrow 0} \\frac{f(x_{0} + h) - f(x_0)}{h}\n$$\n\nIn taking derivatives we normally revert to the derivative rules. The derivative rules are the following, \n\n1. Constant rule\n2. Power rule\n3. Chain rule\n4. Sum (difference) rule\n5. Product rule\n6. Quotient rule (we won't cover this, since you can use the product rule if needed)\n\nThen we can also speak of the exponential and log rule for derivatives. These are ones that will be frequently used. Let us have a brief discussion and examples of each of the rules. We will also accompany the solutions that are written out by hand with a solution generated by the computer to check that we are correct in our calculation. \n\nIt is important to note that there are several ways in which you can take derivatives on the computer. The primary methods are, \n\n1. Symbolic differentiation\n2. Automatic differentiation\n3. Numerical differentiation\n\nWe will not be going into detail on how these methods work. We will just use them in practice. We will show the symbolic and automatic differentiation approaches in this tutorial. For a good introduction to the approximation of derivatives using a computer you can look at these notes [here](https://mth229.github.io/derivatives.html).\n\n#### Constant rule\n\nIf $f(x) = k$ where $k$ is some constant then $f'(k) = 0$. As an application of the constant rule, let us determine the derivative of $f(x) = 8$. \n\n$$\nf'(8) = 0\n$$\n\nThis is the easiest rule and can be computed in one line. Let us see what the computer does with this example. First we use the `Symbolics` package. \n\n\n```julia\n@variables x\nD = Differential(x)\n\ny = 8\nD(y) # we can see that this now gives us the correct formulation\n```\n\n\n\n\n\\begin{equation}\n\\mathrm{\\frac{d}{d x}}\\left( 8 \\right)\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(y)) # solution to the problem -- we see that this is the same as our answer. \n```\n\n\n\n\n 0\n\n\n\nNow we try the `Zygote` package. This uses automatic differentiation. Once again, we will not explain what this method entails. If you want to read more on the topic you are more than welcome. For those that are interested in machine learning and deep learning it will be compulsory to learn more about the concept of automatic differentiation at some point. \n\n\n```julia\nf(x) = 8\n\nf'(x)\n```\n\nWe see that there is no answer here. This seems strange. Let us try another approach with this rule. We can calculate the gradient at a certain point in another way. \n\n\n```julia\nZygote.gradient(y -> 8, 8)\n```\n\n\n\n\n (nothing,)\n\n\n\nWe see that the output is `nothing` here. This shows why we had no output in the previous code. When `nothing` is returned then there will be nothing to display. Another option for automatic differentiation is the `ForwardDiff` package. Let us quickly look at an example with this package. \n\n\n```julia\nForwardDiff.derivative.(f, 8)\n```\n\n\n\n\n 0\n\n\n\nIn this case we get an answer of zero. Which is more in line with what one would expect. \n\n#### Power rule\n\nFor any positive integer $k$ the derivative of $f(x) = x^{k}$ at $x_0$ is, \n\n$$\nf'(x_0) = k \\cdot x_{0}^{k - 1}\n$$\n\nAn example of this would be the following. Find the answer to \n\n$$\nf'(x) = x ^ 3\n$$\n\nWhat do you think the answer should be? Let us check with the computer to see what we get. First we try symbolic differentiation.\n\n\n```julia\ny = x ^ 3\nD(y)\n```\n\n\n\n\n\\begin{equation}\n\\mathrm{\\frac{d}{d x}}\\left( x^{3} \\right)\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(y))\n```\n\n\n\n\n\\begin{equation}\n3 x^{2}\n\\end{equation}\n\n\n\n\nDoes this answer match with what you calculated by hand? Next we try automatic differentiation. \n\n\n```julia\nf(x) = x ^ 3\n\nf'(x) \n```\n\n\n\n\n\\begin{equation}\n3 x^{2}\n\\end{equation}\n\n\n\n\nIt seems that `Zygote` gives the same answer. Let us evaluate this function at a particular point with `ForwardDiff`.\n\n\n```julia\nf'(5) == ForwardDiff.derivative.(f, 5) # evaluated at the point x = 5\n```\n\n\n\n\n true\n\n\n\n\n```julia\nf'(5)\n```\n\n\n\n\n 75\n\n\n\n#### Chain rule\n\nThe chain rule is a bit more complicated then some of the other rules, but it is used frequently in economics. If we have a function $f(x) = p(q(x)) = (p \\circ q)(x)$ which is a composite of two differentiable functions $p(x)$ and $q(x)$ then the derivative at $x_0$ according to the chain rule is, \n\n$$\nf^{\\prime } (x_0 )=p^{\\prime } (q(x_0 ))\\cdot q^{\\prime } (x_0 )\n$$\n\nA good example of where this is applicable is the function \n\n$$\nf(x) = \\sqrt{(5x - 8)}\n$$\n\nIn this case we have a composition of two functions, $p(x) = \\sqrt{x}$ and $q(x) = 5x - 8$. Here we need to take the derivatives separately and combine with our rule. We start with $p'(x)$. We haven't really talked about taking the derivative of a square root. So how do we proceed? Well, our square root can actually be written as $p(x)^{1/2}$. Now we can use our power rule from before to get $p'(x) = \\frac{x^{-1/2}}{2}$. Next we need to take the derivative of $q(x)$, which gives is $q'(x) = 5$ using the power rule (since $5 = 5 \\cdot x^{(1 - 1)}$). Now we combine all the components as per the chain rule, \n\n$$\n\\begin{align*}\nf'\\left( x \\right) & = p'\\left( {q\\left( x \\right)} \\right)\\,\\,q'\\left( x \\right)\\\\ \n& = p'\\left( {5x - 8} \\right)\\,\\,q'\\left( x \\right)\\\\ \n& = \\frac{1}{2}{\\left( {5x - 8} \\right)^{ - \\frac{1}{2}}}\\,\\left( 5 \\right)\\\\ \n& = \\frac{1}{{2\\sqrt {5x - 8} }}\\,\\,\\left( 5 \\right)\\\\ \n& = \\frac{5}{{2\\sqrt {5x - 8} }}\\end{align*}\n$$\n\nLet us check whether the computer gives the same answers, \n\n\n```julia\ny = sqrt(5x - 8)\nD(y)\n```\n\n\n\n\n\\begin{equation}\n\\frac{dsqrt(-8 + 5x)}{dx}\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(y))\n```\n\n\n\n\n\\begin{equation}\n\\frac{\\frac{5}{2}}{\\sqrt{-8 + 5 x}}\n\\end{equation}\n\n\n\n\n\n```julia\nf(x) = sqrt(5x - 8)\n\nf'(x) \n```\n\n\n\n\n\\begin{equation}\n\\frac{5}{2 \\sqrt{-8 + 5 x}}\n\\end{equation}\n\n\n\n\n#### Sum (difference) rule\n\nGiven functions $p$ and $q$ that are differentiable at $x$ and with $f(x) = p(x) + q(x)$ we have that the derivative according to the sum rule is given by, \n\n$$\nf^{\\prime } (x)=p^{\\prime } (x)+q^{\\prime } (x)\n$$\n\nLet us consider an example with the application of this rule. Find the derivative of $f(x) = 2x^5 + 7$. In this case, $p(x) = 2x^5$ and $q(x) = 7$. \n\n$$\n\\begin{align*} \nf'(x)&=\\dfrac{d}{dx}\\left(2x^5+7\\right)\\\\\n&=\\dfrac{d}{dx}(2x^5)+\\dfrac{d}{dx}(7) & & \\text{Apply the sum rule.}\\\\\n&=2\\dfrac{d}{dx}(x^5)+\\dfrac{d}{dx}(7) & & \\text{Apply the constant multiple rule.}\\\\ \n&=2(5x^4)+0 & & \\text{Apply the power rule and the constant rule.}\\\\\n&=10x^4 & & Simplify. \n\\end{align*}\n$$\n\nAs usual, we check the answer on the computer. \n\n\n```julia\ny = 2x^5 + 7\nD(y)\n```\n\n\n\n\n\\begin{equation}\n\\mathrm{\\frac{d}{d x}}\\left( 7 + 2 x^{5} \\right)\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(y))\n```\n\n\n\n\n\\begin{equation}\n10 x^{4}\n\\end{equation}\n\n\n\n\n\n```julia\nf(x) = 2x^5 + 7\n\nf'(x) \n```\n\n\n\n\n\\begin{equation}\n10 x^{4}\n\\end{equation}\n\n\n\n\nThese are the most important rules that we will use the most. The following rules are also used, but less frequently. \n\n#### Product rule\n\nGiven functions $p$ and $q$ that are differentiable at $x$ and with $f(x)=p(x)\\cdot q(x)$ we have that the derivative is, \n\n$$\nf^{\\prime } (x)=p^{\\prime } (x)\\cdot q(x)+p(x)\\cdot q^{\\prime } (x)\n$$\n\nConsider the following example, find $f'(x) = (x^2+2)(3x^3−5x)$ by applying the product rule. \n\nIf we set $p(x)=x2+2$ and $q(x)=3x3−5x$, then $p'(x)=2x$ and $q'(x)=9x2−5$ and therefore, \n\n$$\nf'(x)=p'(x)q(x)+q'(x)p(x)=(2x)(3x^3−5x)+(9x^2−5)(x^2+2)\n$$\n\nIf we simplify this we have $f'(x) = 15x4+3x2−10$\n\nCheck against the answer from computer, \n\n\n```julia\ny = (x^2 + 2)*(3x^3 − 5x)\nD(y)\n```\n\n\n\n\n\\begin{equation}\n\\mathrm{\\frac{d}{d x}}\\left( \\left( 2 + x^{2} \\right) \\left( 3 x^{3} - 5 x \\right) \\right)\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(y))\n```\n\n\n\n\n\\begin{equation}\n\\left( 2 + x^{2} \\right) \\left( -5 + 9 x^{2} \\right) + 2 x \\left( 3 x^{3} - 5 x \\right)\n\\end{equation}\n\n\n\n\nCheck against the automatic differentiation answer, \n\n\n```julia\nf(x) = (x^2 + 2)*(3x^3 − 5x)\n\nf'(x) \n```\n\n\n\n\n\\begin{equation}\n-10 - 5 x^{2} + 2 x \\left( 3 x^{3} - 5 x \\right) + 3 x^{2} \\left( 6 + 3 x^{2} \\right)\n\\end{equation}\n\n\n\n\n#### Exponential\n\nThe exponential function is used a lot in economics. We will often have functions such as $f(x) = \\exp(a \\cdot x)$. The derivative in this case is given by, \n\n$$\nf'(x) = a \\cdot \\exp(a \\cdot x)\n$$\n\nIn economics you will find the exponential function in the compounding of interest. The accumulated value of interest that is compounded continuously is given by \n\n$$\nA(t) = Pe^{rt}\n$$\n\nIf you wanted to take a derivative of this function with respect to the variable $t$ then you would get the following answer, \n\n$$\nA'(t) = r \\cdot Pe^{rt}\n$$\n\n\n```julia\nP = 10; r = 0.05 # choose arbitrary values for P and r\n\nf(x) = P * exp(r*x)\n\nf'(x) \n```\n\n\n\n\n\\begin{equation}\n0.5 e^{0.05 x}\n\\end{equation}\n\n\n\n\n#### Logarithm\n\nFinally, we have the derivative of a log function, which is used almost everywhere in economics. If we have the function $f(x) = \\log(x)$ then the derivative is given by, \n\n$$\nf'(x) = 1 / x\n$$\n\n\n```julia\nf(x) = log(x)\n\nf'(x)\n```\n\n\n\n\n\\begin{equation}\n\\frac{1}{x}\n\\end{equation}\n\n\n\n\n## Higher order derivatives\n\nWith these rules you should be able to tackle most problems that involve derivatives. These derivatives that we calculated were first order derivatives. We can actually take the derivative again with respect to the variable of interest and then we would have **second order derivatives**. The second order derivative is then a derivative of the first order derivative. \n\nWhile the first order derivative provides a rate of change (often a slope of a tangent line), the second order derivative gives us information on the rate of change of the rate of change. \n\n### Example: Cobb-Douglas\n\nWe can illustrate the usage of derivatives in economics with a basic example. Consider the Cobb-Douglas production function (which we will see again in the notebook on the Solow model). This is a simple explicit form for a production function that we often encounter in economics. The form of the function is as follows, \n\n$$\nF(K,L)=K^{\\alpha } \\cdot L^{\\beta}\n$$\n\nwhere $F$ is the production function and it is a function of the capital ($K$) and labour ($L$) inputs. In order to make this a univariate example, we fix the value of $K$, so that it isn't variable. The derivative with respect to labour gives us the marginal product of labour. The derivative is then given as, \n\n$$\n\\frac{{\\textrm{d}} Y(K,L)}{dL } = MPL(K,L)=(\\beta)\\cdot K^{\\alpha } \\cdot L^{\\beta - 1}\n$$\n\nThe derivative that we have obtained above is simply another function and we can take additional derivatives. The second order derivative is given by, \n\n$$\n\\frac{{\\textrm{d}}^2 Y(K,L)}{dL^2 }=(\\beta )\\cdot (\\beta -1)\\cdot K^{\\alpha } \\cdot L^{\\beta -2}\n$$\n\n\nWe can calculate the derivatives with `Symbolics` as well, \n\n\n```julia\n@variables K L α β\n\nD = Differential(L)\n\nY = K ^ (α) * L ^ (β)\nD(Y)\n```\n\n\n\n\n\\begin{equation}\n\\mathrm{\\frac{d}{d L}}\\left( L^{\\beta} K^{\\alpha} \\right)\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D(Y))\n```\n\n\n\n\n\\begin{equation}\nL^{-1 + \\beta} K^{\\alpha} \\beta\n\\end{equation}\n\n\n\n\n\n```julia\nD2 = Differential(L) * Differential(L)\n```\n\n\n\n\n Differential(L) ∘ Differential(L)\n\n\n\n\n```julia\nD2(Y)\n```\n\n\n\n\n\\begin{equation}\n\\frac{d(d / (d * L))(L ^ \\beta * K ^ \\alpha)}{dL}\n\\end{equation}\n\n\n\n\n\n```julia\nexpand_derivatives(D2(Y)) # second order derivative\n```\n\n\n\n\n\\begin{equation}\nL^{-2 + \\beta} K^{\\alpha} \\beta \\left( -1 + \\beta \\right)\n\\end{equation}\n\n\n\n\nWe seem to get the same answer as above if we do a quick check.\n\n### Curvature and second derivative\n\nFor our Cobb-Douglas example, we will graph the second derivative when $\\beta = 0.5$. The production function is concave. For any function that is twice continuously differentiable, the function is concave if and only if its second derivative is non-positive. \n\n\n```julia\nα = 0.5; β = 0.5\n\nK = 1\n\n@variables L\n\nD = Differential(L)\n\nY = K ^ (α) * L ^ (β)\nD(Y)\n\ndiff_1 = expand_derivatives(D(Y));\ndiff_2 = expand_derivatives(D2(Y));\n```\n\n\n```julia\nplot(Y, 0.2, 3, label = \"f(x)\", lw = 2, alpha = 0.7)\nplot!(diff_1, 0.2, 3, label = \"First derivative\", lw = 2, ls = :dashdot, alpha = 0.7)\nplot!(diff_2, 0.2, 3, label = \"Second derivative\", legend = :bottomright, lw = 2, ls = :dash, alpha = 0.7)\n```\n\n\n\n\n \n\n \n\n\n\nWe see that the first derivative is positive, which indicates that the slope of the function is always positive. In terms of the curvature though, the second derivative is always negative, which indicates that the slope of the function is positive but decreasing with an increase in labour. This means that the marginal return to labour is positive but decreasing with an increase in labour. \n\n## Conditions for local maxima\n\nPreviously we looked at the definitions for global and local maxima. In this section we describe the necessary conditions for optimality with respect to derivatives. In the univariate case (with only one variable), which we have mostly looked at thus far, the first and second order necessary condition for a local maxima is the following, \n\n1. **FONC:** $f'(x^*) =0$\n2. **SONC** $f''(x^*) \\leq 0$ (and $f''(x^*) \\geq 0$ for local minima)\n2. (**SOSC** $f''(x^*) < 0$ (and $f''(x^*) > 0$ for local minima))\n\n#### Examples\n\nAn easier way to determine the turning points for functions is to use the first and second order conditions. Say that we want to determine the minima and maxima of the following function,\n\n$$\nf(x) = 200 - 30x + 8x^2 - 1/2x^3\n$$\n\n\n```julia\nf(x) = 200 - 30 * x + 8 * x^2 - 0.5 * x^3\n```\n\n\n\n\n f (generic function with 1 method)\n\n\n\n\n```julia\nplot(f, 0, 12, lw = 2, legend = false)\n```\n\n\n\n\n \n\n \n\n\n\nIt appears from the graph that there are going to be two turning points. We want to calculate the local maximum in the interval $[0, 12]$. First we take the first order condition to find the place where the slope is zero. Then we look at the second order condition to determine if it is a maximum or minimum. For this we are going to be using a root finding package in Julia, called `Roots`.\n\n\n```julia\nroots = find_zeros(f', (0, 12)) # we are essentially setting f'(x) = 0 with this package. \n```\n\n\n\n\n 2-element Vector{Float64}:\n 2.427400704306218\n 8.239265962360449\n\n\n\n\n```julia\nplot(f, 0, 12, lw = 2, legend = false)\nvline!([roots[1], roots[2]], lw = 2, alpha = 0.6, ls = :dash, color = :black, xticks = ([roots[1], roots[2]]))\n```\n\n\n\n\n \n\n \n\n\n\nNext we need to check if the second order derivatives evaluated at the turning points are positive or negative in order to determine if they are maxima or minima. \n\n\n```julia\nf''(roots[1])\n```\n\n\n\n\n 8.717797887081346\n\n\n\nThis value is positive, so we don't believe that this is a maximum. We are looking for the maximum, and for that to be true we must have that the second order derivative is negative. \n\n\n```julia\nf''(roots[2])\n```\n\n\n\n\n -8.717797887081346\n\n\n\nIn this case we see that the value is negative, which indicates to us that this is a **maximum**. We can also look at original quadratic utility function to see whether that was a maximum. The code to find this maximum is the same as above. \n\n\n```julia\nα = 0.2 \n\nU(x) = x .- α .* x .^ 2\n\nutility_roots = find_zeros(U', (-10, 10))\n```\n\n\n\n\n 1-element Vector{Float64}:\n 2.5\n\n\n\nIn this case we get the correct answer, which differs marginally from the value we retrieved from the brute force grid method we used before. \n\n#### Exercise\n\nTotal revenue of the firm is given by $TR = 20Q - 2Q^2$ and the total cost function is $TC = Q^3 - 8Q^{2} + 20Q + 2$. Find the level of output that maximises total profit. First do this by hand and then try to solve the problem on the computer and see if you get the same answer. Verify that this level of output satisfies the condition that marginal revenue is equal to marginal cost. \n\n## Functions of multiple variables\n\nHere we talk about how to deal with functions $f: \\mathbb{R}^{n} \\rightarrow \\mathbb{R}$. This means functions that take values in $\\mathbb{R}^n$ and return a value along the real line. An example of this would be, \n\n$$\nf(x, y) = x^{2} + y^{2}\n$$\n\nThis is a function that takes in two inputs and returns one output. We will mostly be working with functions that have two inputs. In other words, those functions for which $n = 2$, so that we are operating initially in $\\mathbb{R}^2$. Before we continue, I am going to be using two helper functions, that will allow us to easily create some 3D plots. Do not worry too much about the code in the `minmax()` and `mmplotter()` functions, they are a bit more difficult to understand fully on the first reading. You are, however, equipped with all the tools to understand what is happening. This will simply require a careful reading of the first tutorial to figure out. \n\n### Plotting in 3D\n\n\n```julia\nfunction minmax()\n\t\n\tv = collect(range(-2, stop = 2, length = 30)) # values\n\tmini = [x^2 + y^2 for x in v, y in v]\n\tmaxi = -mini # max is just negative min\n\tsaddle = [x^2 + y^3 for x in v, y in v]\n\t\n\treturn Dict(:x => v,:min => mini, :max => maxi, :saddle => saddle)\nend;\n```\n\n\n```julia\nfunction mmplotter(s::Symbol)\n\t\n d = minmax()\n\n surface(d[:x], d[:x], d[s], fillalpha = 0.7, legend = false, fillcolor =:viridis)\nend;\n```\n\n\n```julia\nfunction mmcontour(s::Symbol)\n\t\n d = minmax()\n\n contour(d[:x], d[:x], d[s], fillalpha = 0.5, legend = false, fill = true, fillcolor = :viridis, color = :black)\nend;\n```\n\nWe can plot a set of points $(x, y, f(x, y))$ using a surface plot. The following provides the plot for the function $f(x, y) = x^{2} + y^{2}$ that we mentioned earlier.\n\n\n```julia\nmmplotter(:max)\n```\n\n\n\n\n \n\n \n\n\n\nIn addition to the surface plot, we can have a contour plot, which shows a top down view of the surface plot above. \n\n\n```julia\nmmcontour(:max)\n```\n\n\n\n\n \n\n \n\n\n\n### Partial derivatives\n\nFor a function $f: \\mathbb{R}^{n} \\rightarrow \\mathbb{R}$ the concept of a derivative is extended to partial derivatives for $n$ variables. The partial of $x$ is defined by holding $y$ constant while a derivative in $x$ is taken. We saw an example of this with our calculation of marginal product of labour in a previous example. \n\nThe partial derivative of a function $f$ with respect to the variable $x$, can be written as $\\frac{\\partial{f}}{\\partial{x}}$, which is defined as,\n\n$$\n\\dfrac{∂f}{∂x}=f_x(x,y)=\\lim_{h→0}\\dfrac{f(x+h,y)−f(x,y)}{h}\n$$\n\nIn this definition we see a new symbol, $\\partial$, which indicates a partial derivative. In this case we can also write the derivative with respect to $y$ so there are two partial derivatives for this function, since it is a function of two variables. \n\nThe gradient of $f$, which is referred to as $\\nabla f$, is the vector valued function of partial derivatives $[\\partial f / \\partial x, \\partial f / \\partial y]$.\n\n#### Calculating partial derivatives by hand\n\nIf we wanted to calculate the partial derivative for some function we would have to do the following. Consider the following function, \n\n$$\nf(x,y)=x^2−3xy+2y^2−4x+5y−12\n$$\n\nThe partial derivative of $f$ with respect to $x$ can be calculated using our definition above. First calculate $f(x + h, y)$,\n\n$$\n\\begin{align*} f(x+h,y) &=(x+h)^2−3(x+h)y+2y^2−4(x+h)+5y−12 \\\\ &=x^2+2xh+h^2−3xy−3hy+2y^2−4x−4h+5y−12. \\end{align*} \n$$\n\nNow we need to substitute this into our initial equation above and then simplify, \n\n$$\n\\begin{align*} \\dfrac{∂f}{∂x} &=\\lim_{h→0}\\dfrac{f(x+h,y)−f(x,y)}{h} \\\\ \n&=\\lim_{h→0}\\dfrac{(x^2+2xh+h^2−3xy−3hy+2y^2−4x−4h+5y−12)−(x^2−3xy+2y^2−4x+5y−12)}{h} \\\\ &=\\lim_{h→0}\\dfrac{x^2+2xh+h^2−3xy−3hy+2y^2−4x−4h+5y−12−x^2+3xy−2y^2+4x−5y+12}{h} \\\\ \n&=\\lim_{h→0}\\dfrac{2xh+h^2−3hy−4h}{h}\\\\ \n&=\\lim_{h→0}\\dfrac{h(2x+h−3y−4)}{h} \\\\ \n&=\\lim_{h→0}(2x+h−3y−4) \\\\ \n&=2x−3y−4. \\end{align*}\n$$\n\n\nThe same thing can be done for the partial derivative of $f$ with respect to $y$. As an exercise, you might want to try and do this for $y$. The answer should be $-3x + 4y + 5$. \n\nNow, we won't always use this method to find the partial derivative. There are easier ways than using the definition above. For the partial derivative, we can think about it as taking a derivative of the one variable while holding the other constant. Exactly like we did for our example with the Cobb-Douglas production function. \n\nSo the easier way to take a partial derivative of $f$ with respect to $x$ would be to treat the variable $y$ like it was a constant and apply the usual single variable calculus rules. \n\nLet us consider the individual components of the function. \n\nIn the case of $x^{2}$, we would have that the derivative is $2x$. \n\nFor $-3xy$ we treat the $y$ like a constant, so the derivative is $-3y$.\n\nThe next term, $2y^2$ falls away completely since it is constant. The same is true for $5y$ and $12$.\n\nFinally, we are left with $-4x$, with a derivative given by $-4$. \n\nIf we then add these components together, we get our answer $2x - 3y - 4$\n\n#### Differentiation via the computer\n\nWe can compute the partial derivatives using the `Symbolics` package as follows, \n\n\n```julia\n@variables x y\n\nl = x^2 − 3x*y + 2y^2 − 4x + 5y − 12\n\nH = Differential(x);\nI = Differential(y);\n```\n\n\n```julia\nexpand_derivatives(H(l)) # partial derivative of f(x, y) wrt to x\n```\n\n\n\n\n\\begin{equation}\n-4 + 2 x - 3 y\n\\end{equation}\n\n\n\n\nAlternatively we can use automatic differentiation to calculate the partial derivatives. \n\n\n```julia\nf(x) = x[1]^2 − 3x[1]*x[2] + 2x[2]^2 − 4x[2] + 5x[2] − 12\n\n∇f(x) = ForwardDiff.gradient(f, x)\n\n∂f_∂x(x, y) = ∇f([x, y])[1];\n∂f_∂y(x, y) = ∇f([x, y])[2];\n```\n\nWith this we can now find the gradient at any particular point, say for example we want the partial derivative of $f(x, y)$ with respect to $x$ at the point $(1, 2)$ we can do the following, \n\n\n```julia\n∂f_∂x(1, 2)\n```\n\n\n\n\n -4\n\n\n\nThis has been a brief introduction to unconstrained optimisation. We will continue this discussion in our next tutorial. \n", "meta": {"hexsha": "e3d95d1af04cfd01173080512bc183e3f7a2ccb3", "size": 1031227, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/tut2_data_analysis.ipynb", "max_stars_repo_name": "andiegauna/Macro-318", "max_stars_repo_head_hexsha": "db3a8f67f8b999f2722e20398a1fbd1c9a201893", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/tut2_data_analysis.ipynb", "max_issues_repo_name": "andiegauna/Macro-318", "max_issues_repo_head_hexsha": "db3a8f67f8b999f2722e20398a1fbd1c9a201893", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/tut2_data_analysis.ipynb", "max_forks_repo_name": "andiegauna/Macro-318", "max_forks_repo_head_hexsha": "db3a8f67f8b999f2722e20398a1fbd1c9a201893", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 258.3233967936, "max_line_length": 171041, "alphanum_fraction": 0.6851217045, "converted": true, "num_tokens": 24352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709846, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1503165305139505}} {"text": "```python\nfrom IPython.core.display import HTML\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n# Lecture 6: Indirect methods for constrained optimization\n\n## Some remarks\n* How to deal with problems where the objective function should be maximized, i.e. $\\max f(x)$?\n * We can use the same methods if we instead minimize the negative of $f$, i.e. $\\min -f(x)$\n * The optimal solution $x^*$ is the same for both the problems\n\n\n```python\n# insert image\nfrom IPython.display import Image\nImage(filename = \"Images\\MaxEqMin.jpg\", width = 200, height = 300)\n```\n\n\n\n\n \n\n \n\n\n\n## Simple example\n\n\n```python\ndef f_max(x):\n return -(x-3.0)**2 + 10.0\n\n# clearly x* = 3.0 is the global maximum \n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(-5.0, 12.0, 0.3)\nplt.plot(x, f_max(x), 'bo')\nplt.show()\nprint(f_max(3.0))\n```\n\n\n```python\nfrom scipy.optimize import minimize_scalar\n\n# multiply f_max with -1.0\ndef g(x):\n return -f_max(x)\n\nplt.plot(x, g(x), 'ro')\nplt.show()\n```\n\n\n```python\nres = minimize_scalar(g,method='brent')\nprint(res)\nprint(g(res.x))\nprint(f_max(res.x))\n```\n\n fun: -10.0\n nfev: 10\n nit: 4\n success: True\n x: 3.0\n -10.0\n 10.0\n\n\n# Constrained optimization\n\nNow we will move to studying constrained optimization problems i.e., the full problem\n$$\n\\begin{align} \\\n\\min \\quad &f(x)\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_k(x) = 0\\text{ for all }k=1,\\ldots,K\\\\\n&a_i\\leq x_i\\leq b_i\\text{ for all } i=1,\\ldots,n\\\\\n&x\\in \\mathbb R^n,\n\\end{align}\n$$\nwhere for all $i=1,\\ldots,n$ it holds that $a_i,b_i\\in \\mathbb R$ or they may also be $-\\infty$ or $\\infty$.\n\n## On optimal solutions for constrained problems\n* Two types of constraints: equality and inequality constraints\n* Inequality constraint $g_i(x)\\geq0$ is said to be *active* at point $x$ if $g_i(x)=0$\n* Linear constraints are much easier to consider --> their gradients are constant\n* Nonlinear constraints trickier --> gradient changes for different values of decision variables\n\nNo constraints\n\n*Adopted from Prof. L.T. Biegler (Carnegie Mellon University)*\n\nInequality constraints\n\n*Adopted from Prof. L.T. Biegler (Carnegie Mellon University)*\n\nBoth inequality and equality constraints\n\n*Adopted from Prof. L.T. Biegler (Carnegie Mellon University)*\n\n## Transforming the constraints\nType of inequality:\n$$\ng_i(x)\\geq0 \\iff -g_i(x)\\leq0\n$$\n\n\nInequality to equality:\n$$\ng_i(x)\\leq0 \\iff g_i(x)+y_i^2=0\n$$\n* $y_i$ is a *slack variable*; constraint is active if $y_i=0$\n* By adding $y_i^2$ no need to add $y_i\\geq0$\n* If $g$ is linear, linearity can be preserved by $g_i(x)+y_i=0, y_i\\geq0$\n\nEquality to inequality:\n$$\nh_i(x)=0 \\iff h_i(x)\\geq0 \\text{ and } -h_i(x) \\geq0\n$$\n\n## Example problem\nFor example, we can have an optimization problem\n$$\n\\begin{align} \\\n\\min \\quad &x_1^2+x_2^2\\\\\n\\text{s.t.} \\quad & x_1+x_2-1\\geq 0\\\\\n&-1\\leq x_1\\leq 1, x_2\\leq 3.\\\\\n\\end{align}\n$$\n\nIn order to optimize that problem, we can define the following python function:\n\n\n```python\nimport numpy as np\ndef f_constrained(x):\n return np.linalg.norm(x)**2,[x[0]+x[1]-1, x[0]+1,-x[0]+1,-x[1]+3],[]\n```\n\n\n```python\n#np.linalg.norm??\n```\n\nNow, we can call the function:\n\n\n```python\n(f_val,ieq,eq) = f_constrained([1,0])\nprint(\"Value of f is \"+str(f_val))\nif len(ieq)>0:\n print(\"The values of inequality constraints are:\")\n for ieq_j in ieq:\n print(str(ieq_j)+\", \")\nif len(eq)>0:\n print(\"The values of the equality constraints are:\")\n for eq_k in eq:\n print(str(eq_k)+\", \")\n```\n\n Value of f is 1.0\n The values of inequality constraints are:\n 0, \n 2, \n 0, \n 3, \n\n\nIs this solution feasible?\n\n\n```python\nif all([ieq_j>=0 for ieq_j in ieq]) and all([eq_k==0 for eq_k in eq]):\n print(\"Solution is feasible\")\nelse:\n print(\"Solution is infeasible\")\n```\n\n Solution is feasible\n\n\n# Indirect and direct methods for constrained optimization\n\nThere are two categories of methods for constrained optimization: Indirect and direct methods (based on how they treat constraints). \n\nThe main difference is that\n\n1. **Indirect** methods convert the constrained optimization problem into a single or a sequence of unconstrained optimization problems, that are then solved. Often, the intermediate solutions do not need to be feasible, but the sequence of solutions converges to a solution that is optimal for the original problem (and, thus, feasible).\n\n2. **Direct** methods deal with the constrained optimization problem directly. In this case, all the intermediate solutions are feasible.\n\n# Indirect methods\n\n## Penalty function methods\n\n**IDEA:** Include constraints into the objective function with the help of penalty functions that **penalize constraint violations**.\n\n* **Exterior** penalty functions (approaching the optimum from outside of the feasible region)\n* **Interior** penalty functions (approaching the optimum from inside of the feasible region)\n\n### Exterior penalty functions\n\nLet, $\\alpha(x):\\mathbb R^n\\to\\mathbb R$ be a function so that \n* $\\alpha(x)= 0$, for all feasible $x$\n* $\\alpha(x)>0$, for all infeasible $x$.\n\nDefine a set of optimization problems (depending on parameter $r$)\n$$\n\\begin{align} \\\n\\min \\qquad &f(x)+r\\alpha(x)\\\\\n\\text{s.t.} \\qquad &x\\in \\mathbb R^n\n\\end{align}\n$$\nwhere 𝛼(𝑥) is a **penalty function** and 𝑟 is a **penalty parameter**.\n\nfor $r>0$. Let $x_r$ be an optimal solution of such problem for a given $r$.\n\nIn this case, the optimal solutions $x_r$ converge to the optimal solution of the constrained problem, when \n\n* $r\\to\\infty$, (in exterior penalty functions) \n\nif such a solution exists.\n\n* All the functions should be continuous\n* For each 𝑟, there should exist a solution for penalty functions problem and $𝑥_𝑟$ belongs to a compact subset of $\\mathbb R^n$\n\nFor example, good ideas for penalty functions are\n* $h_k(x)^2$ for equality constraints,\n* $\\left(\\min\\{0,g_j(x)\\}\\right)^2$ for inequality constraints $g_j(x) \\geq 0$, or\n* $\\left(\\max\\{0,g_j(x)\\}\\right)^2$ for inequality constraints $g_j(x) \\leq 0$.\n\n# Illustrative example\n$$\n\\min x \\\\\n\\text{ s.t. } -x + 2 \\leq 0\n$$\nLet\n$$\n\\alpha(x) = (\\max[0,(-x+2)])^2 \n$$\n\nThen\n\n$$\n\\alpha(x) = 0, \\text{ if }x\\geq2\n$$\n$$\n \\alpha(x) = (-x+2)^2, \\text{ if } x<2\n$$\n\n\n\nMinimum of $f(x)+r\\alpha(x)$ is at $2-1/2r$\n\n\nThen, if $ r \\rightarrow \\infty$, $$ \\text{Min} f(x) + r \\alpha(x) = 2 = \\text{Min} f(x) $$\n\nIn general, a constrained optimization problem in a form of\n$$\n\\begin{align} \\\n\\min \\quad &f(x)\\\\\n\\text{s.t.} \\quad & g_j(x) \\geq 0\\text{ for all }j=1,\\ldots,J\\\\\n& h_k(x) = 0\\text{ for all }k=1,\\ldots,K\\\\\n&x\\in \\mathbb R^n,\n\\end{align}\n$$\n\ncan be converted to the following unconstrained optimization problem with a penalty function\n\n$$ \n\\alpha(x) = \\sum_{j=1}^J{(\\min\\{0,g_j(x)\\})^2} + \\sum_{k=1}^K{h_k(x)^2}\n$$\n\n\n\n```python\ndef alpha(x,f):\n (_,ieq,eq) = f(x)\n return sum([min([0,ieq_j])**2 for ieq_j in ieq]) + sum([eq_k**2 for eq_k in eq])\n```\n\nLet us go back to our example:\n$$\n\\begin{align} \\\n\\min \\quad &x_1^2+x_2^2\\\\\n\\text{s.t.} \\quad & x_1+x_2-1\\geq 0\\\\\n&-1\\leq x_1\\leq 1, x_2\\leq 3.\\\\\n\\end{align}\n$$\n\n\n```python\nalpha([1,0],f_constrained)\n```\n\n\n\n\n 0\n\n\n\n\n```python\ndef penalized_function(x,f,r):\n return f(x)[0] + r*alpha(x,f)\n```\n\n\n```python\n# by increasing r we increase the penalty for being infeasible\nprint(penalized_function([-1,0],f_constrained,10000))\nprint(penalized_function([-1,0],f_constrained,100))\nprint(penalized_function([-1,0],f_constrained,10))\nprint(penalized_function([-1,0],f_constrained,1))\n```\n\n 40001.0\n 401.0\n 41.0\n 5.0\n\n\nLet's solve the penalty problem by using Nelder-Mead from scipy.optimize\n\n\n```python\nfrom scipy.optimize import minimize\nres = minimize(lambda x:penalized_function(x,f_constrained,10000000000),# by increasing r we assure convergency\n [0,0],method='Nelder-Mead', \n options={'disp': True})\nprint(res.x)\n```\n\n Optimization terminated successfully.\n Current function value: 0.500000\n Iterations: 60\n Function evaluations: 104\n [0.5 0.5]\n\n\n\n```python\n(f_val,ieq,eq) = f_constrained(res.x)\nprint(\"Value of f is \"+str(f_val))\nif len(ieq)>0:\n print(\"The values of inequality constraints are:\")\n for ieq_j in ieq:\n print(str(ieq_j)+\", \")\nif len(eq)>0:\n print(\"The values of the equality constraints are:\")\n for eq_k in eq:\n print(str(eq_k)+\", \")\n\nif all([ieq_j>=0 for ieq_j in ieq]) and all([eq_k==0 for eq_k in eq]):\n print(\"Solution is feasible\")\nelse:\n print(\"Solution is infeasible\")\n```\n\n Value of f is 0.5000000000000003\n The values of inequality constraints are:\n 4.440892098500626e-16, \n 1.5, \n 0.5, \n 2.4999999999999996, \n Solution is feasible\n\n\n### How to set the penalty parameter $r$?\n\nThe penalty parameter should\n* be large enough in order for the solutions be close enough to the feasible region, but\n* not be too large to\n * cause numerical problems, or\n * cause premature convergence to non-optimal solutions because of relative tolerances.\n\nUsually, the penalty term is either\n* set as big as possible without causing problems (hard to know), or\n* updated iteratively.\n\n\n**Note:** \n\n* We solved our example problem with a fixed value for the penalty parameter $r$. In order to make the penalty function method work in practice, you have to implement the iterative update for $r$. This you can practice in one of the upcoming exercises!\n\n$$\n\\begin{align} \\\n\\min \\quad &f(x) + \\sum_{j=1}^J{r_j(\\min\\{0,g_j(x)\\})^2} + \\sum_{k=1}^K{r_kh_k(x)^2} \\\\\n\\text{s.t.} &\\\\ \n&x\\in \\mathbb R^n,\n\\end{align}\n$$\n\n* The starting point for solving the penalty problems can be selected in an efficient way. When you set $r_i$ and solve the corresponding unconstrained penalty problem, you get an optimal solution $x_{r_i}$. Then you update $r_i\\rightarrow r_{i+1}$ and you can use $x_{r_i}$ as a starting point for solving the penalty problem with $r_{i+1}$.\n\n# Barrier function methods\n\n**IDEA:** Prevent leaving the feasible region so that the value of the objective is $\\infty$ outside the feasible set (an **interior** method).\n\nThis method is only applicable to problems with inequality constraints and for which the set \n$$\\{x\\in \\mathbb R^n: g_j(x)>0\\text{ for all }j=1,\\ldots,J\\}$$\nis non-empty.\n\nLet $\\beta:\\{x\\in \\mathbb R^n: g_j(x)>0\\text{ for all }j=1,\\ldots,J\\}\\to \\mathbb R$ be a function so that $\\beta(x)\\to \\infty$, when $x\\to\\partial\\{x\\in \\mathbb R^n: g_j(x)>0\\text{ for all }j=1,\\ldots,J\\}$, where $\\partial A$ is the boundary of the set $A$. \n\nNow, define optimization problem \n$$\n\\begin{align}\n\\min \\qquad & f(x) + r\\beta(x)\\\\\n\\text{s.t. } \\qquad & x\\in \\{x\\in \\mathbb R^n: g_j(x)>0\\text{ for all }j=1,\\ldots,J\\}.\n\\end{align}\n$$\nand let $x_r$ be the optimal solution of this problem (which we assume to exist for all $r>0$).\n\nIn this case, $x_r$ converges to the optimal solution of the problem (if it exists), when $r\\to 0^+$ (i.e., $r$ converges to zero from the right side (= positive numbers)).\n\nA good idea for a barrier function is $-\\frac1{g_j(x)}$.\n\n## Example\n$$\nmin \\text{ } 𝑥 \\\\\n𝑠.𝑡. −𝑥 + 1 ≤ 0\n$$\n\nLet $𝛽(𝑥) = −\\frac1{−𝑥+1}$ when $𝑥 ≠ 1$\n\n$$\n\\min 𝑓(𝑥) + 𝑟𝛽(𝑥) = 𝑥 + \\frac{𝑟}{𝑥 − 1}\n$$\n\nis at 1 + $\\sqrt r$\n\nThen, if $ r \\rightarrow 0$, $$ \\text{Min} f(x) + r \\beta(x) = 1 = \\text{Min} f(x) $$\n\n\n\n\n```python\ndef beta(x,f):\n _,ieq,_ = f(x)\n try:\n value=sum([1/max([0,ieq_j]) for ieq_j in ieq])\n except ZeroDivisionError:\n value = float(\"inf\")\n return value \n```\n\n\n```python\ndef function_with_barrier(x,f,r):\n return f(x)[0]+r*beta(x,f)\n```\n\n\n```python\n# let's try to find a feasible starting point\nprint(f_constrained([1,1]))\n```\n\n (2.0000000000000004, [1, 2, 0, 2], [])\n\n\n\n```python\nfrom scipy.optimize import minimize\nres = minimize(lambda x:function_with_barrier(x,f_constrained,0.1),\n [1,1],method='Nelder-Mead', options={'disp': True})\nprint(res.x)\n```\n\n Warning: Maximum number of function evaluations has been exceeded.\n [1. 1.]\n\n\n C:\\devel\\anaconda3\\lib\\site-packages\\scipy\\optimize\\optimize.py:734: RuntimeWarning: invalid value encountered in subtract\n np.max(np.abs(fsim[0] - fsim[1:])) <= fatol):\n\n\n\n```python\n\"\"\" \nTo reduce the number of function evaluations, I eliminated some constraints for the sake of education. \nAlso, here we know the optimum and can check if it does not satisfy the eliminated constraints.\nBut, in practice, we should either increase the limitation of the function evaluations in the code \nor use a different method that needs fewer function evaluations.\n\"\"\"\ndef f_constrained(x):\n return np.linalg.norm(x)**2,[x[0]+x[1]-1],[]\n```\n\n\n```python\nfrom scipy.optimize import minimize\nres = minimize(lambda x:function_with_barrier(x,f_constrained,.000000000010), # test different values for r and track the optimum\n [1,1],method='Nelder-Mead', options={'disp': True})\nprint(res.x)\n```\n\n Optimization terminated successfully.\n Current function value: 0.500006\n Iterations: 64\n Function evaluations: 111\n [0.49999611 0.50000691]\n\n\n\n```python\n(f_val,ieq,eq) = f_constrained(res.x)\nprint(\"Value of f is \"+str(f_val))\nif len(ieq)>0:\n print(\"The values of inequality constraints are:\")\n for ieq_j in ieq:\n print(str(ieq_j)+\", \")\nif len(eq)>0:\n print(\"The values of the equality constraints are:\")\n for eq_k in eq:\n print(str(eq_k)+\", \")\nif all([ieq_j>=0 for ieq_j in ieq]) and all([eq_k==0 for eq_k in eq]):\n print(\"Solution is feasible\")\nelse:\n print(\"Solution is infeasible\")\n```\n\n Value of f is 0.5000030228178015\n The values of inequality constraints are:\n 3.022754969661534e-06, \n Solution is feasible\n\n\nIt is 'easy' to see that x* = (0.5,0.5) and f(x*) = 0.5\n\nhttps://www.wolframalpha.com/input/?i=minimize+x%5E2%2By%5E2+on+x%2By%3E%3D1\n\n\n```python\nprint(f_constrained([.5,.5]))\n```\n\n (0.5000000000000001, [0.0], [])\n\n\n## Other notes about using penalty and barrier function methods\n\n* It is worthwhile to consider whether feasibility can be compromised. If the constraints do not have any tolerances, then the barrier function method should be considered.\n\n* Also barrier methods parameter can be set iteratively\n\n* Penalty and barrier functions should be chosen so that they are differentiable (thus $x^2$ above)\n\n* In both methods, the minimum is attained at the limit.\n\n* Different penalty and barrier parameters can be used for different constraints, even for the same problem.\n", "meta": {"hexsha": "1e08a1f94c01a46e6a0fabbca7b723d8f4ea8e18", "size": 97255, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture 6, Indirect methods for constrained optimization.ipynb", "max_stars_repo_name": "bshavazipour/TIES483-2022", "max_stars_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture 6, Indirect methods for constrained optimization.ipynb", "max_issues_repo_name": "bshavazipour/TIES483-2022", "max_issues_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 6, Indirect methods for constrained optimization.ipynb", "max_forks_repo_name": "bshavazipour/TIES483-2022", "max_forks_repo_head_hexsha": "93dfabbfe1e953e5c5f83c44412963505ecf575a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-03T09:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T09:40:02.000Z", "avg_line_length": 76.8814229249, "max_line_length": 49917, "alphanum_fraction": 0.8148064367, "converted": true, "num_tokens": 4589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.15008394509861017}} {"text": "+ This notebook is part of lecture 12 *Graphs, netwroks, and incidence matrices* in the OCW MIT course 18.06 by Prof Gilbert Strang [1]\n+ Created by me, Dr Juan H Klopper\n + Head of Acute Care Surgery\n + Groote Schuur Hospital\n + University Cape Town\n + Email me with your thoughts, comments, suggestions and corrections \n
Linear Algebra OCW MIT18.06 IPython notebook [2] study notes by Dr Juan H Klopper is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.\n\n+ [1] OCW MIT 18.06\n+ [2] Fernando Pérez, Brian E. Granger, IPython: A System for Interactive Scientific Computing, Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007, doi:10.1109/MCSE.2007.53. URL: http://ipython.org\n\n\n```python\nfrom IPython.core.display import HTML, Image\ncss_file = 'style.css'\nHTML(open(css_file, 'r').read())\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom sympy import init_printing, symbols, Matrix\nfrom warnings import filterwarnings\nfrom IPython.display import Image\n```\n\n\n```python\ninit_printing(use_latex = 'mathjax')\nfilterwarnings('ignore')\n```\n\n# Graphs and networks\n# Incidence matrices\n# Kirchhoff's laws\n\n* This lecture is about the application of matrices\n\n## Graphs and networks\n\n* In this instance we refer to nodes and there connections called edges\n* Consider the graph below:\n\n\n```python\nImage(filename = 'Graph1.png')\n```\n\n* We will call the nodes *n* (columns), in this case *n* = 4\n* The edges (connections) will be called *m* (rows), with *m* = 5 in this case\n* This will give us a *m*×*n* = 5×4 matrix\n* We will have to give a direction to every edge\n\n## The incidence matrix\n\n* This corresponds to the graph above\n\n\n```python\nA = Matrix([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 1, 0], [-1, 0, 0, 1], [0, 0, -1, 1]])\nA\n# For each row (edge) look only at that edge (line)\n# In the case of row (edge, line) 1, the arrow point away from node 1, hence the first -1 in the matrix\n# The arrow point towards node 2, hence the 1\n# It does not point to nodes 3 and 4, hence the 0's\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 1 & 0 & 0\\\\0 & -1 & 1 & 0\\\\-1 & 0 & 1 & 0\\\\-1 & 0 & 0 & 1\\\\0 & 0 & -1 & 1\\end{matrix}\\right]$$\n\n\n\n* Edges 1, 2, and 3 form a loop\n* Notice for the first loop (edges 1, 2, and 3) the corresponding third row is a linear combination of rows 1 and 2\n* Intuitively, you can see that you can reach node 3 from node 1 by a combination of edges (rows) 1 and 2\n\n\n```python\nA.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 0 & -1\\\\0 & 1 & 0 & -1\\\\0 & 0 & 1 & -1\\\\0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 2\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* We note that we have three pivot columns, hence a rank, *r* = 3\n* We have one column without a pivot and will thus have one in the nullspace (*n* - *r* = 4 - 3 = 1)\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\\\1\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* The basis for this subspace is one dimensional and includes all scalar multiplications of this vector\n* The meaning in our example is that nothing will happen when the solutions fall on this line in 4-dimensional space, i.e. no current will flow\n\n* If you think of the solution **x** and every component of **x** being a potential at a node, the matrix multiplication A**x** gives you the potential differences along the edges\n* The nullspace would then be the solution where all the potential differences are 0\n\n\n```python\nx1, x2, x3, x4 = symbols('x1, x2, x3, x4')\n```\n\n\n```python\nx_vect = Matrix([x1, x2, x3, x4])\nx_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}x_{1}\\\\x_{2}\\\\x_{3}\\\\x_{4}\\end{matrix}\\right]$$\n\n\n\n\n```python\nA * x_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}- x_{1} + x_{2}\\\\- x_{2} + x_{3}\\\\- x_{1} + x_{3}\\\\- x_{1} + x_{4}\\\\- x_{3} + x_{4}\\end{matrix}\\right]$$\n\n\n\n* For the nullspace, each row now equals 0 (the potential difference between two nodes)\n\n* Let's look at the row space and the nullspace of the row picture\n* We now to get the rowspace by transposing the row that contain pivots\n\n\n```python\nA_row = Matrix([[1, 0, 0, -1], [0, 1, 0, -1], [0, 0, 1, -1]]).transpose()\nA_row\n```\n\n\n\n\n$$\\left[\\begin{matrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\\\-1 & -1 & -1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 1 & 0 & 0\\\\0 & -1 & 1 & 0\\\\-1 & 0 & 1 & 0\\\\-1 & 0 & 0 & 1\\\\0 & 0 & -1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.transpose()\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 0 & -1 & -1 & 0\\\\1 & -1 & 0 & 0 & 0\\\\0 & 1 & 1 & 0 & -1\\\\0 & 0 & 0 & 1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.transpose().rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 1 & 0 & -1\\\\0 & 1 & 1 & 0 & -1\\\\0 & 0 & 0 & 1 & 1\\\\0 & 0 & 0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 3\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* Note how the pivot columns are columns 1, 2, and 4\n* These represent edges 1, 2, 4\n* Note (form the graph above) that thye are independent as they are not a part of a loop\n* A graph without a loop (with 1 less edge than nodes) is called a *tree*\n* It has a nullspace of\n\n\n```python\nA.transpose().nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}-1\\\\-1\\\\1\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}1\\\\1\\\\0\\\\-1\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* The dimension of the nullspace of AT is *m* - *r* = number of edges minus (number of nodes - 1)\n* ∴ number of nodes - number of edges + number of loops = 1\n* This is Euler's formula and works for all graphs\n* It tells you how many independent loops there are\n\n* There is a connection between potentials and currents\n* With 5 edges we will have 5 currents, which we can represent as a vector **y**\n$$ \\overline { y } =\\begin{bmatrix} { y }_{ 1 } & { y }_{ 2 } & { y }_{ 3 } & { y }_{ 4 } & { y }_{ 5 } \\end{bmatrix} $$\n* This relationship is Ohm's law\n\n## Kirchhoff's law\n\n* By the way, Kirchhoff's current law is: AT**y** = **0**\n* We can look at it in the following way\n\n\n```python\nA.transpose()\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 0 & -1 & -1 & 0\\\\1 & -1 & 0 & 0 & 0\\\\0 & 1 & 1 & 0 & -1\\\\0 & 0 & 0 & 1 & 1\\end{matrix}\\right]$$\n\n\n\n\n```python\ny1, y2, y3, y4, y5 = symbols('y1, y2, y3, y4, y5')\n```\n\n\n```python\ny_vect = Matrix([y1, y2, y3, y4, y5])\ny_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}y_{1}\\\\y_{2}\\\\y_{3}\\\\y_{4}\\\\y_{5}\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.transpose() * y_vect\n```\n\n\n\n\n$$\\left[\\begin{matrix}- y_{1} - y_{3} - y_{4}\\\\y_{1} - y_{2}\\\\y_{2} + y_{3} - y_{5}\\\\y_{4} + y_{5}\\end{matrix}\\right]$$\n\n\n\n* For row 1 (setting it equal to 0 and looking at graph above tells us that current flows out from node 1 on all these 3 edges\n* For row 2 (doing the same as above) we note that for node 2 current flow towards it on edge *y*1 and away from it along edge *y*2\n* For row 3 we note that current flows from node three along edges 2 (edge *y*2) and 3 (edge *y*3) and away from it along edge 5 (edge *y*5)\n* For row 4 we note that current flows towards it along edges 4 (edge *y*4) and 5 (edge *y*5)\n\n* Look back at the nullspace of AT\n* The two basis vectors show the flow in current that will allow for NO current to accumulate at a node\n* In this example, current flowed along the loop of edges 1, 2, and 3 (with nothing along 4 and 5\n* The other solution would be current flowing all along the periphery, with nothing along 3\n* These are the basis vectors of the nullspace\n* Another valid basis would include flow along the upper loop\n* Notice that the basis is two dimensional as (between the 3 flows explained above) one is a linear combination of the other two\n\n## Putting it all together\n\n* All of the above can be stated as follows\n$$ \\overline {e} = {A} \\overline {x} $$\n$$ \\overline {y} = {C} \\overline {e} $$\n$$ A^{ T }\\overline { y } =\\overline { f } $$\n* Where\n * **e** is the potential differences\n * **f** is an external current in Kirchhoff's law\n* This gives us the fundamental equation for applications as stated here\n$$ {A}^{T}{C}{A} \\overline{x}=\\overline{f} $$\n* These equations are for equilibrium (no Newton's law, no time)\n\n* Remember that ATA is always symmetric\n\n## Example problem\n\n### Example problem 1\n\n\n```python\nImage(filename = 'Graph2.png')\n```\n\n* Calculate the incidence matrix A\n* Calculate the nullspaces of A and AT\n* Calculate the trace of ATA\n\n#### Solution\n\n\n```python\nA = Matrix([[-1, 1, 0, 0, 0], [0, -1, 1, 0, 0], [-1, 0, 1, 0, 0], [0, -1, 0, 1, 0], [0, 0, 0, -1, 1], [0, 0, 1, 0, -1]])\nA\n```\n\n\n\n\n$$\\left[\\begin{matrix}-1 & 1 & 0 & 0 & 0\\\\0 & -1 & 1 & 0 & 0\\\\-1 & 0 & 1 & 0 & 0\\\\0 & -1 & 0 & 1 & 0\\\\0 & 0 & 0 & -1 & 1\\\\0 & 0 & 1 & 0 & -1\\end{matrix}\\right]$$\n\n\n\n\n```python\nA.rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 0 & 0 & -1\\\\0 & 1 & 0 & 0 & -1\\\\0 & 0 & 1 & 0 & -1\\\\0 & 0 & 0 & 1 & -1\\\\0 & 0 & 0 & 0 & 0\\\\0 & 0 & 0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 2, & 3\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* We note that we have 4 independent columns\n* The dimension of the nullspace will be *n* - *r* = 5 - 4 = 1\n* We will let *x*5 = *s*, then from the row-reduced echelon form abobe we have\n$$ { x }_{ 1 }-{ x }_{ 5 }=0\\\\ { x }_{ 2 }-{ x }_{ 5 }=0\\\\ { x }_{ 3 }-{ x }_{ 5 }=0\\\\ { x }_{ 4 }-{ x }_{ 5 }=0\\\\ \\begin{bmatrix} { x }_{ 1 } \\\\ { x }_{ 2 } \\\\ { x }_{ 3 } \\\\ { x }_{ 4 } \\\\ { x }_{ 5 } \\end{bmatrix}=s\\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ 1 \\\\ 1 \\end{bmatrix} $$\n\n\n```python\nA.nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}1\\\\1\\\\1\\\\1\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* It represents a potential difference between all nodes t be zero: A**x** = **0**\n* This means that the potential at all nodes must be a constant\n\n\n```python\nA.transpose().nullspace()\n```\n\n\n\n\n$$\\begin{bmatrix}\\left[\\begin{matrix}-1\\\\-1\\\\1\\\\0\\\\0\\\\0\\end{matrix}\\right], & \\left[\\begin{matrix}0\\\\-1\\\\0\\\\1\\\\1\\\\1\\end{matrix}\\right]\\end{bmatrix}$$\n\n\n\n* It is of dimension 2, as there are two independent loops\n* As per Euler's formula\n * nodes - edges + loops = 1\n * 5 - 6 + 2 = 1\n* This tells us about current that needs to flow so as not to accumulate current at a node\n* It therefor indicates the independent loops\n* It works out beautifully\n * Look at the two loops and assign flow as per the two vector columns for each edge and you will see perfect flow along either of the two independent loops with no current accumulating at any node\n\n* We could calculate it from the row-reduced echelon for of AT\n\n\n```python\nA.transpose().rref()\n```\n\n\n\n\n$$\\begin{pmatrix}\\left[\\begin{matrix}1 & 0 & 1 & 0 & 0 & 0\\\\0 & 1 & 1 & 0 & 0 & 1\\\\0 & 0 & 0 & 1 & 0 & -1\\\\0 & 0 & 0 & 0 & 1 & -1\\\\0 & 0 & 0 & 0 & 0 & 0\\end{matrix}\\right], & \\begin{bmatrix}0, & 1, & 3, & 4\\end{bmatrix}\\end{pmatrix}$$\n\n\n\n* This gives us 4 independent columns, with dependent *y*3 and *y*6\n$$ y_{ 6 }=s\\\\ { y }_{ 3 }=t\\\\ { y }_{ 1 }+{ y }_{ 3 }={ y }_{ 1 }+t=0\\\\ \\therefore \\quad { y }_{ 1 }=-t\\\\ { y }_{ 2 }+{ y }_{ 3 }+{ y }_{ 6 }=\\quad 0\\\\ \\therefore \\quad { y }_{ 2 }=-s-t\\\\ { y }_{ 4 }-{ y }_{ 6 }={ y }_{ 4 }-s=0\\\\ \\therefore \\quad { y }_{ 4 }=s\\\\ { y }_{ 5 }-{ y }_{ 6 }={ y }_{ 5 }-s=0\\\\ \\therefore \\quad { y }_{ 5 }=s\\\\ \\begin{bmatrix} { y }_{ 1 } \\\\ { y }_{ 2 } \\\\ { y }_{ 3 } \\\\ { y }_{ 4 } \\\\ { y }_{ 5 } \\\\ { y }_{ 6 } \\end{bmatrix}=\\begin{bmatrix} -t \\\\ -s-t \\\\ t \\\\ s \\\\ s \\\\ s \\end{bmatrix}=\\begin{bmatrix} 0 \\\\ -s \\\\ 0 \\\\ s \\\\ s \\\\ s \\end{bmatrix}+\\begin{bmatrix} -t \\\\ -t \\\\ t \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}=s\\begin{bmatrix} 0 \\\\ -1 \\\\ 0 \\\\ 1 \\\\ 1 \\\\ 1 \\end{bmatrix}+t\\begin{bmatrix} -1 \\\\ -1 \\\\ 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix} $$\n\n\n```python\nA.transpose() * A\n```\n\n\n\n\n$$\\left[\\begin{matrix}2 & -1 & -1 & 0 & 0\\\\-1 & 3 & -1 & -1 & 0\\\\-1 & -1 & 3 & 0 & -1\\\\0 & -1 & 0 & 2 & -1\\\\0 & 0 & -1 & -1 & 2\\end{matrix}\\right]$$\n\n\n\n\n```python\n(A.transpose() * A).trace()\n```\n\n\n\n\n$$12$$\n\n\n\n* The degree of the node is the number of edges it has\n* Look at the columns of the incidence matrix A\n* Every non-trivial (non-zero) entry represents an edge\n* Note that there are 2 in column 1\n * This gives us a degree of 2, which will also be the first entry on the diagonal of ATA\n* Column 2 has 3 entries representing 3 edges from node 2 and an entry of 3 on the diagonal of ATA\n* ... and so on\n* The trace is therefor just the sum of the degree of all the nodes\n\n\n```python\n\n```\n", "meta": {"hexsha": "833a9af1b4f52b8af3508773588c677198c7636c", "size": 50358, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/I_13_Graphs_Incidence_matrices_Kirchhoff_laws.ipynb", "max_stars_repo_name": "solomonxie/jupyter-notebooks", "max_stars_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-02-13T05:52:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T09:52:35.000Z", "max_issues_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/I_13_Graphs_Incidence_matrices_Kirchhoff_laws.ipynb", "max_issues_repo_name": "solomonxie/jupyter-notebooks", "max_issues_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forks/MIT_OCW_Linear_Algebra_18_06-master/I_13_Graphs_Incidence_matrices_Kirchhoff_laws.ipynb", "max_forks_repo_name": "solomonxie/jupyter-notebooks", "max_forks_repo_head_hexsha": "65999f179e037242138de72f512dda4bf00c7379", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2027318476, "max_line_length": 862, "alphanum_fraction": 0.5740696612, "converted": true, "num_tokens": 5357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.15004215078862346}}