Bayesian Distributions

A sensor reads 3.0, and its noise has a standard deviation of 1. A Normal prior of width 1 halves the reading to 1.50. A spike-and-slab prior keeps 2.21. At a reading of 0.5 the order flips: 0.25 against 0.04. Same data, same rule, different prior.

Pick a prior and drag the reading. Watch the purple posterior, and the curve below that says where every reading ends up. Then we build, piece by piece, ten prior distributions: what each one is for, how it updates, and how to set it.

You need what a probability is, the bell curve and Bayes' rule in words. We build the rest from zero.

Feed one reading to four priors

3.0

Exact posteriors computed in your browser, illustrative. One reading y of the true value θ, with Normal noise of standard deviation 1. Warm: prior. Blue: likelihood of the reading. Purple: posterior. A bar at 0 shows the spike; its height is its probability.

Chapter 0

Same Reading, Different Answers

Multiply the prior by the likelihood at every value, and see that the prior's shape decides the answer

A sensor reads 3.0, with noise of standard deviation 1. What is the true value θ? The reading alone says 3.0. Bayes' rule says the answer also depends on what you believed before the reading.

That belief is the prior, p(θ): a distribution over the unknown before any data. The likelihood, p(y | θ), says how likely the reading y is if the truth is θ. The posterior, p(θ | y), is the belief after the reading. Call the total of prior times likelihood over every θ the evidence, p(y). Bayes' rule links the four:

Say it aloud

p of theta given y equals p of theta, times p of y given theta, over p of y.

p(θ | y)
p of theta given y the posterior: the belief about θ after the reading.
p(θ)
p of theta the prior: the belief before the reading.
p(y | θ)
p of y given theta the likelihood: how well the value θ explains the reading y.
p(y)
p of y the evidence: prior times likelihood, added over every θ. It makes the posterior total 1.
In plain words

For each candidate θ, multiply its prior by its likelihood. Add all the products to get p(y). Divide each product by p(y).

With numbers

With made-up numbers: candidates θ = 0, 1.5 and 3 have prior 0.6, 0.3 and 0.1. The reading y = 2.5 gives likelihoods 0.018, 0.242 and 0.352. The products are 0.0105, 0.0726 and 0.0352, and they add to 0.118. The posterior is 0.09, 0.61 and 0.30.

Multiply, point by point

Warm is the prior, blue the likelihood, purple their product rescaled. Pick a prior shape, drag the reading, and move the pink probe to see one multiplication.

2.5
1.5

Exact, on a grid of 801 values of θ from −4 to 4. Noise standard deviation 1. Illustrative priors.

The rule never changes. Only the prior changes, and its shape sets what the posterior can do.

Failure: a prior that is zero where the truth is.

Symptom: a positive-only prior meets 100 readings that average −0.5. The posterior mean is 0.02, pressed against 0.

Measure: the posterior probability below 0 is exactly 0, after 100 readings or a million.

Fix: give every value that physics allows some prior probability. Use a hard bound only when the bound is a fact (Chapter 6).

The ten chapters ahead each give one prior a job:

  1. Pretend data: Beta, Gamma and Dirichlet priors, set by a mean and a worth in observations.
  2. Normal-Gamma: an unknown mean and an unknown noise level together.
  3. Mixture: several bumps, and Bayes' rule inside them.
  4. Spike & slab: an effect that is exactly zero or real (the hero's second prior).
  5. Horseshoe: shrink small effects hard and keep big ones (the hero's third).
  6. Bounds: truncate or fold a bell to keep it positive (the hero's fourth).
  7. Simplex: chances that add to 1 and rise together.
  8. Gumbel & Kumaraswamy: samples you can take a gradient through.
  9. Showcase: particles that update any prior.
  10. The field guide: every prior, its job and its update in one table.
A prior gives every θ below 0 probability 0. A thousand readings average −2. What is the posterior probability that θ is below 0?

Chapter 1

A Prior Is Pretend Data

Name a prior mean and its worth in observations, and the update becomes a weighted average

You launch a checkout page. Before any visitor arrives, you think about 5% will buy. How sure are you? Say you would trade that belief for 40 real visitors. That one sentence sets the prior.

For a chance p, the prior is a Beta(α, β): α pretend buyers and β pretend leavers. A belief of 5% worth 40 visitors is α = 2, β = 38. The update adds the real counts: k buyers among n visitors gives Beta(α + k, β + n − k). Bayes Estimation derives why, with MAP estimates and credible intervals. Here we use the result to set priors.

Every conjugate prior (a prior whose posterior stays in its own family) works the same way. Call the prior mean m, and its worth in observations, the prior strength, s. Call the number of real observations n and their mean x̄. The posterior mean is a weighted average:

Say it aloud

m-post equals s times m, plus n times x-bar, all over s plus n.

mpost
m-post the posterior mean.
s
s the prior strength: how many observations the prior is worth.
m
m the prior mean.
n
n the number of real observations.
x̄
x-bar the mean of the real observations.
In plain words

Treat the prior as s observations that averaged m. Pool them with the n real ones that averaged x-bar. Average all s plus n.

With numbers

With made-up numbers: s = 40 and m = 0.05. Then 12 of 100 visitors buy, so x-bar = 0.12. m-post = (40 × 0.05 + 100 × 0.12) / 140 = 14/140 = 0.10. The posterior is Beta(14, 126).

UnknownPriorStrength s, mean mUpdate after n observations
A chance pBeta(α, β)s = α + β, m = α/sBeta(α + k, β + n − k)
A count rate λ (Poisson)Gamma(α, rate β)s = β windows, m = α/βGamma(α + Σx, β + n)
A waiting rate (exponential)Gamma(α, rate β)α pretend events in β pretend timeGamma(α + n, β + Σx)
K category chancesDirichlet(α1..αK)s = Σαi, mi = αi/sαi + counti
A mean, noise knownNormal(μ0, σ2/κ0)s = κ0, m = μ0precision-weighted mean (Bayes Estimation)

The Gamma here uses the rate form: mean α/β. Obstacles per lidar scan: a prior mean of 3 worth 2 scans is Gamma(6, rate 2). Five scans see 25 in total. The posterior is Gamma(31, rate 7), with mean 31/7 = 4.43, which is (2 × 3 + 5 × 5)/7.

Set the prior, then add data

Warm is the prior, purple the posterior; the blue mark is the data mean. Set the prior mean and strength, then add observations and watch the weight move to the data.

0.05
40

Illustrative data from a seeded generator: true buy chance 0.12, true scan rate 5. The curves are exact Beta and Gamma densities.

Failure: a prior worth more than you have seen.

Symptom: a prior mean of 3 with strength 1,000 meets 50 real scans averaging 5. The posterior mean is still 3.10.

Measure: the data's weight is n/(s + n) = 50/1,050 = 4.8%.

Fix: set s to the number of observations you would honestly trade the belief for. A strength of 1,000 claims you have already seen 1,000 scans.

A Beta(3, 7) prior meets 10 trials with 6 hits. What is the posterior mean?

Chapter 2

Unknown Mean, Unknown Noise

Put one prior on the pair, update four numbers, and get a Student-t for the mean

A new thermometer arrives. You know neither its average reading μ nor its noise σ. The algebra is cleaner with the precision λ = 1/σ2, because a Gamma prior lives on positive numbers and precisions add. The Normal-Gamma prior draws the precision first, then the mean:

Say it aloud

lambda follows a Gamma with alpha-nought and beta-nought; given lambda, mu follows a Normal with mean mu-nought and variance one over kappa-nought lambda.

λ
lambda the precision of one reading, 1/σ2.
α0, β0
alpha-nought, beta-nought shape and rate. α0/β0 is the prior's typical precision, worth 2α0 readings.
μ
mu the true average reading.
μ0
mu-nought the prior guess for μ.
κ0
kappa-nought the worth of that guess in readings.
In plain words

Pick a typical precision alpha-nought over beta-nought. Then pick mu-nought, worth kappa-nought readings. The mean's spread is the noise spread divided by the root of kappa-nought, so a noisy instrument gets a vague mean.

With numbers

With made-up numbers: μ0 = 0, κ0 = 1, α0 = 2, β0 = 2. The typical precision is 1, so σ is near 1, and μ is as uncertain as one reading.

Five readings come in: 1.2, 2.5, 1.8, 3.1 and 2.4. Their mean is 2.2, and their squared deviations add to 2.10. The update changes four numbers:

κn = κ0 + n = 1 + 5 = 6 μn = (κ0μ0 + n x̄)/κn = (0 + 5 × 2.2)/6 = 1.83 αn = α0 + n/2 = 4.5 βn = β0 + ½Σ(xi − x̄)2 + κ0n(x̄ − μ0)2/(2κn) = 2 + 1.05 + 2.02 = 5.07

The mean is a pretend-data average again. The last term of βn charges the precision for the gap between the prior guess and the data. Average over the unknown precision, and μ follows a Student-t with 2αn = 9 degrees of freedom, centre 1.83 and scale √(βn/(αnκn)) = 0.43. Its 95% interval runs from 0.85 to 2.81.

Watch the pair sharpen

Top: the belief over the mean μ (across) and the precision λ (up). Warm before data, purple after; the warm cross is the truth. Below: the Student-t for μ and its 95% interval. Add readings.

The first five readings are the ones in the text; later ones come from a seeded generator with true μ = 2 and σ = 1. Densities are exact. Illustrative.

Failure: plugging in the noise.

Symptom: with three readings, the interval x̄ ± 1.96 s/√n misses the truth about one time in five.

Measure: in 100,000 simulated sets of three readings it covers 81%, not 95%.

Fix: average over the unknown noise. The Student-t with 2 degrees of freedom uses 4.30 in place of 1.96 and covers 95%.

Why is the posterior for μ a Student-t and not a Normal?

Chapter 3

Many Bumps From Simple Pieces

Stack weighted bells into one density, then ask which bell made each point

Measure the heights of a crowd of adults and children, and you get two bumps. One bell cannot draw that. A Gaussian mixture picks a component k with chance wk, then draws from that component's bell, with mean μk and standard deviation σk:

Say it aloud

p of x equals the sum over k of w-k, times the Normal density at x with mean mu-k and variance sigma-k squared.

p(x)
p of x the mixture density at the value x.
Σk
the sum over k one term for each of the K components.
wk
w-k the weight of component k: its share of the data. The weights add to 1.
N(x | μk, σk2)
N of x given mu-k, sigma-k squared the bell of component k, centred at μk with spread σk.
In plain words

Shrink bell k to w-k of its area. Stack the shrunken bells. Because the weights add to 1, the stack has area 1.

With numbers

With made-up numbers: weights 0.5, 0.3, 0.2, means −1, 0, 3, every σ = 1. The mean is Σ wkμk = 0.1. The variance is Σ wk(σk2 + μk2) − 0.12 = 3.29: the gaps between bells add spread.

Bayes' rule runs inside the mixture. Which bell made the point x? The weight wk is the prior, the bell's height at x is the likelihood, and p(x) is the evidence. Their ratio is the responsibility rk(x):

rk(x) = wk N(x | μk, σk2) / p(x) x = 2: r = 0.03, 0.24, 0.72 for the bells at −1, 0, 3

Stack the bells, ask who made x

The dashed curves are the weighted bells; the filled curve is their sum; yellow is the mean. Move the third bell, pick the weights, and slide the pink probe. The bar on the right splits the probe point among the bells.

3.0
2.0

Exact densities. Bells 1 and 2 sit at −1 and 0; every σ = 1. Illustrative.

The EM algorithm fits a mixture in two repeated steps. Compute every point's responsibilities. Then refit each bell to the points, weighted by them (EM for Gaussian Mixtures).

With enough components, a mixture can match almost any smooth density (Bishop, section 2.3.9). A mixture of conjugate priors also works as a prior. Each part updates as usual. Each weight grows or shrinks with how well its part predicted the data.

Failure: a bell collapses onto one point.

Symptom: EM reports a log-likelihood that keeps climbing, with no limit.

Measure: one σk falls toward 0 on a single point. At weight 0.2 that point adds −2.5 to the log-likelihood at σ = 1 and +4.4 at σ = 0.001, and it grows forever.

Fix: put a floor under σk, or give σk2 an inverse-Gamma prior and fit the posterior peak (MAP).

A mixture has weights 0.5, 0.3, 0.2 and means −1, 0, 3. What is its mean?

Chapter 4

Exactly Zero, or Real

Mix a point at zero with a wide bell, and get each feature's chance of being real

You test 10,000 genes and expect about 50 to matter. For each gene you want a chance that its effect is real, not only an estimate. The spike-and-slab prior gives each effect θj two branches: exactly zero, or drawn from a wide bell. Call the chance of the real branch π, and the typical size of a real effect s:

Say it aloud

p of theta-j equals one minus pi, times delta-nought, plus pi times a Normal with mean zero and variance s squared.

p(θj)
p of theta-j the prior on the effect of feature j.
π
pi the prior chance that a feature is real.
δ0
delta-nought the spike: all its probability on exactly 0.
N(0, s2)
N of zero, s squared the slab: a bell of width s for real effects.
In plain words

Flip a coin that lands real with chance pi. If not real, the effect is exactly 0. If real, draw it from a bell of width s.

With numbers

With made-up numbers: 50 real genes expected among 10,000 sets π = 0.005. If real effects are about 3 noise units, set s = 3.

Now one noisy reading y of θ, with noise 1. Each branch predicts y. The spike says y is Normal with variance 1; the slab says variance s2 + 1. Score each branch by its prior chance times its prediction. The slab's share is the posterior inclusion probability, PIP:

Say it aloud

PIP equals pi times N of y given zero and s squared plus one, over that term plus one minus pi times N of y given zero and one.

PIP
P-I-P the posterior chance that the feature is real.
N(y | 0, s2 + 1)
N of y given zero, s squared plus one how well the slab predicted the reading.
N(y | 0, 1)
N of y given zero, one how well the spike predicted it: noise alone.
In plain words

Weigh each branch by pi or one minus pi, times its prediction of y. PIP is the slab's share. The posterior mean is PIP times s squared over s squared plus one, times y.

With numbers

With made-up numbers: π = 0.2, s = 3, y = 3. Slab: 0.2 × 0.0804 = 0.0161. Spike: 0.8 × 0.00443 = 0.0035. PIP = 0.82, and the posterior mean is 0.82 × 0.9 × 3 = 2.21. At y = 0.5, PIP = 0.08 and the mean is 0.04.

Keep the feature or drop it

Top: the prior, a warm spike at 0 and a slab. Bottom: the posterior in purple. Drag the reading, then widen the slab and watch the PIP.

3.0
0.20
3

Exact posterior for one reading with noise 1. Illustrative numbers.

Failure: a slab made wide "to be safe".

Symptom: with s = 100, a reading of 3 gets PIP 0.18, against 0.82 at s = 3.

Measure: the reading where PIP passes 0.5 moves from 2.37 to 3.46. A huge slab spreads its prediction so thin that modest readings look like noise (Lindley's paradox).

Fix: set s to the size of effect you expect. Exact answers over p features also sum over 2p on-off patterns (over a billion at p = 30), so use Gibbs sampling over the switches.

A spike-and-slab prior has π = 0.05 over 1,000 features. How many features does it expect to be real before any data?

Chapter 5

Shrink the Small, Keep the Big

Give every effect its own heavy-tailed width, and a smooth prior acts like a spike and a slab

Spike-and-slab needs on-off switches, and switches are slow to sample. The horseshoe prior has no switches. It gives each effect θj its own width, the local scale λj, times one shared width, the global scale τ (Carvalho, Polson and Scott, 2010):

Say it aloud

theta-j, given lambda-j and tau, follows a Normal with mean zero and variance lambda-j squared tau squared; lambda-j follows a half-Cauchy.

θj
theta-j the effect of feature j.
λj
lambda-j the local scale: feature j's own width.
τ
tau the global scale: how big effects are overall.
C+(0, 1)
half-Cauchy the size of a Cauchy draw: median 1, with a tail so heavy that its mean is infinite.
In plain words

Draw a personal width lambda-j from the half-Cauchy. Multiply it by tau. Draw theta-j from a bell that wide. Most widths are small, and a few are huge.

With numbers

A half-Cauchy draw is above 10 with chance 1 − (2/π) arctan 10 = 0.063, and below 0.1 with the same chance. So 6% of features get a bell 100 times wider than another 6%.

How does it update? With one reading y of noise 1, a given width shrinks y by the shrinkage weight κ = 1/(1 + λ2τ2). A κ near 1 pulls y to 0; a κ near 0 keeps y. The posterior mean averages κ over the widths that explain y:

Say it aloud

The expected theta given y equals one minus the expected kappa given y, times y.

E[θ | y]
the expected theta given y the posterior mean of the effect.
E[κ | y]
the expected kappa given y the average shrinkage weight, over the widths that fit the reading.
y
y the reading.
In plain words

Each width shrinks y by its kappa. Average kappa over the widths, weighted by how well each predicts y. Keep one minus that share of y.

With numbers

At τ = 1, κ has a Beta(1/2, 1/2) prior, piled up at 0 and at 1: a horseshoe. At y = 0.5, E[κ | y] = 0.66 and the mean is 0.17. At y = 4, E[κ | y] = 0.14 and the mean is 3.45. A Normal prior of variance 1 keeps half of each: 0.25 and 2.00.

See the horseshoe

Left: the shrinkage weight κ, warm before the reading and purple after. Right: the posterior mean for every reading, horseshoe in purple, a Normal prior of the same scale in yellow. Drag τ and the reading.

4.0
1

Exact, by numerical integration over the local scale. One reading, noise 1. Illustrative.

Failure: a global scale set too large.

Symptom: 100 features, 5 real of size 5, τ fixed at 1. In our simulation, 22 null features keep posterior means above 0.5.

Measure: the total squared error is 18.7. With τ = 0.05 no null passes 0.5, and the error is 4.2 (a Normal prior gives 47.7, the raw readings 84.0).

Fix: set τ from the number of real effects you expect, p0 of D. Piironen and Vehtari (2017) suggest τ0 = p0/(D − p0) · σ/√n, here 5/95 = 0.053. Or give τ its own half-Cauchy prior.

What lets the horseshoe keep big signals while it shrinks noise?

Chapter 6

Cut the Bell or Fold It

Keep a Gaussian inside its bounds by cutting and rescaling, or by folding the negative side over

A length, a delay or a standard deviation cannot be negative. There are two ways to put a bell on positive numbers. You can cut off the part outside and rescale the rest: truncate. Or you can observe the size of a signed error, |X|: fold. Call the standard Normal density φ and its CDF Φ. A bell with mean μ and spread σ, truncated to the interval from a to b, has density:

Say it aloud

p of x equals phi of x minus mu over sigma, over sigma times capital Phi at the upper bound minus capital Phi at the lower bound.

p(x)
p of x the truncated density.
φ(·)
phi the standard Normal density; μ and σ belong to the parent bell, not the cut one.
Φ(·) − Φ(·)
capital Phi at b minus capital Phi at a the parent's area between the bounds.
a, b
a, b the bounds; b can be infinity.
In plain words

Keep the parent bell between a and b. Divide by the parent's area there, so the kept piece has area 1.

With numbers

N(0, 1) cut to [0, ∞) keeps area 0.5, so its density doubles. Its mean is √(2/π) = 0.798, not 0, and its variance is 0.363.

Folding adds the mirror image instead. If y = |X| and X is Normal with mean μ and spread σ:

Say it aloud

p of y equals phi of y minus mu over sigma, plus phi of y plus mu over sigma, all over sigma, for y at least zero.

p(y)
p of y the folded density of the size y.
φ((y − μ)/σ)
phi of y minus mu over sigma the parent's height at +y.
φ((y + μ)/σ)
phi of y plus mu over sigma the parent's height at −y, folded over.
In plain words

For each size y, add the parent's height at plus y and at minus y. Folding keeps all the area, so it needs no rescaling.

With numbers

μ = 1, σ = 1: the density at 0 is 0.48 folded and 0.29 truncated. The means are 1.17 and 1.29. At μ = 0 the two agree: that is the half-normal.

Cut, fold or clip

The yellow outline is the parent bell; the warm area is the result; the dashed line is its mean. Try all three, then drag μ.

1.0
1.0
∞

Exact densities; the lower bound is 0. Clip shows what np.clip(x, 0, None) does to the samples. Illustrative.

A truncated Normal prior updates simply. Do the Normal update, then cut. Prior N(0, 1) on [0, ∞) and a reading of −1 give N(−0.5, 0.5), cut at 0: mean 0.42. That is the hero's Positive prior at y = −1. For a standard deviation, set a half-normal's scale near the largest value you find plausible; Gelman (2006) prefers the heavier-tailed half-Cauchy.

Failure: clipping instead of truncating.

Symptom: np.clip on draws from N(0.5, 1) turns 30.9% of them into exactly 0, a spike no density has.

Measure: count exact zeros. The clipped mean is 0.70; the truncated mean is 1.01.

Fix: truncate (scipy.stats.truncnorm) if values below 0 cannot happen. Fold if you see the size of a signed error.

A robot's signed drift from its lane is Normal with mean 0.3 m. You only log the size of the drift. Which distribution describes the log?

Chapter 7

Chances That Rise Together

Draw correlated scores from a bell, push them through softmax, and break the Dirichlet's rule

A document is 50% sports, 30% politics and 20% tech. Three chances that add to 1 are a point in a triangle, the simplex. The Dirichlet is the conjugate prior there: its update adds counts. But any two of its parts always pull against each other. For Dirichlet(2, 2, 2), every pair has correlation −0.5.

Real topics rise together: a paper about genetics is often also about disease. The logistic-normal draws a vector of scores z from a multivariate Normal with mean μ and covariance Σ, then turns the scores into chances with softmax:

Say it aloud

z follows a Normal with mean mu and covariance capital Sigma; theta-k equals e to the z-k, over the sum over j of e to the z-j.

z
z a vector of K scores, one per category, on a log scale.
μ
mu the typical scores.
Σ
capital Sigma the covariance: which scores rise and fall together.
θk
theta-k the chance of category k.
Σj ezj
the sum over j of e to the z-j the total that makes the chances add to 1.
In plain words

Draw correlated scores z from a bell. Exponentiate each score and divide by the total. Scores that rise together give chances that rise together.

With numbers

Three categories, z3 pinned at 0, z1 and z2 with spread 1 and correlation ρ. At ρ = 0, θ1 and θ2 have correlation −0.75. At ρ = 0.95 it is +0.55, out of the Dirichlet's reach.

Make two chances rise together

Each blue dot is one draw of three chances; the corners are all-in on one category. Switch families, then drag the knob and read the correlation of chances 1 and 2.

2.0

600 seeded draws, illustrative. Logistic-normal: z3 = 0, z1 and z2 have spread 1 and correlation ρ. The yellow dot is the sample mean.

The price is conjugacy. Multinomial counts times a logistic-normal has no closed form, so the update needs a Laplace approximation, variational inference or MCMC. The correlated topic model of Blei and Lafferty uses this prior. To set it, put μ at the log ratios of the typical chances, and put positive entries in Σ for categories that appear together.

Failure: K free scores for K chances.

Symptom: a sampler's scores drift for thousands of steps and never settle, while the chances stay put.

Measure: add 1 to every score and softmax gives the same chances, so one direction of z is invisible to the data.

Fix: pin one score at 0 and model K − 1 scores, as this device does (Aitchison's additive log-ratio).

What can a logistic-normal prior do that a Dirichlet cannot?

Chapter 8

Samples You Can Differentiate

Write a sample as a smooth function of uniform noise, with Gumbel for categories and Kumaraswamy for chances

A variational autoencoder takes gradients through a sample. The reparameterization trick makes that work: write the sample as a smooth function of the parameters and of noise, as in μ + σ·(noise). Two distributions bring the trick to categories and to chances.

The Gumbel distribution describes maxima. The largest of 1,000 exponential waits with mean 1, minus ln 1,000, is close to Gumbel(0, 1): mean 0.5772, variance 1.645. Call the chance of category k pk. The Gumbel-max trick picks a category:

Say it aloud

k-star is the k that makes log p-k plus g-k largest, where g-k is minus the log of minus the log of u-k.

k*
k-star the chosen category.
argmaxk
arg-max over k the k that makes the bracket largest.
pk
p-k the chance of category k.
gk
g-k fresh Gumbel noise for category k.
uk
u-k a uniform draw between 0 and 1.
In plain words

Add fresh Gumbel noise to each log-chance. Pick the largest. Category k wins with chance p-k, exactly.

With numbers

p = 0.5, 0.3, 0.2 and u = 0.3, 0.8, 0.6 give g = −0.19, 1.50, 0.67. The sums are −0.88, 0.30 and −0.94, so category 2 wins. Over 200,000 draws the shares are 0.499, 0.301 and 0.201.

The argmax has no useful gradient. The Gumbel-softmax (Jang, Gu and Poole; Maddison, Mnih and Teh; both 2017) uses softmax at a temperature T instead: a soft one-hot vector that hardens as T falls.

For a chance on [0, 1], the Beta is the natural prior, but its CDF has no closed form to invert. The Kumaraswamy(a, b) has the CDF F(x) = 1 − (1 − xa)b. Its inverse is exact:

Say it aloud

x equals one minus one-minus-u to the one over b, all to the one over a.

x
x a Kumaraswamy sample between 0 and 1.
u
u a uniform draw between 0 and 1.
b
b the shape that pulls mass toward 0.
a
a the shape that pulls mass toward 1.
In plain words

Draw u. Run the CDF backwards with two powers. Gradients flow to a and b.

With numbers

a = 2, b = 5, u = 0.5: x = (1 − 0.50.2)0.5 = 0.360, the median. Beta(2, 5) has median 0.264. Kumaraswamy(a, b) equals Beta(a, b) only when a or b is 1.

Turn uniform noise into a sample

Gumbel: warm marks the log-chances, teal the winner, purple the soft sample. Kumaraswamy: the pink u maps through the CDF to x. Draw one, then 1,000.

1.0
2.0
5.0

Seeded uniform draws, illustrative. Gumbel chances fixed at 0.5, 0.3, 0.2. Kumaraswamy: warm is its density, the yellow outline is Beta(a, b), blue is the share of 1,000 draws.

Failure: the wrong temperature.

Symptom: at T = 5 the soft sample is no longer a choice. At T = 0.1 the gradients swing wildly.

Measure: the largest entry of the soft sample averages 0.41 at T = 5 (near uniform), 0.67 at T = 1 and 0.96 at T = 0.1.

Fix: start near T = 1 and lower it during training, or use the straight-through version: the hard argmax going forward, the soft gradient going back.

Why does the Gumbel-softmax matter for models with discrete latent variables?

Chapter 9

Particles Update Any Prior

Sample the prior, weight each sample by the likelihood, and resample when the weights pile up

The horseshoe and the logistic-normal have no closed-form posterior. A particle distribution needs none. It stores N samples xi, the particles, each with a weight wi; the weights add to 1. Draw the particles from the prior. When a reading arrives, multiply each weight by the likelihood and rescale. That is Bayes' rule from Chapter 0, done on samples, and it works for any prior you can sample.

The danger is weight piling onto a few particles. Call the number of equal-weight particles the cloud is worth the effective sample size, ESS:

Say it aloud

ESS equals one over the sum over i of w-i squared.

ESS
E-S-S the effective sample size, between 1 and N.
Σi
the sum over i one term for each of the N particles.
wi
w-i the weight of particle i, rescaled so the weights add to 1.
In plain words

Square each weight, add the squares, and invert. Equal weights give ESS = N. One particle that holds all the weight gives 1.

With numbers

Weights 0.7, 0.1, 0.1, 0.1: ESS = 1/(0.49 + 0.03) = 1.9 of 4. Give 1,000 particles from a Normal(0, 1) prior one reading of 3: ESS is about 190. A reading of 5 leaves about 13.

Resampling repairs the cloud: draw N new particles from the old ones in proportion to their weights, then reset every weight to 1/N. Heavy particles get copies; light ones vanish. Repeated resampling without moving the particles shrinks the set. In our run, 40 readings left 125 distinct values among 1,000. A small random move after each resample restores the spread (Sequential Monte Carlo, Particle Filter).

Update a cloud of particles

Bars pile up the particles by weight: warm before any reading, purple after. The yellow outline is the exact posterior; blue ticks are readings. Pick a prior, add readings, and watch the ESS.

500

Seeded simulation, illustrative. Readings have noise 1; the priors are the hero's four. The exact posterior uses all readings at once. The move is a small random jitter, a stand-in for a proper MCMC move.

Try the four priors. The particle mean tracks the exact one within a few hundredths while ESS stays high. Spike-and-slab particles start with 80% sitting exactly on 0; the readings move weight off them. Then press the surprise reading: ESS falls, and few distinct particles survive the resample.

Failure: a reading the prior did not expect.

Symptom: after one surprising reading the particle mean jumps, and the next run with a new seed gives a different answer.

Measure: ESS. One reading of 5 against a Normal(0, 1) prior leaves about 13 effective particles of 1,000; single runs range from about 10 to 30.

Fix: use more particles. Or draw them from a wider proposal and correct the weights (Importance Sampling). Or add the evidence in small steps, with moves between them.

Four particles have weights 0.25 each. What is the ESS?

Chapter 10

The Field Guide

Match the belief to its prior, and keep the updates and settings in one place

Name the belief first, then find its row. Each row gives the prior's job, how to set it and how it updates.

PriorJobSet it byHow it updates
Beta, Gamma, DirichletA chance, a rate, K sharesPrior mean m and strength sAdd counts: a weighted average
Normal-GammaMean and noise both unknownμ0, κ0; typical precision α0/β0Four numbers; Student-t for μ
Gaussian mixtureSeveral groups, many bumpsK by held-out fit; start EM from k-meansResponsibilities; mixture weights reweighted
Spike-and-slabExact zeros, chance each is realπ = expected real share; s = real effect sizePIP per feature; Gibbs over switches
HorseshoeMany zeros, scalableτ0 = p0/(D − p0) · σ/√nMCMC (HMC); mean = (1 − E[κ]) y
Truncated NormalA hard bound that is a factParent μ, σ and the boundsNormal update, then cut
Folded / half-normalThe size of a signed error; a scale priorScale near the largest plausible valueNumerical, or MCMC
Logistic-normalShares that rise togetherμ at log ratios; Σ for co-occurrence; pin one scoreLaplace, variational or MCMC
GumbelMaxima; differentiable categoriesLocation, scale; temperature TUsed inside samplers, not as a prior
KumaraswamyA Beta-like chance you can reparameterizeShapes a, bVariational fit through the inverse CDF
ParticlesAny prior you can sampleN; resample threshold; move stepWeight by likelihood, resample at low ESS

Numbers worth remembering

Corrections to the old version of this page

The core as code

pythonimport numpy as np
from scipy import stats, special

def pip(y, pi=0.2, s=3.0):
    """Spike-and-slab: chance the effect is real, one reading with noise 1."""
    slab = pi * stats.norm.pdf(y, 0, np.sqrt(s*s + 1))
    spike = (1 - pi) * stats.norm.pdf(y, 0, 1)
    return slab / (slab + spike)                    # pip(3) = 0.819

def horseshoe_mean(y, tau=1.0, m=4000):
    """E[theta | y] = (1 - E[kappa | y]) y, integrating over lambda = tan(phi)."""
    phi = (np.arange(m) + .5) / m * np.pi / 2       # half-Cauchy = uniform phi
    g = (np.tan(phi) * tau) ** 2
    w = stats.norm.pdf(y, 0, np.sqrt(g + 1))
    return (w * g / (g + 1)).sum() / w.sum() * y     # horseshoe_mean(4) = 3.45

def normal_gamma(x, m0=0., k0=1., a0=2., b0=2.):
    n, xb = len(x), np.mean(x)
    kn = k0 + n; mn = (k0*m0 + n*xb) / kn; an = a0 + n/2
    bn = b0 + .5*np.sum((x - xb)**2) + k0*n*(xb - m0)**2 / (2*kn)
    return stats.t(2*an, loc=mn, scale=np.sqrt(bn / (an*kn)))   # the marginal for mu

def gumbel_max(logp, rng):
    return np.argmax(logp - np.log(-np.log(rng.uniform(size=len(logp)))))

def kumaraswamy(a, b, u):
    return (1 - (1 - u) ** (1/b)) ** (1/a)          # median: u = 0.5

def particle_update(x, logw, y):
    logw = logw + stats.norm.logpdf(y, x, 1)
    w = np.exp(logw - logw.max()); w /= w.sum()
    ess = 1 / np.sum(w**2)
    return np.log(w), ess

Keep going

The takeaway. The update rule is always prior times likelihood. Choose the prior for its job, set its numbers in units you can defend, such as pretend observations, an expected count of real effects or a hard bound, and check what it does to a reading you understand.

Now press Present or Teach and explain four things from memory. Explain why a conjugate posterior mean is a weighted average, with Gamma(31, rate 7). Explain how the spike-and-slab scores a reading of 3 to get PIP 0.82. Explain why the horseshoe keeps 3.45 of a reading of 4. Explain what ESS measures and when to resample. Then go back to the hero, pick the horseshoe, and drag the reading from 0 to 5.

Bayesian Distributions
Next: Specialized Distributions · Back to Gleams