Section 1
Named families of distributions
How to use this pageClick any colored symbol to read what it means. Commit to a guess before the demo answers it. Each challenge is solved by moving a control, and it is worth 8 XP.
and data and parameters and probability and density the mean, the center and the scale and the precision an error or divergence
Any model of a quantity has to say how likely each value is. A real number has too many values to list, so statisticians use a family of distributions: one formula with a few adjustable numbers, the parameters. Each choice of parameters picks one member. A coin needs one parameter, the chance of heads. A bell curve needs two: its center and its width .
Predict first. The data are 200 points from a density with two humps. Which fit explains new points from the same source better?
Few dials or many?
Everything is seeded and synthetic. A histogram gives zero probability to an empty bin, which would be an infinite penalty, so every density is floored at 0.00001. The score is the average log-probability of 3000 fresh points from the same source. Higher is better.
true densityGaussian fithistogram
On the bell tab the Gaussian wins, because its two numbers are all the data need. On the two-humps tab no choice of two numbers gives two humps, while a histogram with enough bins finds both. Push the bins up with few training points, and the histogram starts fitting single points, so its score collapses.
Going deeper: dials and overfitting (added here)
Think of a family as a machine with dials. Few dials are easy to set and hard to overfit, but the machine makes only a narrow range of shapes. Many dials fit more shapes and can fit noise as well. That is overfitting: more dials fit the training data better and the new data worse. A family is a bet that the world has the shape the family allows.
Section 2
Bernoulli distribution
The simplest random variable has two outcomes: a coin lands heads or tails, a message is spam or not. Call the outcomes 1 and 0. The Bernoulli distribution has one parameter, , in [0, 1], which is the probability that . The book gives the first two properties as Equations 3.16 and 3.17:
Click any coloured symbol to see what it means.
Click any coloured symbol to see what it means.
The two outcomes exhaust all possibilities, so the second follows from the first. One formula covers both values, Equation 3.18:
Predict first. For which probability is the variance of a coin largest?
Click any coloured symbol to see what it means.
It is a switch written as arithmetic. For the exponent of is 1 and the exponent of is 0, so the formula returns . For it returns . Because one formula covers both cases, it can be multiplied over many observations and differentiated. The mean and variance are Equations 3.19 and 3.20:
Click any coloured symbol to see what it means.
Click any coloured symbol to see what it means.
Going deeper: the mean and variance of a coin (added here, not printed in the book)
The mean is times 1, plus 0 times , so it equals . A variable that takes only the values 0 and 1 satisfies , so and the variance is .
A biased coin
The tosses come from a seeded generator. Move the parameter, then toss again for a new sample.
exact probabilityobserved sharevariance
Click any coloured symbol to see what it means.
With few tosses the observed share jumps around, and with thousands it settles on . The variance is largest at one half, where the outcome is most uncertain, and it is zero at both ends, where the outcome is certain. A Bernoulli variable has no free spread: once is set, the variance is fixed.
Challenge +8 XPSet so that the variance is 0.21, within 0.005.
Section 3
Multinoulli distribution
A variable with different states, such as the next word in a sentence or the class of an image, needs the multinoulli or categorical distribution. It is parametrized by a vector of probabilities, where is the probability of the -th state. The last state gets whatever is left, and the entries must satisfy . In symbols:
Only numbers are needed, because the probabilities add up to 1. For this is exactly the Bernoulli distribution.
Going deeper: categories and the multinomial
The Bernoulli and multinoulli distributions are enough to describe any distribution over their domain. They do this not because they are powerful but because their domain is simple: every state can be listed. For continuous variables there are uncountably many states, so a distribution with a few parameters must impose strict limits on its shape.
The states are usually categories, not numbers, so state 1 need not have the value 1, and one does not normally compute an expectation or variance. The book notes that the term was coined recently and popularized by Murphy (2012). It is a special case of the multinomial distribution, which describes how often each category appears among samples. Many texts write “multinomial” for the case .
The space of three-state distributions
Drag the dot, or use the sliders. The third probability is fixed by the other two. Then draw samples to see the counts.
probabilityobserved share
For three states, plot against the second probability. Non-negativity and a total of at most 1 select a triangle. Each point inside is a valid distribution, and the third probability is the distance to the sloping edge.
The corners are the three certain distributions, where one state has probability 1. The center is the uniform distribution. The count vector after draws follows the multinomial distribution, and the readout evaluates it for the counts you see.
Going deeper: the multinomial counts (added here, not printed in the book)
The book describes the multinomial distribution in words only. For the counts after draws it is the formula below. The readout in the demo evaluates it for the counts you see.
Challenge +8 XPDrag the point to the center of the triangle, so that both probabilities are within 0.02 of one third.
Section 4
Gaussian distribution
The most used distribution over real numbers is the normal or Gaussian distribution, the bell curve (Equation 3.21). Its plot is the book's Figure 3.1.
Click any coloured symbol to see what it means.
The factor in front is a normalizing constant that makes the total area 1. The mean is any real number, and the standard deviation is positive. The variance is .
Going deeper: reading the exponent (added here)
Read it from the outside in. The exponent is minus half the squared distance of from the center , measured in units of . The exponent is never positive and is zero only at the center, so the curve peaks at and falls off symmetrically.
Predict first. The standard deviation of a Gaussian is halved. What happens to the height of its peak?
Figure 3.1, interactive
The default and is the book's figure. The dashed curve appears after your prediction.
densitypeakinflection points
The book marks the peak at and the inflection points at . An inflection point is where the curve stops bending down and starts bending up. Drag the round handle to move and the square handles to change .
Challenge +8 XPMake the peak height 0.80, within 0.005, by changing the standard deviation only.
A smaller makes the peak taller and the bell narrower. The area stays 1 because the peak height is . The share of probability within one, two and three standard deviations depends only on the distance in units of , so it is the same for every and .
Going deeper: where the bends sit (added here, not printed in the book)
Differentiate the density twice. The second derivative is zero exactly where the bracket vanishes:
so the bends sit at , one standard deviation from the peak.
The precision parametrization
Evaluating the density needs inverted and squared each time. The book therefore gives Equation 3.22 with the precision , the inverse of the variance:
Click any coloured symbol to see what it means.
The distribution does not change. High precision means a narrow bell, and a precise measurement is one with small variance. The gain is computational: when the density is evaluated many times, no division by is needed.
Section 5
Reasons for the Gaussian default
Without prior knowledge of the shape of a distribution over the real numbers, the normal is a good default. The book gives two reasons.
The central limit theorem
Many quantities are sums of many small influences: measurement noise, sensor error, many small random effects. The central limit theorem says that the sum of many independent random variables is approximately normal, whatever the shapes of the individual terms, as long as no single term dominates. A complicated system can therefore often be modeled as normal noise even when its parts are not normal.
Predict first. Which source needs the most terms before its sum looks normal?
Sums of many random terms
The demo adds independent terms, repeats the sum 4000 times and standardizes each sum. Its distance is the Kolmogorov-Smirnov distance: the largest vertical gap between the empirical distribution of the standardized sums and the normal curve. Smaller means closer to normal. The book states the theorem without a demonstration, so this check is added here.
histogram of sumsnormal density
With one term the histogram is the source itself. On the default trials, the uniform and two-spike sources are already close to a bell at 5 terms, with a distance of about 0.01 to 0.05. The exponential source needs about 20 to 30 terms to reach about 0.03. The biased coin is slowest, because a sum of coin tosses takes only whole-number values: its histogram is a comb of spikes that follows the bell, and even at 60 terms the distance is about 0.1.
Going deeper: where the limit fails (added here)
The theorem describes a limit. It does not say that every real quantity is normal, and very heavy-tailed quantities may not converge the way the theorem needs.
Challenge +8 XPOn the Uniform tab, find a number of terms at which the distance drops below 0.015.
Maximum uncertainty at fixed variance
The second reason is that, among all distributions with the same variance, the normal encodes the maximum uncertainty over the real numbers. It inserts the least prior knowledge into a model. The book defers the full argument to Section 19.4.2. To compare densities we need a measure of uncertainty, the differential entropy , which Section 3.13 defines as the average surprise of a draw. It is not printed in this section:
Same variance, different uncertainty
The demo fixes the variance and compares five densities: the Gaussian, the Laplace, the logistic, the uniform and a two-bump mixture whose separation you control. The bar chart shows each entropy minus the Gaussian entropy.
GaussianLaplacelogisticuniformtwo bumps
The Gaussian bar sits at zero and every other density lies below it. A change in moves all the entropies together, so the ranking never changes. The two-bump mixture shows the effect best: at zero separation it is a Gaussian, and as the bumps move apart at fixed variance, its uncertainty falls. This is a handful of examples, not a proof.
Going deeper: closed forms of the entropies (added here, not printed in the book)
At a common variance, each entropy has a closed form. The Gaussian value is the largest of the five. The demo integrates each density numerically and agrees with these values.
The uniform density on an interval of width has entropy , the logistic and Laplace values follow the same pattern.
Challenge +8 XPPush the bump separation until the two-bump entropy is at least 0.3 nats below the Gaussian entropy.
Section 6
Multivariate Gaussian
The normal generalizes to , where is the dimension. It has a mean vector and a positive definite symmetric covariance matrix (Equation 3.23):
Click any coloured symbol to see what it means.
A two-dimensional Gaussian
In the full tab the correlation tilts the ellipses. In the diagonal tab the correlation is forced to zero, so the ellipses line up with the axes. In the isotropic tab both spreads are equal and the ellipses become circles. A full covariance in dimensions has free numbers, a diagonal one has and an isotropic one has 1. This count is added here. It is why the simpler forms are attractive in high dimensions.
Brightness shows the density. The two ellipses mark squared Mahalanobis distance 1 and 4. Drag in the plot to move the query point and read its distance.
Compare it with one dimension. The squared distance has become the quadratic form , the squared Mahalanobis distance.
Going deeper: the constant and the size of the cloud (added here)
It measures distance in units adapted to the shape of the cloud, so directions in which the cloud is wide count for less per unit of length. The constant in front plays the role of the one-dimensional , with measuring the size of the cloud.
The matrix is the covariance matrix from Section 3.8. Its diagonal holds the variance of each coordinate and its off-diagonal entries the covariances. The density needs the inverse, which is expensive to compute again and again, so Equation 3.24 uses the precision matrix , the inverse of the covariance:
Click any coloured symbol to see what it means.
A diagonal covariance makes the coordinates uncorrelated, and for a Gaussian uncorrelated means independent. The isotropic Gaussian goes further: its covariance is a scalar times the identity matrix, so the variance is the same in every direction and the contours are circles.
Going deeper: why the contours are ellipses (added here, not printed in the book)
Each contour is the set where the quadratic form equals a constant. That set is an ellipse. Its axes point along the eigenvectors of , and its half-lengths are the square roots of the constant times the eigenvalues.
Challenge +8 XPDrag the query point until its squared Mahalanobis distance is between 0.9 and 1.1, which puts it on the unit ellipse.
Section 7
Exponential and Laplace distributions
A Gaussian is smooth everywhere, so it cannot place a sharp point at one value. The exponential distribution places its peak exactly at zero (Equation 3.25):
Click any coloured symbol to see what it means.
The symbol is the indicator function. It equals 1 when its condition holds and 0 otherwise, so every negative value gets probability zero. For the density starts at height and decays at rate .
Going deeper: mean and variance of the exponential (standard facts, not printed in the book)
Its mean is and its variance is .
A closely related distribution places a sharp peak at any point : the Laplace distribution (Equation 3.26).
Click any coloured symbol to see what it means.
Sharp points and tails
The upper plot shows the sharp point. The exponential jumps from 0 to at the origin, and the Laplace has a corner at , while the matched Gaussian is smooth. The lower plot takes logarithms. The Gaussian becomes a parabola and the Laplace becomes two straight lines. Straight lines decay more slowly, so far from the center the Laplace puts much more probability than a Gaussian with the same variance.
exponential or LaplaceGaussian, same mean and variance
It is two exponential tails glued back to back at . The decay uses the absolute distance where the Gaussian uses the squared distance. This gives a pointed peak and heavier tails at the same scale. The mean is and the variance is (standard, not printed).
Challenge +8 XPOn the Laplace tab, make the peak height exactly 0.50. The peak of a Laplace density is .
Section 8
Dirac and empirical distributions
Sometimes all the probability should sit at one point. The tool is the Dirac delta (Equation 3.27):
Click any coloured symbol to see what it means.
Predict first. As a narrow bell is squeezed toward a spike, the weighted average of a smooth function under it approaches what?
The delta is zero everywhere except at 0, yet it integrates to 1, which no ordinary function can do. The book calls it a generalized function, defined by what it does inside an integral. One can think of it as the limit of functions that put less and less mass away from 0. A shift by gives an infinitely narrow, infinitely high peak at . Its key property is that integrating it against a function picks out that function's value at the spike.
Going deeper: the sifting property (added here, not printed in the book)
The book defines the delta through its behavior inside integrals. This is the explicit statement of that property:
The delta as a limit of narrowing bells
The density is a Gaussian with center and a shrinking width. The lower plot shows a test function and its average under the bell.
Challenge +8 XPNarrow the bell until the weighted average is within 0.002 of the value of the function at the center.
As the width shrinks the bell grows taller and thinner, its area stays 1, and the weighted average of slides toward . In the limit this is the sifting property at work.
The empirical distribution
A common use of the delta is the empirical distribution of a data set (Equation 3.28):
Click any coloured symbol to see what it means.
With data points, each spike has mass . The spikes add up to 1, so this is a valid distribution. It is the distribution we sample from when we train on the data.
Going deeper: expectations, discrete data and maximum likelihood (added here)
Expectations under a delta are therefore trivial: the expectation of under a spike at is . For discrete variables no delta is needed: the empirical distribution is a multinoulli distribution with the observed frequencies. The book adds that the empirical distribution is the density that maximizes the likelihood of the training data (Section 5.5).
Build an empirical distribution
Click the plot to add a data point, up to 20. Drag a point to move it. Each point carries a spike of mass .
To sample from it means picking a data point at random, with replacement. A model trained on the data is therefore asked to match this spiky distribution. How spiky should the model be? The next demo replaces each spike by a bump of width .
Predict first. As the spike width shrinks to zero, what happens to the likelihood of the training data?
Training data and new data
The data are 30 seeded draws from a two-bump density, plus 800 fresh points from the same density. The model replaces each spike by a Gaussian of width (a kernel density estimate). The score is the average log-likelihood.
training pointsnew-data scoretraining score
As the spikes narrow, the likelihood of the training data keeps rising, because each point sits on top of its own tall spike. In the limit of zero width, the training likelihood grows without bound. The score on new data tells the other half of the story. It peaks at an intermediate width and then falls steeply. The empirical distribution reproduces its training set and says almost nothing about new points. The two goals, fitting the data and generalizing from it, pull in different directions.
Going deeper: the kernel density estimate (added here, not printed in the book)
Replacing each spike by a Gaussian of width gives this smoothed empirical distribution. As goes to 0 it becomes Equation 3.28.
Challenge +8 XPMove the spike width until the new-data score is within 0.02 of the best value on the grid.
Section 9
Mixtures of distributions
A mixture distribution combines component distributions. On each trial, a component identity is drawn from a multinoulli distribution, and the sample is then drawn from that component (Equation 3.29):
Click any coloured symbol to see what it means.
Here is the multinoulli distribution over the identities. In words: the probability of is the sum over components of the chance of choosing that component times the chance that it generates . The empirical distribution is a mixture too, with one Dirac component for each data point.
Going deeper: the sum rule (added here)
The formula is the sum rule applied to the joint distribution, from the chain rule.
Latent variables
The identity is a latent variable: a random variable that we cannot observe directly. It is linked to the visible through the joint distribution. Latent variables return in Section 16.5.
Three bells and their hidden component
Choose a component, then set its weight, mean and width. Click or drag the plot to choose an observed value. The lower plot compares the prior, the share of each component before looking at the value, with the posterior, the share after.
component 1component 2component 3mixture
With the color box ticked, each sample is generated in two steps: a draw of the hidden component and then a draw from it. Untick the box and only the dots remain, which is all an observer sees. The prior is the model's belief about before it sees , and the posterior is the belief after. The book makes this distinction with the words “prior” and “posterior”.
Challenge +8 XPMove the query point until component 3 has a posterior of 0.95 or more.
Gaussian mixtures
A very powerful and common type is the Gaussian mixture model, whose components are Gaussians with their own means and covariances . The covariances can be shared, or each component can be restricted to be diagonal or isotropic. Besides these, the parameters include the prior probabilities of the components. Figure 3.2 shows samples from a three-component model whose components illustrate the three kinds of covariance. The next demo rebuilds it.
Figure 3.2, interactive
From left to right: an isotropic component, a diagonal component with more spread along the second axis, and a full-covariance component that you can rotate. The parameters are chosen for this demo.
Uncoloured, the samples look like a cloud with three lumps, which is what real data look like. Colored, the mixture shows how it generated them. The isotropic lump is round. The diagonal lump is stretched along one axis. The full lump is stretched along a direction that only a full covariance matrix can express.
Challenge +8 XPRotate the full component until its long axis points along the diagonal, at 45 degrees.
Universal approximation of densities
The book's last claim here is that a Gaussian mixture is a universal approximator of densities: any smooth density can be approximated, with any specific non-zero error, by a Gaussian mixture with enough components. A single component is limited, but adding components removes the limit. The demo fits a mixture with components to a target density, by expectation-maximisation run on the target itself. It starts from equally spaced components and adjusts every weight, mean and width. The error is the Kullback-Leibler divergence , which is 0 only when the two agree.
More components, smaller error
With one component the error is largest for the two pointed peaks. The flat top and the skewed target are next, and the triangle is already fairly bell-shaped. The error then falls as components are added, though not smoothly, because expectation-maximisation can settle in a local optimum. For the two pointed peaks the error is 0.0026 nats at six components, 0.0010 at twelve and 0.0009 at sixteen, so it levels off. The guarantee is for smooth densities, and sharp features are the hard case.
Going deeper: the cost of universality (added here)
The number of components needed may be very large, so universality says that a mixture can represent a density, not that it does so economically.
Challenge +8 XPOn the Two pointed peaks tab, find a number of components that brings the error below 0.005 nats.
What to take away
- A family of distributions is a formula with a few parameters. Few parameters prevent overfitting and limit the shapes that can be expressed.
- Bernoulli (one parameter ) and multinoulli ( parameters) describe any distribution over a finite set. The Bernoulli mean and variance are and .
- The Gaussian has a mean and a scale , or equivalently a precision . It is the default because sums of many small effects tend to it and because, at fixed variance, it commits to the least.
- The multivariate Gaussian replaces with a covariance matrix or its inverse, the precision matrix. Diagonal and isotropic versions use fewer parameters.
- Exponential and Laplace densities have a sharp point at zero or at , and the Laplace has heavier tails than the Gaussian at the same scale.
- The Dirac delta puts all the mass on one point. The empirical distribution is a sum of deltas, one per data point, and it is a mixture.
- A mixture picks a hidden component first. Gaussian mixtures approximate any smooth density with enough components.
Final quizCheck yourself
Questions that mix the whole module. Each one is scored, and the score feeds your mastery of this module.
Source: Ian Goodfellow, Yoshua Bengio and Aaron Courville, Deep Learning, MIT Press, 2016, Section 3.9 (pages 62–68), free to read at deeplearningbook.org. Where the book prints equation numbers, the numbers here follow the book. The order of ideas follows the book. The explanations and all demos were written for this page.