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.
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
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:
p of theta given y equals p of theta, times p of y given theta, over p of y.
For each candidate θ, multiply its prior by its likelihood. Add all the products to get p(y). Divide each product by p(y).
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.
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.
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:
Chapter 1
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:
m-post equals s times m, plus n times x-bar, all over s plus n.
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 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).
| Unknown | Prior | Strength s, mean m | Update after n observations |
|---|---|---|---|
| A chance p | Beta(α, β) | s = α + β, m = α/s | Beta(α + 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 time | Gamma(α + n, β + Σx) |
| K category chances | Dirichlet(α1..αK) | s = Σαi, mi = αi/s | αi + counti |
| A mean, noise known | Normal(μ0, σ2/κ0) | s = κ0, m = μ0 | precision-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.
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.
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.
Chapter 2
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:
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.
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 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:
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.
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%.
Chapter 3
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:
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.
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 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):
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.
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).
Chapter 4
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:
p of theta-j equals one minus pi, times delta-nought, plus pi times a Normal with mean zero and variance s squared.
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 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:
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.
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 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.
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.
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.
Chapter 5
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):
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.
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.
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:
The expected theta given y equals one minus the expected kappa given y, times y.
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.
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.
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.
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.
Chapter 6
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:
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.
Keep the parent bell between a and b. Divide by the parent's area there, so the kept piece has area 1.
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 σ:
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.
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.
μ = 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.
The yellow outline is the parent bell; the warm area is the result; the dashed line is its mean. Try all three, then drag μ.
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.
Chapter 7
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:
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.
Draw correlated scores z from a bell. Exponentiate each score and divide by the total. Scores that rise together give chances that rise together.
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.
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.
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).
Chapter 8
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:
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.
Add fresh Gumbel noise to each log-chance. Pick the largest. Category k wins with chance p-k, exactly.
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:
x equals one minus one-minus-u to the one over b, all to the one over a.
Draw u. Run the CDF backwards with two powers. Gradients flow to a and b.
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.
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.
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.
Chapter 9
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:
ESS equals one over the sum over i of w-i squared.
Square each weight, add the squares, and invert. Equal weights give ESS = N. One particle that holds all the weight gives 1.
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).
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.
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.
Chapter 10
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.
| Prior | Job | Set it by | How it updates |
|---|---|---|---|
| Beta, Gamma, Dirichlet | A chance, a rate, K shares | Prior mean m and strength s | Add counts: a weighted average |
| Normal-Gamma | Mean and noise both unknown | μ0, κ0; typical precision α0/β0 | Four numbers; Student-t for μ |
| Gaussian mixture | Several groups, many bumps | K by held-out fit; start EM from k-means | Responsibilities; mixture weights reweighted |
| Spike-and-slab | Exact zeros, chance each is real | π = expected real share; s = real effect size | PIP per feature; Gibbs over switches |
| Horseshoe | Many zeros, scalable | τ0 = p0/(D − p0) · σ/√n | MCMC (HMC); mean = (1 − E[κ]) y |
| Truncated Normal | A hard bound that is a fact | Parent μ, σ and the bounds | Normal update, then cut |
| Folded / half-normal | The size of a signed error; a scale prior | Scale near the largest plausible value | Numerical, or MCMC |
| Logistic-normal | Shares that rise together | μ at log ratios; Σ for co-occurrence; pin one score | Laplace, variational or MCMC |
| Gumbel | Maxima; differentiable categories | Location, scale; temperature T | Used inside samplers, not as a prior |
| Kumaraswamy | A Beta-like chance you can reparameterize | Shapes a, b | Variational fit through the inverse CDF |
| Particles | Any prior you can sample | N; resample threshold; move step | Weight by likelihood, resample at low ESS |
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
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.