{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-1 fw=all -->\n",
    "\n",
    "# Random Variables\n",
    "\n",
    "In that section we worked with *discrete* random variables, those taking\n",
    "values in a finite set or the integers, where a probability *mass* sits on each\n",
    "outcome and we sum to get probabilities. Deep learning lives mostly in the\n",
    "*continuous* world: a pixel intensity, a network weight, a Gaussian noise sample\n",
    "all range over a continuum, and there a single outcome carries zero probability.\n",
    "The fix is the *density*, met already in that section:\n",
    "probability becomes *area under a curve*, so the natural operation is no longer\n",
    "summation but integration. This section builds the continuous theory we actually\n",
    "use: densities and their cumulative functions, the summary statistics (mean,\n",
    "variance, standard deviation) that compress a distribution to a few numbers, and\n",
    "the joint/marginal/covariance machinery for several correlated variables. At\n",
    "every step the discrete sum and the continuous integral are *the same idea* seen\n",
    "through that section, and almost everything below\n",
    "integrates the small identity the equation: *probability of a tiny\n",
    "interval $\\approx$ its width times the density there.*"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "random-variables-imports"
   },
   "source": [
    "%matplotlib inline\n",
    "from d2l import torch as d2l\n",
    "import torch\n",
    "import numpy as np"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-2 fw=all -->\n",
    "\n",
    "## From Discrete to Continuous Probability\n",
    "\n",
    "Continuous random variables are subtler than discrete ones, and the technical\n",
    "jump is exactly the jump from *summing a list* to *integrating a function*. We\n",
    "develop the theory in three steps: the density that replaces the mass function,\n",
    "the cumulative function that turns it back into a genuine probability, and the\n",
    "derivative relationship between them, which is the fundamental theorem of\n",
    "calculus restated for probabilities.\n",
    "\n",
    "### The Density Appears: A Thought Experiment\n",
    "\n",
    "Throw a dart at a board and ask for the probability it lands *exactly*\n",
    "$2\\,\\textrm{cm}$ from the center. Measure to one digit, with bins for\n",
    "$0,1,2,\\ldots\\,\\textrm{cm}$: of $100$ throws, perhaps $20$ land in the\n",
    "\"$2\\,\\textrm{cm}$\" bin, suggesting $20\\%$. But that bin holds everything between\n",
    "$1.5$ and $2.5\\,\\textrm{cm}$, not what we asked. Measure finer, to bins of\n",
    "$0.1\\,\\textrm{cm}$: now perhaps $3$ throws land in $[1.95,2.05]$, suggesting\n",
    "$3\\%$. We have only pushed the problem one digit down.\n",
    "\n",
    "Abstract it. Knowing the first $k$ digits match $2.000\\ldots$, the\n",
    "$(k{+}1)$-th digit is essentially a uniform draw from $\\{0,\\ldots,9\\}$: no\n",
    "physical mechanism makes the micrometer count prefer a $7$ to a $3$. So each\n",
    "extra digit of accuracy shrinks the probability by a factor of $10$:\n",
    "\n",
    "$$\n",
    "P(\\textrm{distance is}\\; 2.00\\ldots \\;\\textrm{to}\\; k \\;\\textrm{digits}) \\approx p\\cdot 10^{-k}.\n",
    "$$\n",
    "\n",
    "Knowing $k$ digits pins the value to an interval of width $10^{-k}$. Writing\n",
    "$\\epsilon$ for that width, the statement becomes $P(X\\text{ in an interval of\n",
    "width }\\epsilon\\text{ around }2)\\approx \\epsilon\\cdot p$. Nothing privileged the point $2$: a good\n",
    "dart thrower is likelier to land near the center, so the constant depends on\n",
    "*where* we look. Calling it $p(x)$,\n",
    "\n",
    "$$P(X \\;\\textrm{is in an}\\; \\epsilon \\textrm{-sized interval around}\\; x ) \\approx \\epsilon \\cdot p(x).$$\n",
    "\n",
    "This *is* the *probability density function* (p.d.f.): a function $p(x)$ encoding\n",
    "the relative likelihood of landing near $x$ versus elsewhere. It is the exact\n",
    "object introduced as a normalized non-negative function in\n",
    "the equation; here we see *where it comes from*.\n",
    "\n",
    "One consequence is immediate, and it is where continuous probability first\n",
    "feels strange. Shrinking the interval to a single point\n",
    "($\\epsilon\\to 0$) sends the right-hand side of the equation to zero,\n",
    "so for *any* fixed value $x$,\n",
    "\n",
    "$$P(X = x) = 0.$$\n",
    "\n",
    "This resolves the dartboard paradox: the probability of landing *exactly*\n",
    "$2\\,\\textrm{cm}$ out is zero, even though the dart certainly lands *somewhere*.\n",
    "The size notion at work here deserves a name. A set has *measure zero* when,\n",
    "for every $\\varepsilon>0$, it can be covered by a countable collection of\n",
    "intervals of total length at most $\\varepsilon$: a single point fits inside one\n",
    "interval of length $\\varepsilon$, and a countable set $\\{x_1,x_2,\\ldots\\}$ fits\n",
    "inside intervals of lengths $\\varepsilon/2,\\varepsilon/4,\\ldots$, which sum to\n",
    "$\\varepsilon$. For a variable with a density, every measure-zero set carries\n",
    "zero probability: covering the set by intervals of total length $\\delta$ caps\n",
    "its probability at the integral of $p$ over those intervals, which shrinks to\n",
    "zero with $\\delta$ (immediately when $p$ is bounded, and with a little more\n",
    "care in general). A point carrying *positive* mass is called an *atom*, so a\n",
    "variable with a density has no atoms; sets of positive length, by contrast, can\n",
    "carry positive probability, and we read those probabilities off the density by\n",
    "integrating.\n",
    "\n",
    "### Densities and Their Two Defining Properties\n",
    "\n",
    "What must $p(x)$ satisfy to be a density? Two things, both from\n",
    "the equation. First, probabilities are never negative, so $p(x)\\ge 0$.\n",
    "Second, slice $\\mathbb{R}$ into width-$\\epsilon$ pieces $(\\epsilon i,\n",
    "\\epsilon(i{+}1)]$; by the equation each contributes about $\\epsilon\\,\n",
    "p(\\epsilon i)$ to the total probability, and summing,\n",
    "\n",
    "$$\n",
    "P(X\\in\\mathbb{R}) \\approx \\sum_i \\epsilon \\cdot p(\\epsilon\\cdot i)\n",
    "\\;\\xrightarrow[\\epsilon\\to0]{}\\; \\int_{-\\infty}^{\\infty} p(x)\\,dx .\n",
    "$$\n",
    "\n",
    "The middle expression is exactly the Riemann sum of that section.\n",
    "Since $X$ must take *some* value, $P(X\\in\\mathbb{R})=1$, and we recover the\n",
    "normalization $\\int_{-\\infty}^{\\infty} p(x)\\,dx = 1$ of the equation.\n",
    "The same slicing argument over a finite range gives the rule we actually use:\n",
    "*probability is area under the density*,\n",
    "\n",
    "$$P(X\\in(a, b]) = \\int_{a}^{b} p(x)\\,dx.$$\n",
    "\n",
    "These two properties, non-negativity and total area $1$, describe *exactly* the\n",
    "space of densities. the figure shows the picture: the total\n",
    "shaded region has area $1$, and the probability of an interval is the area above\n",
    "it.\n",
    "\n",
    "![A probability density $p(x)$. The total area under the curve is $1$; the probability that $X$ lands in the interval from $a$ to $b$ is the area of the shaded slab above it, $\\int_a^b p(x)\\,dx$. The density itself is not a probability (it may exceed $1$); only its integral over an interval is.](../img/mdl-prob-pdf-area.svg)\n",
    "\n",
    "We can confirm the equation numerically. Take the two-bump density\n",
    "$p(x)=0.2\\,\\mathcal N(x;3,1)+0.8\\,\\mathcal N(x;-1,1)$ and recover the probability\n",
    "of an interval by a Riemann sum, the discrete approximation of the integral."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "random-variables-density-to-probability"
   },
   "source": [
    "import numpy as onp\n",
    "# Recover P(-2 < X <= 3) from the density by a Riemann sum (numerical integral)\n",
    "epsilon = 0.01\n",
    "x = onp.arange(-8, 8, epsilon)\n",
    "p = 0.2*onp.exp(-(x - 3)**2 / 2)/onp.sqrt(2 * onp.pi) + \\\n",
    "    0.8*onp.exp(-(x + 1)**2 / 2)/onp.sqrt(2 * onp.pi)\n",
    "print(f'total mass     : {float(onp.sum(epsilon * p)):.4f}')\n",
    "mask = (x > -2) & (x <= 3)\n",
    "print(f'P(-2 < X <= 3) : {float(onp.sum(epsilon * p[mask])):.4f}')"
   ],
   "execution_count": 2,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "total mass     : 1.0000\nP(-2 < X <= 3) : 0.7725\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-3 fw=all -->\n",
    "\n",
    "The total mass prints as $1.0000$, just as the equation demands\n",
    "(the grid spans $[-8,8]$, wide enough that the truncated Gaussian tails hold\n",
    "mass under $10^{-7}$), and the interval integral returns a genuine probability\n",
    "in $[0,1]$: the printed $0.7725$ sits within $6\\times10^{-4}$ of the exact value\n",
    "$0.7731$, the small bias of a left-endpoint Riemann sum at $\\epsilon=0.01$. A\n",
    "catalogue of named densities (Gaussian, exponential, and the rest) waits in\n",
    "that section; here we stay abstract.\n",
    "\n",
    "### The Cumulative Distribution Function\n",
    "\n",
    "A density has one awkward feature: its *values* are not probabilities. A density\n",
    "can exceed $10$, as long as it does so only over an interval shorter than\n",
    "$1/10$. The remedy is the *cumulative distribution function* (c.d.f.), which by\n",
    "the equation accumulates the density up to $x$ and so *is* a\n",
    "probability:\n",
    "\n",
    "$$\n",
    "F(x) = \\int_{-\\infty}^{x} p(t)\\,dt = P(X \\le x).\n",
    "$$\n",
    "\n",
    "Read off its properties directly: $F(x)\\to 0$ as $x\\to-\\infty$ and $F(x)\\to 1$ as\n",
    "$x\\to+\\infty$ (the total mass is $1$); $F$ is non-decreasing, since the integrand\n",
    "$p\\ge 0$ only ever adds area; and since $X$ has a density, $F$ is an integral of\n",
    "it and hence continuous. The\n",
    "c.d.f. is also what lets discrete and continuous variables share one framework.\n",
    "For a discrete $X$ taking $0$ and $1$ with probability $\\tfrac12$ each,\n",
    "\n",
    "$$\n",
    "F(x) = \\begin{cases}\n",
    "0 & x < 0, \\\\\n",
    "\\tfrac12 & 0 \\le x < 1, \\\\\n",
    "1 & x \\ge 1,\n",
    "\\end{cases}\n",
    "$$\n",
    "\n",
    "a *staircase* that jumps by the mass at each atom. The same $F$ thus describes\n",
    "continuous variables, discrete ones, and mixtures (flip a coin: heads, report a\n",
    "die roll; tails, a dart distance).\n",
    "\n",
    "The density and the c.d.f. carry the same information, and the bridge between\n",
    "them is the fundamental theorem of calculus. Differentiating\n",
    "the equation recovers the density.\n",
    "\n",
    "**Proposition (density is the derivative of the c.d.f.).** *If $X$ has a\n",
    "continuous density $p$, then $F$ is differentiable and*\n",
    "\n",
    "$$\n",
    "F'(x) = p(x).\n",
    "$$\n",
    "\n",
    "**Proof.** By definition the equation, $F(x)=\\int_{-\\infty}^x p(t)\\,dt$\n",
    "is the area-so-far function of the integrand $p$. The fundamental theorem of\n",
    "calculus the equation says precisely that such an area function is\n",
    "differentiable with derivative equal to the integrand, $F'(x)=p(x)$, at every\n",
    "point where $p$ is continuous. $\\blacksquare$\n",
    "\n",
    "So $p=F'$ and $F=\\int p$ are two views of one object: the density is the\n",
    "*instantaneous rate* at which probability accumulates, and the c.d.f. is the\n",
    "*accumulated area*. the figure puts them side by side (the\n",
    "shaded area $\\int_a^b p$ on the left equals the vertical rise $F(b)-F(a)$ on the\n",
    "right), making the equation and the equation a single\n",
    "picture.\n",
    "\n",
    "![Left: a density $p$ with the area over the interval from $a$ to $b$ shaded. Right: the matching c.d.f. $F(x)=\\int_{-\\infty}^x p$, an increasing curve from $0$ to $1$; the rise $F(b)-F(a)$ equals the shaded area on the left. The density is the slope of the c.d.f. $\\left(F'=p\\right)$ and the c.d.f. is the accumulated area under the density.](../img/mdl-prob-pdf-cdf.svg)\n",
    "\n",
    "The inverse $F^{-1}$, which maps a probability level $q\\in(0,1)$ back to the\n",
    "value $x$ with $F(x)=q$, is called the *quantile function*; its values at\n",
    "$q=0.25,0.5,0.75$ are the quartiles, the middle one the median. The quantile\n",
    "function is also a *sampler*, by an argument short enough to give in full. The\n",
    "argument needs one ingredient: a variable $U$ *uniform on $[0,1]$*, the\n",
    "variable whose density is constant at $1$ there, so that $U$ assigns every\n",
    "subinterval of $[0,1]$ probability equal to its length\n",
    "(that section names this law $U(0,1)$).\n",
    "\n",
    "**Proposition (inverse-transform sampling).** *Let $F$ be a continuous, strictly\n",
    "increasing c.d.f. and let $U$ be uniform on $[0,1]$. Then $X=F^{-1}(U)$ has\n",
    "c.d.f. exactly $F$.*\n",
    "\n",
    "**Proof.** Because $F$ is increasing, the events $F^{-1}(U)\\le x$ and\n",
    "$U\\le F(x)$ are the same event, and the uniform assigns the latter probability\n",
    "$F(x)$, the length of the subinterval $[0,F(x)]$:\n",
    "\n",
    "$$\n",
    "P\\bigl(F^{-1}(U)\\le x\\bigr) = P\\bigl(U\\le F(x)\\bigr) = F(x). \\quad\\blacksquare\n",
    "$$\n",
    "\n",
    "the figure is the picture: feed the uniform level\n",
    "$U$ into the *vertical* axis of the c.d.f. and reflect it through the curve down\n",
    "to the horizontal axis. Because the curve is steep where the density is high, a\n",
    "uniformly spread set of levels lands its reflections densely exactly there: the\n",
    "c.d.f.'s slope, which is the density by the equation, does the\n",
    "shaping. This one-line proposition is how libraries turn raw uniform noise into\n",
    "samples from any one-dimensional distribution: generate $U$, look up\n",
    "$F^{-1}(U)$. We put it to work when we meet the named distributions in\n",
    "that section, where inverting the exponential's c.d.f. gives\n",
    "that distribution's standard sampler in closed form.\n",
    "\n",
    "![Inverse-transform sampling. Uniform levels $U$ on the vertical axis (left) reflect through the c.d.f. $F$ down to values $x=F^{-1}(U)$ on the horizontal axis. Where $F$ is steep, that is, where the density $p=F'$ is large, a uniform spread of levels is compressed into a dense cluster of samples, so the histogram of reflected points reproduces $p$.](../img/mdl-prob-inverse-transform.svg)\n",
    "\n",
    "Sampling is also how expectations are computed at scale: given independent\n",
    "draws $x_1,\\ldots,x_n$ of $X$, the *Monte Carlo* estimate\n",
    "$\\tfrac1n\\sum_{i=1}^n g(x_i)$ approximates $E[g(X)]$, and its variance is\n",
    "$\\textrm{Var}(g(X))/n$ (Exercise 6 carries out the computation), shrinking with\n",
    "every additional sample. The guarantee that the estimate converges to the\n",
    "expectation, the law of large numbers, is stated and proved in\n",
    "that section.\n",
    "\n",
    "## Summarizing a Distribution\n",
    "\n",
    "A full distribution is often more than we can interpret at a glance. *Summary\n",
    "statistics* compress it to a few numbers: the *mean* says where the variable\n",
    "sits, the *variance* and *standard deviation* say how far it spreads. Each is an\n",
    "expectation (a density-weighted average, the equation), and each\n",
    "obeys algebra that we prove once and reuse everywhere.\n",
    "\n",
    "### The Mean\n",
    "\n",
    "The *mean* (or *expectation*) is the average value, weighting each outcome by its\n",
    "probability. For a discrete $X$ taking $x_i$ with probability $p_i$,\n",
    "\n",
    "$$\\mu_X = E[X] = \\sum_i x_i p_i,$$\n",
    "\n",
    "and in the continuum the sum becomes the density-weighted integral\n",
    "the equation, $\\mu_X=\\int x\\,p(x)\\,dx$, by the same\n",
    "slice-and-refine argument that produced the normalization\n",
    "the equation. The same\n",
    "weighting averages any *function* of $X$: $E[g(X)]=\\sum_i g(x_i)\\,p_i$ in the\n",
    "discrete case, while the continuous form $\\int g(x)\\,p(x)\\,dx$ restates the\n",
    "second half of the equation. The rule is used so routinely\n",
    "without comment (we invoke it below every time we average $X^2$ or a\n",
    "squared deviation) that it is known as the *law of the unconscious\n",
    "statistician*; what is new here is only the name and the discrete form. The\n",
    "mean tells us, with some caution, where the variable tends to sit.\n",
    "\n",
    "A running example recurs through the whole section. Let $X$ take $a-2$ with\n",
    "probability $p$, $a+2$ with probability $p$, and $a$ with probability $1-2p$.\n",
    "Then\n",
    "\n",
    "$$\n",
    "\\mu_X = (a-2)p + a(1-2p) + (a+2)p = a,\n",
    "$$\n",
    "\n",
    "the center of symmetry, exactly as intuition demands.\n",
    "\n",
    "The two algebraic properties of the mean we lean on most are that it is\n",
    "*linear*: constants pull out and sums split. Both follow in one line from the\n",
    "definition.\n",
    "\n",
    "**Proposition (linearity of expectation).** *For random variables $X,Y$ and\n",
    "constants $a,b$,*\n",
    "\n",
    "$$\n",
    "E[aX+b]=a\\,E[X]+b,\n",
    "\\qquad\n",
    "E[X+Y]=E[X]+E[Y].\n",
    "$$\n",
    "\n",
    "**Proof.** Both are linearity of the sum (or integral) defining the expectation.\n",
    "For the scaling-and-shift, $E[aX+b]=\\sum_i(ax_i+b)p_i = a\\sum_i x_i p_i + b\\sum_i\n",
    "p_i = a\\,E[X]+b$, using $\\sum_i p_i=1$. For the sum, write the expectation over\n",
    "the *joint* distribution of $(X,Y)$, with $p_{ij}$ the probability of the pair\n",
    "$(x_i,y_j)$ (the discrete joint of that section; its continuous\n",
    "counterpart, the joint density, arrives later in this section), and split the\n",
    "inner sum: $E[X+Y]=\\sum_{i,j}\n",
    "(x_i+y_j)p_{ij} = \\sum_{i,j} x_i p_{ij} + \\sum_{i,j} y_j p_{ij} = E[X]+E[Y]$, the\n",
    "last step recognizing the marginals $\\sum_j p_{ij}=P(X=x_i)$. The continuous case\n",
    "replaces every sum by an integral verbatim. $\\blacksquare$\n",
    "\n",
    "The second identity needs *no independence assumption*: expectations of sums\n",
    "always add, however entangled $X$ and $Y$ are. Expected-loss calculations\n",
    "throughout the book rest on this.\n",
    "\n",
    "The mean alone is not enough. A profit of $\\$10\\pm\\$1$ per sale and one of\n",
    "$\\$10\\pm\\$15$ share a mean but carry wildly different risk. We need a measure of\n",
    "*spread*.\n",
    "\n",
    "### Variance and Standard Deviation\n",
    "\n",
    "The *variance* measures how far $X$ strays from its mean. The deviation\n",
    "$X-\\mu_X$ is positive or negative, so we square it before averaging:\n",
    "\n",
    "$$\\sigma_X^2 = \\textrm{Var}(X) = E\\bigl[(X-\\mu_X)^2\\bigr].$$\n",
    "\n",
    "Expanding the square gives a formula that is almost always easier to compute\n",
    "with, and it deserves a proof since we use it constantly.\n",
    "\n",
    "**Proposition (computational form of the variance).**\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(X) = E[X^2] - E[X]^2 = E[X^2]-\\mu_X^2.\n",
    "$$\n",
    "\n",
    "**Proof.** Expand the square inside the equation and apply linearity\n",
    "the equation, treating $\\mu_X$ as the constant it is:\n",
    "\n",
    "$$\n",
    "E\\bigl[(X-\\mu_X)^2\\bigr]\n",
    " = E\\bigl[X^2 - 2\\mu_X X + \\mu_X^2\\bigr]\n",
    " = E[X^2] - 2\\mu_X\\,E[X] + \\mu_X^2\n",
    " = E[X^2] - \\mu_X^2,\n",
    "$$\n",
    "\n",
    "since $E[X]=\\mu_X$, so $-2\\mu_X E[X]+\\mu_X^2 = -2\\mu_X^2+\\mu_X^2=-\\mu_X^2$. $\\blacksquare$\n",
    "\n",
    "On the running example $\\mu_X=a$, and the computational form does the rest:\n",
    "$E[X^2]=(a-2)^2p+a^2(1-2p)+(a+2)^2p = a^2+8p$, so\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(X) = E[X^2]-\\mu_X^2 = (a^2+8p)-a^2 = 8p.\n",
    "$$\n",
    "\n",
    "This is sensible: at the largest allowed $p=\\tfrac12$ the variable is a coin flip\n",
    "between $a\\pm2$, each $2$ away from the mean, giving variance $8\\cdot\\tfrac12=4=2^2$;\n",
    "at $p=0$ it is constant at $a$ with no variance at all.\n",
    "\n",
    "How does variance behave under the affine maps we constantly apply (rescaling\n",
    "units, centering data)? The shift drops out and the scale comes out squared.\n",
    "\n",
    "**Proposition (variance under affine maps).** *For constants $a,b$,*\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(aX+b) = a^2\\,\\textrm{Var}(X).\n",
    "$$\n",
    "\n",
    "**Proof.** By linearity the equation the mean maps as\n",
    "$\\mu_{aX+b}=a\\mu_X+b$, so the deviation is $(aX+b)-\\mu_{aX+b}=a(X-\\mu_X)$; the\n",
    "shift $b$ cancels. Squaring and taking the expectation,\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(aX+b) = E\\bigl[a^2(X-\\mu_X)^2\\bigr] = a^2\\,E\\bigl[(X-\\mu_X)^2\\bigr] = a^2\\,\\textrm{Var}(X). \\qquad\\blacksquare\n",
    "$$\n",
    "\n",
    "Two further facts round out the list: $\\textrm{Var}(X)\\ge 0$, with equality iff\n",
    "$X$ is constant (a square has non-negative mean, zero only when $X-\\mu_X\\equiv0$);\n",
    "and for *independent* $X,Y$, $\\textrm{Var}(X+Y)=\\textrm{Var}(X)+\\textrm{Var}(Y)$\n",
    "(we prove the general version, with a covariance correction, in\n",
    "that section).\n",
    "\n",
    "The variance has a units problem. If $X$ is in stars, $X-\\mu_X$ is in stars but\n",
    "$(X-\\mu_X)^2$ is in *squared stars*, so $\\textrm{Var}(X)$ is not comparable to\n",
    "the data. Taking the square root restores the original units and defines the\n",
    "*standard deviation*\n",
    "\n",
    "$$\n",
    "\\sigma_X = \\sqrt{\\textrm{Var}(X)}.\n",
    "$$\n",
    "\n",
    "Its properties echo the variance through the square root: $\\sigma_X\\ge0$;\n",
    "$\\sigma_{aX+b}=|a|\\sigma_X$ (the absolute value because $\\sqrt{a^2}=|a|$); and for\n",
    "independent $X,Y$, $\\sigma_{X+Y}=\\sqrt{\\sigma_X^2+\\sigma_Y^2}$. On the running\n",
    "example $\\sigma_X=2\\sqrt{2p}$, back in units of stars.\n",
    "\n",
    "### What the Standard Deviation Means: Markov and Chebyshev\n",
    "\n",
    "Does $\\sigma_X$ have a concrete reading? Yes: it sets the scale over which $X$\n",
    "fluctuates, and a pair of inequalities, each with a one-line proof, makes this\n",
    "rigorous for *any* distribution. The first, *Markov's inequality*, turns\n",
    "knowledge of a bare mean into a tail bound: a non-negative variable cannot put\n",
    "much mass far above its mean.\n",
    "\n",
    "**Proposition (Markov's inequality).** *If $X\\ge 0$ and $a>0$, then*\n",
    "\n",
    "$$\n",
    "P(X \\ge a) \\le \\frac{E[X]}{a}.\n",
    "$$\n",
    "\n",
    "**Proof.** Let $\\mathbf{1}_{X\\ge a}$ be the indicator variable that is $1$ when\n",
    "$X\\ge a$ and $0$ otherwise. Then $X \\ge a\\,\\mathbf{1}_{X\\ge a}$ *pointwise*: on\n",
    "the event $\\{X\\ge a\\}$ the right-hand side is $a\\le X$, and elsewhere it is\n",
    "$0\\le X$. Taking expectations of both sides and using\n",
    "$E[\\mathbf{1}_{X\\ge a}]=P(X\\ge a)$ gives $E[X]\\ge a\\,P(X\\ge a)$. $\\blacksquare$\n",
    "\n",
    "So at most a tenth of any non-negative population exceeds ten times its\n",
    "average: true of incomes, file sizes, and gradient norms alike, with no\n",
    "distributional assumption whatsoever. On its own the bound is crude, because it\n",
    "knows only the mean. Feeding it the *squared deviation* $(X-\\mu_X)^2$, whose\n",
    "mean is by definition the variance, sharpens it into the statement we are\n",
    "after, an inequality due to Bienaymé and to Chebyshev [@Chebyshev.1867].\n",
    "\n",
    "**Proposition (Chebyshev's inequality).** *For any $X$ with finite variance and\n",
    "any $\\alpha>0$,*\n",
    "\n",
    "$$P\\bigl(|X - \\mu_X| \\ge \\alpha\\sigma_X\\bigr) \\le \\frac{1}{\\alpha^2}.$$\n",
    "\n",
    "**Proof.** The variable $Z=(X-\\mu_X)^2$ is non-negative with\n",
    "$E[Z]=\\textrm{Var}(X)=\\sigma_X^2$ by the equation, and the event\n",
    "$\\{|X-\\mu_X|\\ge\\alpha\\sigma_X\\}$ is exactly the event\n",
    "$\\{Z\\ge\\alpha^2\\sigma_X^2\\}$. Markov's inequality the equation with\n",
    "$a=\\alpha^2\\sigma_X^2$ gives\n",
    "$P(|X-\\mu_X|\\ge\\alpha\\sigma_X) \\le \\sigma_X^2/(\\alpha^2\\sigma_X^2) = 1/\\alpha^2$. $\\blacksquare$\n",
    "\n",
    "**Corollary ($\\varepsilon$-form).** *For any $X$ with finite variance and any\n",
    "$\\varepsilon>0$,*\n",
    "\n",
    "$$\n",
    "P\\bigl(|X-\\mu_X| \\ge \\varepsilon\\bigr) \\le \\frac{\\textrm{Var}(X)}{\\varepsilon^2}.\n",
    "$$\n",
    "\n",
    "Setting $\\varepsilon=\\alpha\\sigma_X$ recovers the equation when\n",
    "$\\sigma_X>0$; applying Markov's inequality to $(X-\\mu_X)^2$ with\n",
    "$a=\\varepsilon^2$ proves the corollary directly and covers the edge case\n",
    "$\\sigma_X=0$, where $X$ equals its mean with probability one and the left-hand\n",
    "side is $0$. This is the form that section\n",
    "invoked for the concentration of random angles.\n",
    "\n",
    "In words at $\\alpha=10$: for *any* distribution at most $1\\%$ of the mass lies\n",
    "ten or more standard deviations from the mean; at least $99\\%$ lies strictly\n",
    "within. The standard deviation is thus a universal yardstick for \"how far is\n",
    "far.\"\n",
    "\n",
    "The bound is *sharp*, and our running example shows exactly why no tighter\n",
    "constant is possible. With $\\mu_X=a$ and $\\sigma_X=2\\sqrt{2p}$, Chebyshev at\n",
    "$\\alpha=2$ promises $P\\bigl(|X-a|\\ge 4\\sqrt{2p}\\bigr)\\le\\tfrac14$: at most a\n",
    "quarter of the mass sits $4\\sqrt{2p}$ or farther from the mean. The two outlying\n",
    "atoms $a\\pm2$ sit at distance exactly $2$, and as $p$ shrinks the threshold\n",
    "$4\\sqrt{2p}$ shrinks with it. the figure shows the three\n",
    "regimes. For $p>\\tfrac18$ the threshold exceeds $2$, no atom lies that far out,\n",
    "and the left-hand side is $0$: the bound holds with room to spare. At\n",
    "$p=\\tfrac18$ the threshold equals $2$ exactly (then $\\sigma_X=1$, so $a\\pm2$ are\n",
    "precisely two standard deviations from the mean): both outlying atoms count\n",
    "toward the event, the probability is $p+p=\\tfrac14$, and the bound is attained\n",
    "with *equality*, so no constant smaller than $1/\\alpha^2$ could work for every\n",
    "distribution. For $p<\\tfrac18$ the threshold drops below $2$, both atoms lie\n",
    "beyond it, and their combined mass $2p<\\tfrac14$ keeps the inequality satisfied.\n",
    "\n",
    "![Chebyshev's bound on the running three-atom example: masses drawn as vertical bars at $a-2,a,a+2$ with the threshold distance $\\alpha\\sigma_X=4\\sqrt{2p}$ for $\\alpha=2$ marked as a horizontal bracket about the mean $a$. The three panels show the regimes $p>1/8$, $p=1/8$ (where the bound is attained with equality), and $p<1/8$ that the text walks through.](../img/mdl-prob-chebyshev.svg)\n",
    "\n",
    "### Means and Variances in the Continuum\n",
    "\n",
    "Everything above transfers to continuous variables by the now-familiar move:\n",
    "slice $\\mathbb{R}$ into width-$\\epsilon$ pieces, apply the discrete definition,\n",
    "and let $\\epsilon\\to0$ to turn the sum into an integral. The mean is the\n",
    "density-weighted average the equation, and the variance follows\n",
    "from its computational form the equation:\n",
    "\n",
    "$$\n",
    "\\mu_X = \\int_{-\\infty}^\\infty x\\,p_X(x)\\,dx,\n",
    "\\qquad\n",
    "\\sigma^2_X = \\int_{-\\infty}^\\infty x^2 p_X(x)\\,dx - \\mu_X^2 .\n",
    "$$\n",
    "\n",
    "Every property proved above (linearity, the affine rule, Markov and\n",
    "Chebyshev) carries over unchanged, since each rested only on linearity and\n",
    "positivity of the averaging operation.\n",
    "For the uniform density $U(0,1)$ met at inverse-transform sampling ($p(x)=1$ on\n",
    "$[0,1]$, zero elsewhere),\n",
    "$\\mu_X=\\int_0^1 x\\,dx=\\tfrac12$ and $\\sigma_X^2=\\int_0^1\n",
    "x^2\\,dx-\\tfrac14=\\tfrac13-\\tfrac14=\\tfrac1{12}$, both elementary integrals.\n",
    "\n",
    "A cautionary example: the *Cauchy distribution* $p(x)=\\frac{1}{\\pi(1+x^2)}$ is a\n",
    "perfectly good density (a table of integrals confirms it integrates to $1$), yet\n",
    "it has *neither* a finite variance *nor* a well-defined mean. The variance\n",
    "integral $\\int x^2 p(x)\\,dx$ diverges because $\\frac{x^2}{1+x^2}\\to1$, so the\n",
    "integrand has infinite area. The mean is worse: although the integrand\n",
    "$\\frac{x}{\\pi(1+x^2)}$ is *odd* and tempts us to declare $0$ by symmetry, the mean\n",
    "is defined only when $\\int|x|p(x)\\,dx<\\infty$. Substituting $u=1+x^2$,\n",
    "$\\int_0^\\infty \\frac{x}{\\pi(1+x^2)}\\,dx=\\frac{1}{2\\pi}\\int_1^\\infty\n",
    "\\frac{du}{u}=+\\infty$, and the left tail gives $-\\infty$, so the mean is a\n",
    "meaningless $\\infty-\\infty$ whose value depends on how the limits are taken, a\n",
    "*stronger* failure than \"the mean is infinite.\" We can watch both integrals\n",
    "diverge numerically by extending the integration range and seeing the partial\n",
    "sums refuse to settle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "random-variables-cauchy-diverges"
   },
   "source": [
    "import numpy as onp\n",
    "# Cauchy second moment integral over growing ranges: it should NOT converge\n",
    "for R in [10, 100, 1000]:\n",
    "    x = onp.arange(-R, R, 0.01)\n",
    "    integrand = x**2 / (onp.pi * (1 + x**2))\n",
    "    print(f'integral_-{R}^{R} x^2 p(x) dx = {float(onp.sum(0.01*integrand)):.3f}')"
   ],
   "execution_count": 3,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "integral_-10^10 x^2 p(x) dx = 5.430\nintegral_-100^100 x^2 p(x) dx = 62.668\nintegral_-1000^1000 x^2 p(x) dx = 635.620\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-4 fw=all -->\n",
    "\n",
    "The \"integral\" grows without bound as the range widens: it does not converge, so\n",
    "the variance is infinite. Distributions whose tails are fat enough that moments\n",
    "diverge are called *heavy-tailed*, and they are endemic inside machine learning:\n",
    "gradient-noise spectra, token frequencies, and the spectra of trained weight\n",
    "matrices all show heavy tails. that section\n",
    "classifies tails by how fast averages over them concentrate.\n",
    "\n",
    "## Several Variables\n",
    "\n",
    "Machine learning rarely involves one variable in isolation. Pixels $R_{i,j}$ in\n",
    "an image, prices $P_t$ across time: nearby coordinates are correlated, and a\n",
    "model that ignores this under-performs (that section analyzes\n",
    "exactly such a model). We need a language for *several*, possibly correlated,\n",
    "continuous variables, and the multiple integrals of that section\n",
    "supply it.\n",
    "\n",
    "### Joint and Marginal Densities\n",
    "\n",
    "For two variables $X,Y$, the same $\\epsilon$-interval reasoning gives a *joint\n",
    "density* $p(x,y)$ with\n",
    "\n",
    "$$\n",
    "P(X\\approx x \\text{ and } Y\\approx y \\text{ in } \\epsilon\\text{-boxes}) \\approx \\epsilon^{2}\\,p(x, y),\n",
    "$$\n",
    "\n",
    "and the one-variable properties carry over: $p(x,y)\\ge0$, $\\int_{\\mathbb{R}^2}\n",
    "p(x,y)\\,dx\\,dy=1$, and $P((X,Y)\\in\\mathcal{D})=\\int_{\\mathcal{D}} p(x,y)\\,dx\\,dy$.\n",
    "For $n$ variables the joint density $p(\\mathbf x)=p(x_1,\\ldots,x_n)$ obeys the\n",
    "same non-negativity and unit-integral rules.\n",
    "\n",
    "Often we hold a joint density but want the distribution of *one* coordinate,\n",
    "ignoring the rest: its *marginal distribution*. Starting from\n",
    "$P(X\\in[x,x+\\epsilon])\\approx\\epsilon\\,p_X(x)$ and noting $Y$ takes *some* value,\n",
    "we slice in $y$ as well:\n",
    "\n",
    "$$\n",
    "\\epsilon\\,p_X(x) \\approx \\sum_i P\\bigl(X\\in[x,x{+}\\epsilon],\\ Y\\in[\\epsilon i,\\epsilon(i{+}1)]\\bigr)\n",
    "                 \\approx \\sum_i \\epsilon^{2}\\,p_{X,Y}(x,\\epsilon i).\n",
    "$$\n",
    "\n",
    "Geometrically this integrates the joint density up a vertical strip at $x$, as in\n",
    "the figure. Cancelling one $\\epsilon$ and recognizing the\n",
    "remaining sum as an integral over $y$,\n",
    "\n",
    "$$\n",
    "p_X(x) = \\int_{-\\infty}^\\infty p_{X, Y}(x, y)\\,dy.\n",
    "$$\n",
    "\n",
    "![A continuous joint density $p_{X,Y}(x,y)$ shown by its contours, with one vertical strip at $x$ highlighted. Integrating the joint density up that strip, over all $y$, gives the height of the marginal density $p_X(x)$ plotted along the $\\mathit{x}$-axis below. Sweeping the strip across $x$ traces out the whole marginal.](../img/mdl-prob-marginal.svg)\n",
    "\n",
    "To marginalize, then, we *integrate out* the variables we do not care about, the\n",
    "same operation introduced in that section, here given its\n",
    "probabilistic meaning.\n",
    "\n",
    "### Conditional Densities and Independence\n",
    "\n",
    "With the joint and the marginal in hand, the last piece is *conditioning*: how the\n",
    "density of $X$ should update once we learn that $Y=y$. The discrete rule\n",
    "$P(X\\mid Y)=P(X,Y)/P(Y)$ carries over verbatim to densities. We define the\n",
    "**conditional density**\n",
    "\n",
    "$$\n",
    "p_{X\\mid Y}(x\\mid y) = \\frac{p_{X,Y}(x,y)}{p_Y(y)}, \\qquad p_Y(y) > 0.\n",
    "$$\n",
    "\n",
    "For each fixed $y$ this is a genuine density in $x$: it is non-negative, and\n",
    "dividing the joint by exactly $p_Y(y)=\\int p_{X,Y}(x,y)\\,dx$ is precisely what makes\n",
    "it integrate to one. Geometrically it is a horizontal slice of the joint surface\n",
    "at height $y$, renormalized to unit area, as the figure\n",
    "shows: cut the joint density along $y=y_0$, then rescale that profile so its area\n",
    "is one. Rearranging the equation\n",
    "gives the **chain rule** $p_{X,Y}(x,y)=p_{X\\mid Y}(x\\mid y)\\,p_Y(y)$, and writing it\n",
    "both ways ($p_{X,Y}=p_{X\\mid Y}\\,p_Y=p_{Y\\mid X}\\,p_X$) and equating yields **Bayes'\n",
    "rule for densities**,\n",
    "\n",
    "$$\n",
    "p_{X\\mid Y}(x\\mid y) = \\frac{p_{Y\\mid X}(y\\mid x)\\,p_X(x)}{p_Y(y)},\n",
    "$$\n",
    "\n",
    "the engine of every Bayesian update in this book.\n",
    "\n",
    "The sharpest special case is when learning $Y$ tells us *nothing* about $X$.\n",
    "\n",
    "**Proposition (independence).** *The following are equivalent: (i) the joint\n",
    "factorizes, $p_{X,Y}(x,y)=p_X(x)\\,p_Y(y)$ for all $x,y$; (ii) the conditional equals\n",
    "the marginal, $p_{X\\mid Y}(x\\mid y)=p_X(x)$ whenever $p_Y(y)>0$. When either holds we\n",
    "call $X$ and $Y$ independent, $X\\perp Y$.*\n",
    "\n",
    "**Proof.** If (i) holds, then $p_{X\\mid Y}(x\\mid y)=p_X(x)p_Y(y)/p_Y(y)=p_X(x)$, which\n",
    "is (ii). Conversely, if (ii) holds, multiply by $p_Y(y)$ and use the chain rule:\n",
    "$p_{X,Y}(x,y)=p_{X\\mid Y}(x\\mid y)\\,p_Y(y)=p_X(x)\\,p_Y(y)$, which is (i). $\\blacksquare$\n",
    "\n",
    "As a worked example, take the joint $p_{X,Y}(x,y)=4xy$ on the unit square\n",
    "$[0,1]^2$ (it integrates to one). The marginal is $p_Y(y)=\\int_0^1 4xy\\,dx=2y$, so\n",
    "$p_{X\\mid Y}(x\\mid y)=4xy/2y=2x$, *independent of $y$*. The conditional never\n",
    "changes as $y$ varies, so by the proposition $X\\perp Y$. This is exactly the\n",
    "visual test of the figure: independence is the case where\n",
    "the renormalized slice $p(x\\mid y_0)$ has the *same shape* at every height $y_0$,\n",
    "since the joint factors and the $y$-factor cancels in the renormalization. A joint\n",
    "that does not factor this way (say one supported on the triangle $x\\le y$) has\n",
    "a conditional whose support and shape shift with $y$, the signature of dependence.\n",
    "\n",
    "![Reading off a conditional density. Left: the contours of a joint density $p_{X,Y}(x,y)$ with one horizontal slice at $y=y_0$ highlighted. Right: that slice, $x\\mapsto p_{X,Y}(x,y_0)$, renormalized to unit area to give the conditional density $p(x\\mid y_0)$ of the equation. When the joint factors, every slice has the same shape after renormalization, regardless of $y_0$, which is precisely independence; when it does not, the slice shape drifts with $y_0$.](../img/mdl-prob-conditional-slice.svg)\n",
    "\n",
    "Independence is a strong, all-of-the-distribution statement. It is strictly\n",
    "stronger than being *uncorrelated* (zero covariance), which constrains only the\n",
    "linear relationship; we make the gap precise in the covariance subsection below.\n",
    "This factorized structure is also exactly what the naive Bayes classifier of\n",
    "that section assumes across features to make high-dimensional\n",
    "densities tractable.\n",
    "\n",
    "### Conditional Expectation and the Tower Property\n",
    "\n",
    "The conditional density invites a conditional version of the mean. Averaging $X$\n",
    "against the slice $p_{X\\mid Y}(x\\mid y)$ rather than its own marginal gives the\n",
    "**conditional expectation**\n",
    "\n",
    "$$\n",
    "E[X\\mid Y{=}y] = \\int x\\,p_{X\\mid Y}(x\\mid y)\\,dx,\n",
    "$$\n",
    "\n",
    "the average value of $X$ *once $Y$ is known to be $y$*. As $y$ ranges it traces a\n",
    "function of $y$; feeding in the random $Y$ makes $E[X\\mid Y]$ itself a random\n",
    "variable, a function of $Y$ alone. The variance gets a conditional version the\n",
    "same way: $\\textrm{Var}(X\\mid Y)=E[X^2\\mid Y]-E[X\\mid Y]^2$, the computational\n",
    "form the equation applied within each slice. Two identities then say\n",
    "that conditioning can\n",
    "only *reorganize* the mean and spread of $X$, never conjure or destroy them.\n",
    "\n",
    "**Proposition (laws of total expectation and variance).** *Let $X,Y$ be jointly\n",
    "continuous with finite variance (for discrete pairs, the same identities hold\n",
    "with every integral replaced by a sum). Then*\n",
    "\n",
    "$$\n",
    "E[X] = E\\bigl[E[X\\mid Y]\\bigr],\n",
    "\\qquad\n",
    "\\textrm{Var}(X) = E\\bigl[\\textrm{Var}(X\\mid Y)\\bigr] + \\textrm{Var}\\bigl(E[X\\mid Y]\\bigr).\n",
    "$$\n",
    "\n",
    "**Proof.** For the first (the **tower property**), expand the inner expectation\n",
    "and use the chain rule $p_{X\\mid Y}(x\\mid y)\\,p_Y(y)=p_{X,Y}(x,y)$ to recombine\n",
    "the slices into the joint, then integrate out $y$ via the equation:\n",
    "\n",
    "$$\n",
    "E\\bigl[E[X\\mid Y]\\bigr]\n",
    " = \\int\\!\\Bigl(\\int x\\,p_{X\\mid Y}(x\\mid y)\\,dx\\Bigr)p_Y(y)\\,dy\n",
    " = \\iint x\\,p_{X,Y}(x,y)\\,dx\\,dy\n",
    " = E[X].\n",
    "$$\n",
    "\n",
    "The set where $p_Y(y)=0$, on which the conditional density\n",
    "the equation is undefined, contributes nothing to either\n",
    "integral: $Y$ lands in it with probability zero, and the joint density vanishes\n",
    "there as well (it integrates to $p_Y$ in $x$), so both sides ignore it.\n",
    "For the variance, apply the definition of $\\textrm{Var}(X\\mid Y)$ within\n",
    "each slice, take the\n",
    "expectation over $Y$, and add and subtract $E\\bigl[E[X\\mid Y]\\bigr]^2=E[X]^2$:\n",
    "\n",
    "$$\n",
    "E\\bigl[\\textrm{Var}(X\\mid Y)\\bigr] + \\textrm{Var}\\bigl(E[X\\mid Y]\\bigr)\n",
    " = \\Bigl(E[X^2] - E\\bigl[E[X\\mid Y]^2\\bigr]\\Bigr)\n",
    " + \\Bigl(E\\bigl[E[X\\mid Y]^2\\bigr] - E[X]^2\\Bigr)\n",
    " = E[X^2] - E[X]^2,\n",
    "$$\n",
    "\n",
    "which is $\\textrm{Var}(X)$, using the tower property on $E[X^2]$ and on\n",
    "$E[X\\mid Y]$. $\\blacksquare$\n",
    "\n",
    "The variance law (sometimes called **Eve's law**, after the E-V-V-E pattern of\n",
    "its right-hand side) has a memorable reading: the spread of $X$ splits\n",
    "into the *average spread within each $Y$-slice* plus the *spread of the\n",
    "slice-averages themselves*, unexplained variance plus explained variance. That\n",
    "decomposition underlies the *analysis of variance* (ANOVA), the classical\n",
    "method that attributes the variation in data to competing explanatory factors,\n",
    "and it reappears in latent-variable models, models that explain observed data\n",
    "through an unobserved cause (that section). We use the tower property\n",
    "the equation repeatedly when an expectation is easier one slice at a\n",
    "time, most heavily in the maximum-likelihood estimator of\n",
    "that section and the variational bounds of\n",
    "that section, where a hidden variable is integrated\n",
    "out one conditional slice at a time.\n",
    "\n",
    "### Covariance\n",
    "\n",
    "For a *single* extra summary statistic capturing how two variables move together,\n",
    "we use the *covariance*. For discrete $X,Y$ taking $(x_i,y_j)$ with probability\n",
    "$p_{ij}$,\n",
    "\n",
    "$$\\sigma_{XY} = \\textrm{Cov}(X, Y) = \\sum_{i, j} (x_i - \\mu_X)(y_j-\\mu_Y)\\,p_{ij} = E[XY] - E[X]E[Y],$$\n",
    "\n",
    "the second form being the exact two-variable analogue of the computational\n",
    "variance formula the equation (and indeed\n",
    "$\\textrm{Cov}(X,X)=\\textrm{Var}(X)$). The covariance is positive when $X$ and $Y$\n",
    "tend to be large together, negative when one is large as the other is small.\n",
    "\n",
    "An example makes this concrete. Let $X\\in\\{1,3\\}$ and $Y\\in\\{-1,3\\}$ with\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "P(X{=}1, Y{=}{-}1) &= \\tfrac{p}{2}, &\\quad P(X{=}1, Y{=}3) &= \\tfrac{1-p}{2}, \\\\\n",
    "P(X{=}3, Y{=}{-}1) &= \\tfrac{1-p}{2}, &\\quad P(X{=}3, Y{=}3) &= \\tfrac{p}{2},\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "for a parameter $p\\in[0,1]$. At $p=1$ the two are large or small *together*; at\n",
    "$p=0$ they are *opposed*; at $p=\\tfrac12$ all four cells are equally likely and\n",
    "the two are unrelated. With $\\mu_X=2$, $\\mu_Y=1$, the definition\n",
    "the equation gives, after summing the four terms,\n",
    "$\\textrm{Cov}(X,Y)=4p-2$: equal to $+2$ at $p=1$, $-2$ at $p=0$, and $0$ at\n",
    "$p=\\tfrac12$, matching every expectation.\n",
    "\n",
    "Covariance captures only *linear* co-variation. If $Y$ is uniform on\n",
    "$\\{-2,-1,0,1,2\\}$ and $X=Y^2$, then $X$ is a deterministic function of $Y$ yet\n",
    "$\\textrm{Cov}(X,Y)=0$, because the symmetric quadratic relationship has no linear\n",
    "trend. Zero covariance does *not* mean independent.\n",
    "\n",
    "The continuous version replaces the sum by the density-weighted integral,\n",
    "\n",
    "$$\n",
    "\\sigma_{XY} = \\int_{\\mathbb{R}^2} (x-\\mu_X)(y-\\mu_Y)\\,p(x, y)\\,dx\\,dy .\n",
    "$$\n",
    "\n",
    "the figure shows clouds of points whose covariance we tune\n",
    "from negative through zero to positive: the cloud tilts down, rounds out, then\n",
    "tilts up. Its bottom row replays the *identical* draws with $Y$ restated in\n",
    "cents instead of dollars: every sample covariance inflates by a factor of $100$\n",
    "while no cloud changes shape. Covariance carries the units of its arguments;\n",
    "only its sign is scale-free, a defect the correlation coefficient below will\n",
    "repair.\n",
    "\n",
    "![Top row: scatter clouds of $(X,Y)$ pairs with covariance tuned negative, zero, and positive (left to right), $Y$ in dollars: negative covariance tilts the cloud down-right, zero leaves it round, positive tilts it up-right. Bottom row: the identical draws with $Y$ restated in cents. Every sample covariance is multiplied by $100$ while each panel's correlation $\\rho$ (gray) is unchanged: the magnitude of covariance carries units, only its sign is scale-free.](../img/mdl-prob-covariance.svg)\n",
    "\n",
    "Two properties we use repeatedly: covariance is *linear in each argument*, with\n",
    "$\\textrm{Cov}(aX+b,Y)=a\\,\\textrm{Cov}(X,Y)$ and symmetrically\n",
    "$\\textrm{Cov}(X,cY+d)=c\\,\\textrm{Cov}(X,Y)$ (shifts drop out, scales pull\n",
    "through, in either slot); and independent variables have zero covariance, since\n",
    "then $E[XY]=E[X]E[Y]$ in the equation. Covariance also completes the\n",
    "variance-of-a-sum rule.\n",
    "\n",
    "**Proposition (variance of a sum).** *For any random variables $X,Y$,*\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(X+Y) = \\textrm{Var}(X) + \\textrm{Var}(Y) + 2\\,\\textrm{Cov}(X, Y).\n",
    "$$\n",
    "\n",
    "**Proof.** Write $\\bar X=X-\\mu_X$, $\\bar Y=Y-\\mu_Y$, so $X+Y$ has mean\n",
    "$\\mu_X+\\mu_Y$ by linearity the equation and deviation $\\bar X+\\bar Y$.\n",
    "Then by the equation and linearity,\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(X+Y) = E\\bigl[(\\bar X+\\bar Y)^2\\bigr]\n",
    " = E[\\bar X^2] + 2\\,E[\\bar X\\bar Y] + E[\\bar Y^2]\n",
    " = \\textrm{Var}(X) + 2\\,\\textrm{Cov}(X,Y) + \\textrm{Var}(Y),\n",
    "$$\n",
    "\n",
    "recognizing $E[\\bar X\\bar Y]=\\textrm{Cov}(X,Y)$ from the equation. $\\blacksquare$\n",
    "\n",
    "When $X$ and $Y$ are independent the cross term vanishes and we recover the\n",
    "additive rule $\\textrm{Var}(X+Y)=\\textrm{Var}(X)+\\textrm{Var}(Y)$ promised\n",
    "earlier.\n",
    "\n",
    "### Correlation\n",
    "\n",
    "Covariance inherits the *units* of $X$ times $Y$ (inches $\\times$ dollars), so\n",
    "its magnitude is hard to read. Switching $Y$ from dollars to cents multiplies it\n",
    "by $100$. To get a unit-free measure, divide by something that also scales by\n",
    "$100$: the standard deviations. The *correlation coefficient* is\n",
    "\n",
    "$$\\rho(X, Y) = \\frac{\\textrm{Cov}(X, Y)}{\\sigma_{X}\\sigma_{Y}}.$$\n",
    "\n",
    "The normalization is calibrated so that $\\rho$ never leaves $[-1,1]$, and the\n",
    "proof is the Cauchy--Schwarz argument of\n",
    "that section wearing probabilistic clothes.\n",
    "\n",
    "**Proposition (correlation bound).** *For any $X,Y$ with finite, nonzero\n",
    "variances, $-1\\le\\rho(X,Y)\\le 1$, with equality iff $Y=aX+b$ almost surely\n",
    "for constants $a\\ne0,b$ (a perfect linear relationship up to probability-zero\n",
    "events).*\n",
    "\n",
    "**Proof.** A variance is never negative, so $\\textrm{Var}(tX+Y)\\ge 0$ for every\n",
    "real $t$. Expanding it by the variance-of-a-sum rule the equation\n",
    "(with the affine rule the equation on the $tX$ term) gives a\n",
    "quadratic in $t$,\n",
    "\n",
    "$$\n",
    "\\textrm{Var}(tX+Y) = \\textrm{Var}(X)\\,t^2 + 2\\,\\textrm{Cov}(X,Y)\\,t + \\textrm{Var}(Y) \\;\\ge\\; 0\n",
    "\\quad\\textrm{for every } t.\n",
    "$$\n",
    "\n",
    "A quadratic with positive leading coefficient $\\textrm{Var}(X)$ that stays\n",
    "non-negative cannot have two distinct real roots, so its discriminant is $\\le 0$:\n",
    "\n",
    "$$\n",
    "\\bigl(2\\,\\textrm{Cov}(X,Y)\\bigr)^2 - 4\\,\\textrm{Var}(X)\\,\\textrm{Var}(Y)\\le 0,\n",
    "\\qquad\\textrm{i.e.}\\qquad\n",
    "\\textrm{Cov}(X,Y)^2 \\le \\textrm{Var}(X)\\,\\textrm{Var}(Y).\n",
    "$$\n",
    "\n",
    "Dividing by $\\sigma_X^2\\sigma_Y^2$ gives $\\rho^2\\le 1$, which is the claim.\n",
    "Equality forces the discriminant to vanish, so the quadratic has a (repeated)\n",
    "root $t^\\star$ with $\\textrm{Var}(t^\\star X+Y)=0$; a variable of zero variance is constant almost surely, so\n",
    "$t^\\star X+Y=c$ almost surely, i.e. $Y=-t^\\star X+c$ almost surely is affine in\n",
    "$X$.\n",
    "Conversely, suppose $Y=aX+b$; the nonzero-variance hypothesis forces $a\\neq0$,\n",
    "since $a=0$ would make $Y$ constant. Using\n",
    "$\\textrm{Cov}(X,aX+b)=a\\,\\textrm{Var}(X)$ (shifts drop out, scales pull\n",
    "through) and $\\sigma_{aX+b}=|a|\\sigma_X$,\n",
    "\n",
    "$$\n",
    "\\rho(X, aX+b) = \\frac{a\\,\\textrm{Var}(X)}{\\sigma_X\\cdot|a|\\,\\sigma_X} = \\frac{a}{|a|} = \\operatorname{sign}(a),\n",
    "$$\n",
    "\n",
    "so equality holds. $\\blacksquare$\n",
    "\n",
    "The two extremes thus read off: $\\rho=+1$ for a perfect increasing linear\n",
    "relationship ($a>0$) and $\\rho=-1$ for a perfect decreasing one ($a<0$),\n",
    "independent of the scale $|a|$: correlation\n",
    "measures direction and tightness of a linear relationship, never its slope.\n",
    "On the running discrete\n",
    "example $\\sigma_X=1$, $\\sigma_Y=2$, so\n",
    "$\\rho=\\frac{4p-2}{2}=2p-1$, sweeping from $-1$ to $+1$ as $p$ does from $0$\n",
    "to $1$.\n",
    "the figure shows clouds at correlation $-0.9$, $0$, and\n",
    "$0.9$; unlike the covariance clouds, the *spread* is comparable across panels and\n",
    "only the tilt changes.\n",
    "\n",
    "![Scatter clouds of $(X,Y)$ at correlation $-0.9$, $0$, and $0.9$ (left to right). Correlation rescales covariance to lie between $-1$ and $1$, so unlike raw covariance the comparison is unit-free: only the tilt, not the overall spread, changes across the panels.](../img/mdl-prob-correlation.svg)\n",
    "\n",
    "There is also a geometric reading. Centering so $\\mu_X=\\mu_Y=0$, the\n",
    "correlation the equation becomes $\\sum_{i,j}x_iy_j\\,p_{ij}$ divided\n",
    "by the two root-mean-squares, which is exactly the cosine formula of\n",
    "that section with coordinates weighted by\n",
    "$p_{ij}$. If standard deviations are \"lengths\" and correlations are \"cosines of\n",
    "angles,\" that section's geometric intuition transfers wholesale to random\n",
    "variables: uncorrelated means orthogonal, $\\rho=\\pm1$ means parallel.\n",
    "\n",
    "For $n$ variables we collect every pairwise covariance into a single\n",
    "**covariance matrix** $\\boldsymbol\\Sigma$ with entries\n",
    "$\\Sigma_{ij}=\\textrm{Cov}(X_i,X_j)$, so the diagonal holds the variances and the\n",
    "off-diagonal the cross-terms. It is symmetric because $\\textrm{Cov}$ is. It is\n",
    "also positive semidefinite, by a two-line computation that generalizes the\n",
    "variance-of-a-sum rule the equation: writing $\\bar X_i=X_i-\\mu_{X_i}$,\n",
    "the deviation of $\\sum_i a_iX_i$ is $\\sum_i a_i\\bar X_i$, and expanding the\n",
    "square inside the expectation,\n",
    "\n",
    "$$\n",
    "\\textrm{Var}\\Bigl(\\sum_i a_i X_i\\Bigr)\n",
    " = E\\Bigl[\\Bigl(\\sum_i a_i \\bar X_i\\Bigr)^{\\!2}\\Bigr]\n",
    " = \\sum_{i,j} a_i a_j\\,E[\\bar X_i \\bar X_j]\n",
    " = \\sum_{i,j} a_i a_j\\,\\Sigma_{ij}\n",
    " = \\mathbf a^\\top \\boldsymbol\\Sigma\\,\\mathbf a .\n",
    "$$\n",
    "\n",
    "The left-hand side is a variance and hence non-negative, so\n",
    "$\\mathbf a^\\top\\boldsymbol\\Sigma\\,\\mathbf a\\ge 0$ for every $\\mathbf a$:\n",
    "positive semidefiniteness is the $n$-variable face of $\\textrm{Var}\\ge 0$.\n",
    "Because $\\boldsymbol\\Sigma$ is symmetric PSD, the spectral theorem\n",
    "(that section) diagonalizes it. The Gaussian $\\mathcal\n",
    "N(\\boldsymbol\\mu,\\boldsymbol\\Sigma)$ is built from exactly this matrix: its\n",
    "density contours are ellipses whose axes point along the eigenvectors of\n",
    "$\\boldsymbol\\Sigma$ with half-lengths $\\propto\\sqrt{\\lambda_i}$, the standard\n",
    "deviation along each principal direction, and we draw and sample these contours\n",
    "when we meet the multivariate Gaussian in that section\n",
    "(the figure). Finding those principal axes *is*\n",
    "principal component analysis, PCA (that section), and the same\n",
    "deviations-as-vectors geometry underlies least squares\n",
    "the equation.\n",
    "\n",
    "### Change of Variables for Densities\n",
    "\n",
    "One last piece of machinery closes the section. When we push a random variable\n",
    "through a function $Y=g(X)$, its density is *not*\n",
    "simply $p_X\\!\\big(g^{-1}(y)\\big)$: as the map stretches and compresses space the\n",
    "density must be re-scaled to keep its total mass at $1$. We already computed\n",
    "the re-scaling factor. The integral change-of-variables theorem of\n",
    "that section, $\\int_{\\boldsymbol\\phi(U)}f(\\mathbf\n",
    "x)\\,d\\mathbf x=\\int_U f(\\boldsymbol\\phi(\\mathbf x))\\,|\\det\n",
    "D\\boldsymbol\\phi(\\mathbf x)|\\,d\\mathbf x$ the equation, already\n",
    "established that a reparametrization scales volume locally by the absolute\n",
    "Jacobian determinant. All a density does is read that theorem with $f=p$ and the\n",
    "constraint that the total integral stays $1$: *probability mass in equals\n",
    "probability mass out*.\n",
    "\n",
    "Take the one-dimensional case first, $g$ monotone so it has an inverse. The\n",
    "intuition is that the mass\n",
    "in a tiny interval must survive the map, $p_Y(y)\\,|dy| = p_X(x)\\,|dx|$ with\n",
    "$y=g(x)$; solving for the new density and writing $x=g^{-1}(y)$ gives the\n",
    "formula. A derivation needing no infinitesimals takes two lines with tools we\n",
    "already have. For increasing $g$ the events $\\{g(X)\\le y\\}$ and\n",
    "$\\{X\\le g^{-1}(y)\\}$ coincide, so the c.d.f.s satisfy\n",
    "$F_Y(y)=F_X\\bigl(g^{-1}(y)\\bigr)$; differentiating with the chain rule and\n",
    "the equation gives\n",
    "$p_Y(y)=p_X\\bigl(g^{-1}(y)\\bigr)\\,\\tfrac{dg^{-1}}{dy}(y)$, and for decreasing\n",
    "$g$ the event flips to $\\{X\\ge g^{-1}(y)\\}$, producing a minus sign that the\n",
    "absolute value absorbs. Either way we obtain the\n",
    "**one-dimensional change-of-variables formula**\n",
    "\n",
    "$$\n",
    "p_Y(y) = p_X\\!\\big(g^{-1}(y)\\big)\\,\\left|\\frac{d g^{-1}}{dy}(y)\\right|.\n",
    "$$\n",
    "\n",
    "The derivative factor is exactly the local stretch of the map: where $g$ spreads a\n",
    "small interval out, the density must drop to keep the area fixed. In several\n",
    "dimensions the scalar stretch $|dg^{-1}/dy|$ becomes the absolute Jacobian\n",
    "determinant, by instantiating the equation with\n",
    "$\\boldsymbol\\phi=g^{-1}$ and $f=p_X$:\n",
    "$P(Y\\in A)=P\\bigl(X\\in g^{-1}(A)\\bigr)=\\int_{g^{-1}(A)}p_X(\\mathbf x)\\,d\\mathbf x\n",
    "=\\int_A p_X\\bigl(g^{-1}(\\mathbf y)\\bigr)\\,\\bigl|\\det J_{g^{-1}}(\\mathbf y)\\bigr|\\,d\\mathbf y$,\n",
    "so the integrand on the right is the density of $Y$. Conservation of mass thus reads\n",
    "\n",
    "$$\n",
    "p_Y(\\mathbf y) = p_X\\!\\big(g^{-1}(\\mathbf y)\\big)\\,\\big|\\det J_{g^{-1}}(\\mathbf y)\\big|,\n",
    "\\qquad\\text{equivalently}\\qquad\n",
    "\\log p_Y(\\mathbf y) = \\log p_X(\\mathbf x) - \\log\\big|\\det J_{g}(\\mathbf x)\\big|\n",
    "\\quad\\text{at }\\mathbf x = g^{-1}(\\mathbf y).\n",
    "$$\n",
    "\n",
    "The log form is the one that matters in practice: pushing data through an\n",
    "invertible network adds a single $-\\log|\\det J_g|$ term to the log-density, and\n",
    "because $\\log|\\det(J_2 J_1)| = \\log|\\det J_1| + \\log|\\det J_2|$ these terms simply\n",
    "*sum* along a composition of layers. That additivity is what makes\n",
    "**normalizing flows** [@rezende2015variational] trainable at scale\n",
    "(that section).\n",
    "\n",
    "As a worked example, let $X\\sim\\mathcal N(0,1)$ and $Y=e^X$, so $g^{-1}(y)=\\log y$\n",
    "and $|dg^{-1}/dy| = 1/y$ for $y>0$. Formula the equation gives the\n",
    "**log-normal** density\n",
    "\n",
    "$$\n",
    "p_Y(y) = \\frac{1}{y\\sqrt{2\\pi}}\\,\\exp\\!\\Big(-\\tfrac12(\\log y)^2\\Big), \\qquad y>0,\n",
    "$$\n",
    "\n",
    "whose $1/y$ prefactor is precisely the change-of-variables correction. The\n",
    "prediction is directly checkable: sample $X\\sim\\mathcal N(0,1)$, push the\n",
    "samples through $e^X$, and a histogram of the results should trace out this\n",
    "density, $1/y$ correction and all."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "random-variables-change-of-variables"
   },
   "source": [
    "# Push X ~ N(0, 1) through Y = e^X and compare a histogram of the samples\n",
    "# with the log-normal density predicted by the change-of-variables formula\n",
    "np.random.seed(0)\n",
    "y = np.exp(np.random.randn(100000))\n",
    "edges = np.linspace(0.0, 8.0, 65)\n",
    "mids, width = (edges[:-1] + edges[1:]) / 2, edges[1] - edges[0]\n",
    "hist = np.histogram(y, edges)[0] / (100000 * width)\n",
    "analytic = np.exp(-np.log(mids)**2 / 2) / (mids * np.sqrt(2 * np.pi))\n",
    "d2l.plot(mids, [hist, analytic], 'y', 'p(y)',\n",
    "         legend=['histogram of exp(X)', 'log-normal density'])"
   ],
   "execution_count": 4,
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"246.28125pt\" height=\"183.35625pt\" viewBox=\"0 0 246.28125 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T13:42:44.778839</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 246.28125 183.35625 \nL 246.28125 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 43.78125 145.8 \nL 239.08125 145.8 \nL 239.08125 7.2 \nL 43.78125 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <path d=\"M 51.249432 145.8 \nL 51.249432 7.2 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_2\">\n      <defs>\n       <path id=\"m1e8a95239a\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m1e8a95239a\" x=\"51.249432\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 0 -->\n      <g transform=\"translate(48.068182 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_3\">\n      <path d=\"M 96.340341 145.8 \nL 96.340341 7.2 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m1e8a95239a\" x=\"96.340341\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(93.159091 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_5\">\n      <path d=\"M 141.43125 145.8 \nL 141.43125 7.2 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m1e8a95239a\" x=\"141.43125\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 4 -->\n      <g transform=\"translate(138.25 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_7\">\n      <path d=\"M 186.522159 145.8 \nL 186.522159 7.2 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m1e8a95239a\" x=\"186.522159\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 6 -->\n      <g transform=\"translate(183.340909 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-36\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_9\">\n      <path d=\"M 231.613068 145.8 \nL 231.613068 7.2 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m1e8a95239a\" x=\"231.613068\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 8 -->\n      <g transform=\"translate(228.431818 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \nQ 1584 2216 1326 1975 \nQ 1069 1734 1069 1313 \nQ 1069 891 1326 650 \nQ 1584 409 2034 409 \nQ 2484 409 2743 651 \nQ 3003 894 3003 1313 \nQ 3003 1734 2745 1975 \nQ 2488 2216 2034 2216 \nz\nM 1403 2484 \nQ 997 2584 770 2862 \nQ 544 3141 544 3541 \nQ 544 4100 942 4425 \nQ 1341 4750 2034 4750 \nQ 2731 4750 3128 4425 \nQ 3525 4100 3525 3541 \nQ 3525 3141 3298 2862 \nQ 3072 2584 2669 2484 \nQ 3125 2378 3379 2068 \nQ 3634 1759 3634 1313 \nQ 3634 634 3220 271 \nQ 2806 -91 2034 -91 \nQ 1263 -91 848 271 \nQ 434 634 434 1313 \nQ 434 1759 690 2068 \nQ 947 2378 1403 2484 \nz\nM 1172 3481 \nQ 1172 3119 1398 2916 \nQ 1625 2713 2034 2713 \nQ 2441 2713 2670 2916 \nQ 2900 3119 2900 3481 \nQ 2900 3844 2670 4047 \nQ 2441 4250 2034 4250 \nQ 1625 4250 1398 4047 \nQ 1172 3844 1172 3481 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-38\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_6\">\n     <!-- y -->\n     <g transform=\"translate(138.471875 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-79\" d=\"M 2059 -325 \nQ 1816 -950 1584 -1140 \nQ 1353 -1331 966 -1331 \nL 506 -1331 \nL 506 -850 \nL 844 -850 \nQ 1081 -850 1212 -737 \nQ 1344 -625 1503 -206 \nL 1606 56 \nL 191 3500 \nL 800 3500 \nL 1894 763 \nL 2988 3500 \nL 3597 3500 \nL 2059 -325 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-79\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_11\">\n      <path d=\"M 43.78125 140.651808 \nL 239.08125 140.651808 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_12\">\n      <defs>\n       <path id=\"m5bda1eb241\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m5bda1eb241\" x=\"43.78125\" y=\"140.651808\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 0.0 -->\n      <g transform=\"translate(20.878125 144.451026) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_13\">\n      <path d=\"M 43.78125 101.470828 \nL 239.08125 101.470828 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m5bda1eb241\" x=\"43.78125\" y=\"101.470828\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.2 -->\n      <g transform=\"translate(20.878125 105.270046) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-32\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_15\">\n      <path d=\"M 43.78125 62.289848 \nL 239.08125 62.289848 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m5bda1eb241\" x=\"43.78125\" y=\"62.289848\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.4 -->\n      <g transform=\"translate(20.878125 66.089067) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_17\">\n      <path d=\"M 43.78125 23.108868 \nL 239.08125 23.108868 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m5bda1eb241\" x=\"43.78125\" y=\"23.108868\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.6 -->\n      <g transform=\"translate(20.878125 26.908087) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_11\">\n     <!-- p(y) -->\n     <g transform=\"translate(14.798437 86.535156) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-28\" d=\"M 1984 4856 \nQ 1566 4138 1362 3434 \nQ 1159 2731 1159 2009 \nQ 1159 1288 1364 580 \nQ 1569 -128 1984 -844 \nL 1484 -844 \nQ 1016 -109 783 600 \nQ 550 1309 550 2009 \nQ 550 2706 781 3412 \nQ 1013 4119 1484 4856 \nL 1984 4856 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-29\" d=\"M 513 4856 \nL 1013 4856 \nQ 1481 4119 1714 3412 \nQ 1947 2706 1947 2009 \nQ 1947 1309 1714 600 \nQ 1481 -109 1013 -844 \nL 513 -844 \nQ 928 -128 1133 580 \nQ 1338 1288 1338 2009 \nQ 1338 2731 1133 3434 \nQ 928 4138 513 4856 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-70\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(63.476562 0)\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(102.490234 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(161.669922 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_19\">\n    <path d=\"M 52.658523 111.015314 \nL 55.476705 41.649308 \nL 58.294886 16.071964 \nL 61.113068 13.815139 \nL 63.93125 23.688746 \nL 66.749432 34.800472 \nL 69.567614 45.645768 \nL 72.385795 55.958201 \nL 75.203977 67.038583 \nL 78.022159 74.749399 \nL 80.840341 82.930388 \nL 83.658523 90.891963 \nL 86.476705 95.107837 \nL 89.294886 99.699847 \nL 92.113068 104.072445 \nL 94.93125 108.460715 \nL 97.749432 112.049692 \nL 100.567614 113.679621 \nL 103.385795 116.328255 \nL 106.203977 119.133613 \nL 109.022159 120.262026 \nL 111.840341 122.691246 \nL 114.658523 124.493572 \nL 117.476705 124.838364 \nL 120.294886 126.860103 \nL 123.113068 128.01986 \nL 125.93125 129.618444 \nL 128.749432 130.151305 \nL 131.567614 130.778201 \nL 134.385795 131.734217 \nL 137.203977 132.455147 \nL 140.022159 132.815612 \nL 142.840341 133.270111 \nL 145.658523 134.006713 \nL 148.476705 134.947057 \nL 151.294886 135.542608 \nL 154.113068 135.526935 \nL 156.93125 135.464246 \nL 159.749432 136.044124 \nL 162.567614 136.404589 \nL 165.385795 136.843416 \nL 168.203977 136.561313 \nL 171.022159 136.655348 \nL 173.840341 136.921778 \nL 176.658523 137.533002 \nL 179.476705 137.752415 \nL 182.294886 137.642708 \nL 185.113068 137.78376 \nL 187.93125 138.034518 \nL 190.749432 138.285276 \nL 193.567614 138.347966 \nL 196.385795 138.818138 \nL 199.203977 138.927844 \nL 202.022159 138.708431 \nL 204.840341 138.849483 \nL 207.658523 139.16293 \nL 210.476705 139.178603 \nL 213.294886 139.350999 \nL 216.113068 139.382344 \nL 218.93125 139.115913 \nL 221.749432 139.28831 \nL 224.567614 139.209948 \nL 227.385795 139.335327 \nL 230.203977 139.335327 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"line2d_20\">\n    <path d=\"M 52.658523 113.871806 \nL 55.476705 37.976805 \nL 58.294886 13.5 \nL 61.113068 13.717379 \nL 63.93125 22.905427 \nL 66.749432 34.678562 \nL 69.567614 46.512742 \nL 72.385795 57.46018 \nL 75.203977 67.229449 \nL 78.022159 75.801978 \nL 80.840341 83.266798 \nL 83.658523 89.748133 \nL 86.476705 95.373973 \nL 89.294886 100.263176 \nL 92.113068 104.521017 \nL 94.93125 108.238523 \nL 97.749432 111.493417 \nL 100.567614 114.351638 \nL 103.385795 116.868982 \nL 106.203977 119.092632 \nL 109.022159 121.062525 \nL 111.840341 122.812521 \nL 114.658523 124.371394 \nL 117.476705 125.763661 \nL 120.294886 127.010267 \nL 123.113068 128.12916 \nL 125.93125 129.135764 \nL 128.749432 130.043373 \nL 131.567614 130.863479 \nL 134.385795 131.606044 \nL 137.203977 132.27973 \nL 140.022159 132.892085 \nL 142.840341 133.449707 \nL 145.658523 133.95838 \nL 148.476705 134.423181 \nL 151.294886 134.848582 \nL 154.113068 135.238532 \nL 156.93125 135.596522 \nL 159.749432 135.925647 \nL 162.567614 136.228658 \nL 165.385795 136.508001 \nL 168.203977 136.765862 \nL 171.022159 137.004192 \nL 173.840341 137.224736 \nL 176.658523 137.429063 \nL 179.476705 137.61858 \nL 182.294886 137.794553 \nL 185.113068 137.958126 \nL 187.93125 138.110329 \nL 190.749432 138.252093 \nL 193.567614 138.384264 \nL 196.385795 138.507606 \nL 199.203977 138.622815 \nL 202.022159 138.730522 \nL 204.840341 138.831304 \nL 207.658523 138.925684 \nL 210.476705 139.014142 \nL 213.294886 139.097115 \nL 216.113068 139.175003 \nL 218.93125 139.248173 \nL 221.749432 139.316961 \nL 224.567614 139.381677 \nL 227.385795 139.442603 \nL 230.203977 139.5 \n\" clip-path=\"url(#pa6d98777e2)\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #bf00bf; stroke-width: 1.5\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 43.78125 145.8 \nL 43.78125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 239.08125 145.8 \nL 239.08125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 43.78125 145.8 \nL 239.08125 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 43.78125 7.2 \nL 239.08125 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"legend_1\">\n    <g id=\"patch_7\">\n     <path d=\"M 100.495313 44.55625 \nL 232.08125 44.55625 \nQ 234.08125 44.55625 234.08125 42.55625 \nL 234.08125 14.2 \nQ 234.08125 12.2 232.08125 12.2 \nL 100.495313 12.2 \nQ 98.495313 12.2 98.495313 14.2 \nL 98.495313 42.55625 \nQ 98.495313 44.55625 100.495313 44.55625 \nz\n\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n    </g>\n    <g id=\"line2d_21\">\n     <path d=\"M 102.495313 20.298438 \nL 112.495313 20.298438 \nL 122.495313 20.298438 \n\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n    </g>\n    <g id=\"text_12\">\n     <!-- histogram of exp(X) -->\n     <g transform=\"translate(130.495313 23.798438) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \nL 1178 3500 \nL 1178 0 \nL 603 0 \nL 603 3500 \nz\nM 603 4863 \nL 1178 4863 \nL 1178 4134 \nL 603 4134 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \nL 1172 3500 \nL 2356 3500 \nL 2356 3053 \nL 1172 3053 \nL 1172 1153 \nQ 1172 725 1289 603 \nQ 1406 481 1766 481 \nL 2356 481 \nL 2356 0 \nL 1766 0 \nQ 1100 0 847 248 \nQ 594 497 594 1153 \nL 594 3053 \nL 172 3053 \nL 172 3500 \nL 594 3500 \nL 594 4494 \nL 1172 4494 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-67\" d=\"M 2906 1791 \nQ 2906 2416 2648 2759 \nQ 2391 3103 1925 3103 \nQ 1463 3103 1205 2759 \nQ 947 2416 947 1791 \nQ 947 1169 1205 825 \nQ 1463 481 1925 481 \nQ 2391 481 2648 825 \nQ 2906 1169 2906 1791 \nz\nM 3481 434 \nQ 3481 -459 3084 -895 \nQ 2688 -1331 1869 -1331 \nQ 1566 -1331 1297 -1286 \nQ 1028 -1241 775 -1147 \nL 775 -588 \nQ 1028 -725 1275 -790 \nQ 1522 -856 1778 -856 \nQ 2344 -856 2625 -561 \nQ 2906 -266 2906 331 \nL 2906 616 \nQ 2728 306 2450 153 \nQ 2172 0 1784 0 \nQ 1141 0 747 490 \nQ 353 981 353 1791 \nQ 353 2603 747 3093 \nQ 1141 3584 1784 3584 \nQ 2172 3584 2450 3431 \nQ 2728 3278 2906 2969 \nL 2906 3500 \nL 3481 3500 \nL 3481 434 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \nQ 2534 3019 2420 3045 \nQ 2306 3072 2169 3072 \nQ 1681 3072 1420 2755 \nQ 1159 2438 1159 1844 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1341 3275 1631 3429 \nQ 1922 3584 2338 3584 \nQ 2397 3584 2469 3576 \nQ 2541 3569 2628 3553 \nL 2631 2963 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \nQ 1497 1759 1228 1600 \nQ 959 1441 959 1056 \nQ 959 750 1161 570 \nQ 1363 391 1709 391 \nQ 2188 391 2477 730 \nQ 2766 1069 2766 1631 \nL 2766 1759 \nL 2194 1759 \nz\nM 3341 1997 \nL 3341 0 \nL 2766 0 \nL 2766 531 \nQ 2569 213 2275 61 \nQ 1981 -91 1556 -91 \nQ 1019 -91 701 211 \nQ 384 513 384 1019 \nQ 384 1609 779 1909 \nQ 1175 2209 1959 2209 \nL 2766 2209 \nL 2766 2266 \nQ 2766 2663 2505 2880 \nQ 2244 3097 1772 3097 \nQ 1472 3097 1187 3025 \nQ 903 2953 641 2809 \nL 641 3341 \nQ 956 3463 1253 3523 \nQ 1550 3584 1831 3584 \nQ 2591 3584 2966 3190 \nQ 3341 2797 3341 1997 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6d\" d=\"M 3328 2828 \nQ 3544 3216 3844 3400 \nQ 4144 3584 4550 3584 \nQ 5097 3584 5394 3201 \nQ 5691 2819 5691 2113 \nL 5691 0 \nL 5113 0 \nL 5113 2094 \nQ 5113 2597 4934 2840 \nQ 4756 3084 4391 3084 \nQ 3944 3084 3684 2787 \nQ 3425 2491 3425 1978 \nL 3425 0 \nL 2847 0 \nL 2847 2094 \nQ 2847 2600 2669 2842 \nQ 2491 3084 2119 3084 \nQ 1678 3084 1418 2786 \nQ 1159 2488 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1356 3278 1631 3431 \nQ 1906 3584 2284 3584 \nQ 2666 3584 2933 3390 \nQ 3200 3197 3328 2828 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-66\" d=\"M 2375 4863 \nL 2375 4384 \nL 1825 4384 \nQ 1516 4384 1395 4259 \nQ 1275 4134 1275 3809 \nL 1275 3500 \nL 2222 3500 \nL 2222 3053 \nL 1275 3053 \nL 1275 0 \nL 697 0 \nL 697 3053 \nL 147 3053 \nL 147 3500 \nL 697 3500 \nL 697 3744 \nQ 697 4328 969 4595 \nQ 1241 4863 1831 4863 \nL 2375 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-78\" d=\"M 3513 3500 \nL 2247 1797 \nL 3578 0 \nL 2900 0 \nL 1881 1375 \nL 863 0 \nL 184 0 \nL 1544 1831 \nL 300 3500 \nL 978 3500 \nL 1906 2253 \nL 2834 3500 \nL 3513 3500 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-58\" d=\"M 403 4666 \nL 1081 4666 \nL 2241 2931 \nL 3406 4666 \nL 4084 4666 \nL 2584 2425 \nL 4184 0 \nL 3506 0 \nL 2194 1984 \nL 872 0 \nL 191 0 \nL 1856 2491 \nL 403 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-68\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(63.378906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(91.162109 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(143.261719 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(182.470703 0)\"/>\n      <use xlink:href=\"#DejaVuSans-67\" transform=\"translate(243.652344 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(307.128906 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(348.242188 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6d\" transform=\"translate(409.521484 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(506.933594 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(538.720703 0)\"/>\n      <use xlink:href=\"#DejaVuSans-66\" transform=\"translate(599.902344 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(635.107422 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(666.894531 0)\"/>\n      <use xlink:href=\"#DejaVuSans-78\" transform=\"translate(726.667969 0)\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(785.847656 0)\"/>\n      <use xlink:href=\"#DejaVuSans-28\" transform=\"translate(849.324219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-58\" transform=\"translate(888.337891 0)\"/>\n      <use xlink:href=\"#DejaVuSans-29\" transform=\"translate(956.84375 0)\"/>\n     </g>\n    </g>\n    <g id=\"line2d_22\">\n     <path d=\"M 102.495313 34.976562 \nL 112.495313 34.976562 \nL 122.495313 34.976562 \n\" style=\"fill: none; stroke-dasharray: 5.55,2.4; stroke-dashoffset: 0; stroke: #bf00bf; stroke-width: 1.5\"/>\n    </g>\n    <g id=\"text_13\">\n     <!-- log-normal density -->\n     <g transform=\"translate(130.495313 38.476562) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-2d\" d=\"M 313 2009 \nL 1997 2009 \nL 1997 1497 \nL 313 1497 \nL 313 2009 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 3500 \nL 1159 3500 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-64\" d=\"M 2906 2969 \nL 2906 4863 \nL 3481 4863 \nL 3481 0 \nL 2906 0 \nL 2906 525 \nQ 2725 213 2448 61 \nQ 2172 -91 1784 -91 \nQ 1150 -91 751 415 \nQ 353 922 353 1747 \nQ 353 2572 751 3078 \nQ 1150 3584 1784 3584 \nQ 2172 3584 2448 3432 \nQ 2725 3281 2906 2969 \nz\nM 947 1747 \nQ 947 1113 1208 752 \nQ 1469 391 1925 391 \nQ 2381 391 2643 752 \nQ 2906 1113 2906 1747 \nQ 2906 2381 2643 2742 \nQ 2381 3103 1925 3103 \nQ 1469 3103 1208 2742 \nQ 947 2381 947 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-6c\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(27.783203 0)\"/>\n      <use xlink:href=\"#DejaVuSans-67\" transform=\"translate(88.964844 0)\"/>\n      <use xlink:href=\"#DejaVuSans-2d\" transform=\"translate(152.441406 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(188.525391 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(251.904297 0)\"/>\n      <use xlink:href=\"#DejaVuSans-72\" transform=\"translate(313.085938 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6d\" transform=\"translate(352.449219 0)\"/>\n      <use xlink:href=\"#DejaVuSans-61\" transform=\"translate(449.861328 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6c\" transform=\"translate(511.140625 0)\"/>\n      <use xlink:href=\"#DejaVuSans-20\" transform=\"translate(538.923828 0)\"/>\n      <use xlink:href=\"#DejaVuSans-64\" transform=\"translate(570.710938 0)\"/>\n      <use xlink:href=\"#DejaVuSans-65\" transform=\"translate(634.1875 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6e\" transform=\"translate(695.710938 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(759.089844 0)\"/>\n      <use xlink:href=\"#DejaVuSans-69\" transform=\"translate(811.189453 0)\"/>\n      <use xlink:href=\"#DejaVuSans-74\" transform=\"translate(838.972656 0)\"/>\n      <use xlink:href=\"#DejaVuSans-79\" transform=\"translate(878.181641 0)\"/>\n     </g>\n    </g>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pa6d98777e2\">\n   <rect x=\"43.78125\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-5 fw=all -->\n",
    "\n",
    "The two curves coincide: the mass pushed forward through $e^x$ piles up exactly\n",
    "where the equation says it must, including the mode at\n",
    "$y=e^{-1}$ that the naive guess $p_X(\\log y)$ (which peaks at $y=1$) gets\n",
    "wrong. A linear map\n",
    "$\\mathbf y = A\\mathbf x$ illustrates the multivariate rule in one stroke: $J_g=A$ is\n",
    "constant, so the density is rescaled uniformly by $1/|\\det A|$; stretch space by\n",
    "$|\\det A|$ and the density thins by the same factor.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* A continuous random variable is described by a *probability density* $p(x)\\ge0$\n",
    "  with $\\int p\\,dx=1$ the equation; the density is not itself a\n",
    "  probability; only its integral over an interval is,\n",
    "  $P(X\\in(a,b])=\\int_a^b p$ the equation. Any single point, and\n",
    "  more generally any set of *measure zero* (coverable by intervals of\n",
    "  arbitrarily small total length), has probability zero.\n",
    "* The *cumulative distribution function* $F(x)=\\int_{-\\infty}^x p=P(X\\le x)$ *is*\n",
    "  a probability and unifies discrete, continuous, and mixed variables. Density and\n",
    "  c.d.f. are derivative and integral of each other: $F'=p$\n",
    "  the equation, the fundamental theorem of calculus.\n",
    "* The *mean* $\\mu_X=E[X]$ locates the distribution and is *linear*\n",
    "  the equation: sums of expectations add with no independence\n",
    "  needed. The *variance* $\\textrm{Var}(X)=E[X^2]-\\mu_X^2$\n",
    "  the equation measures spread, scales as\n",
    "  $\\textrm{Var}(aX+b)=a^2\\textrm{Var}(X)$ the equation, and its root\n",
    "  is the *standard deviation*, back in the original units.\n",
    "* *Markov's inequality* the equation caps the tail of a non-negative\n",
    "  variable by its mean; applied to $(X-\\mu_X)^2$ it yields *Chebyshev's\n",
    "  inequality* the equation: at most a $1/\\alpha^2$ fraction of any\n",
    "  distribution lies $\\alpha$\n",
    "  standard deviations or farther from the mean.\n",
    "* Several variables are handled by a *joint density*; *marginals* come from\n",
    "  integrating out the unwanted variables the equation. *Covariance*\n",
    "  measures linear co-variation, giving $\\textrm{Var}(X+Y)=\\textrm{Var}(X)+\n",
    "  \\textrm{Var}(Y)+2\\textrm{Cov}(X,Y)$ the equation, and *correlation*\n",
    "  normalizes it to $[-1,1]$ as a cosine between centered variables. Zero\n",
    "  covariance does not imply independence.\n",
    "* Pushing $X$ through an invertible map $g$ rescales its density by the local\n",
    "  stretch of the map: $p_Y(y)=p_X(g^{-1}(y))\\,|dg^{-1}/dy|$\n",
    "  the equation, with the absolute Jacobian determinant taking\n",
    "  over in several dimensions the equation, the log-det form that\n",
    "  powers normalizing flows.\n",
    "\n",
    "## Exercises\n",
    "1. Suppose $X$ has density $p(x) = \\frac{1}{x^2}$ for $x \\ge 1$ and $p(x) = 0$ otherwise. Verify it is a density and compute $P(X > 2)$ and the c.d.f. $F(x)$.\n",
    "2. The Laplace distribution has density $p(x) = \\tfrac12 e^{-|x|}$. Find its mean and standard deviation. (*Hint:* $\\int_0^\\infty xe^{-x}\\,dx = 1$ and $\\int_0^\\infty x^2e^{-x}\\,dx = 2$.)\n",
    "3. A population has mean $1$ and standard deviation $2$. Use Chebyshev\n",
    "   the equation to bound the population probability $P(X>9)$. Then\n",
    "   explain why observing $25\\%$ above $9$ in a *finite sample* is evidence\n",
    "   against the claim but is not logically impossible without knowing the sample\n",
    "   size.\n",
    "4. Two variables $X,Y$ have joint density $p_{XY}(x, y) = x+y$ on $[0,1]^2$ and $0$ otherwise. Verify that it integrates to one, find the marginals $p_X,p_Y$ and the covariance $\\textrm{Cov}(X,Y)$, and decide whether $X$ and $Y$ are independent.\n",
    "5. Give a second proof of the affine variance rule $\\textrm{Var}(aX+b)=a^2\\textrm{Var}(X)$ the equation, this time starting from the computational form $\\textrm{Var}(aX+b)=E[(aX+b)^2]-E[aX+b]^2$ the equation: expand both expectations with linearity the equation and watch the cross terms cancel. (The proof in the text instead worked with the deviation $a(X-\\mu_X)$.)\n",
    "6. Using $\\textrm{Var}(X+Y)=\\textrm{Var}(X)+\\textrm{Var}(Y)+2\\textrm{Cov}(X,Y)$ the equation, show that for independent identically distributed $X_1,\\ldots,X_n$ with variance $\\sigma^2$, the sample mean $\\bar X=\\tfrac1n\\sum_i X_i$ has variance $\\sigma^2/n$. (This is why averaging reduces noise.)\n",
    "7. Let $X$ be uniform on $\\{-1,0,1\\}$ and $Y=|X|$. Compute $\\textrm{Cov}(X,Y)$ and confirm it is zero even though $Y$ is a deterministic function of $X$. Why does correlation miss this relationship?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=mdl-random-variables-md-6 fw=pytorch -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/1094)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-pytorch",
   "display_name": "d2l (PyTorch)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
