📊 Data Science & Statistics · Graduate · STAT 410

Bayesian Statistics

A graduate-level introduction to Bayesian inference, organized into 18 lessons across six modules. Begin with probability and odds, compare likelihoods under different sampling plans, and derive beta-binomial updating and prediction. Continue with conjugate models, prior choice, credible intervals, decision theory, value of information, sequential decisions, simulation, MCMC diagnostics,…

Start the interactive course (quizzes, progress, videos) →

Free forever. No sign-up, no ads. 18 lessons. The full lesson text is below so you can read it right here.

Module 1: Inference as Updating

Build probability and odds updates from explicit events, compare sampling plans and their inclusive tails, and derive a beta-binomial posterior and predictive distribution.

Bayes' Theorem: Base Rates, Odds, and Repeated Evidence

  • Derive a posterior from conditional probabilities and a complete table of expected counts.
  • Convert probabilities to odds, update with likelihood ratios, and interpret positive and negative evidence.
  • Distinguish conditional independence from repeated observation and state the assumptions needed to combine results.
  • Explain how population choice, uncertainty in model inputs, and decision costs limit a numerical conclusion.

One flagged component

A detector flags a manufactured component. How likely is the component to have a defect? The answer depends on both the detector and the population from which the component was selected. Work through this fictional quality-control model before looking at the answer: 1% of components have the defined defect, the detector flags 80% of defective components, and it also flags 9.6% of sound components. These are stipulated teaching values, not measurements of a real device.

Specify the events before calculating

Let D mean that a randomly selected component has the defined defect, and let + mean that the detector flags it. The prior probability is P(D) = 0.01. The sensitivity is P(+ | D) = 0.80; the false-positive rate is P(+ | not D) = 0.096. Specificity is P(- | not D) = 1 - 0.096 = 0.904. A vertical bar means that the information after it is given. P(+ | D) and P(D | +) condition on different groups. [1]

Assume every component is inspected, defect status is measured without error for defining the model, and these operating rates apply to the selected population. In a real investigation, specify the defect criterion, sampling process, and evidence supporting each rate. Neither sensitivity nor specificity alone is the proportion of flagged components that are defective.

Build the denominator with natural counts

Scale the probabilities to 100,000 components. The following are expected counts under the model, not a promise about an actual batch. This scale avoids rounding fractional expected counts.

Component statusFlagged +Not flagged -Total
Defective D8002001,000
Sound, not D9,50489,49699,000
Total10,30489,696100,000

Once a flag is observed, restrict attention to the flagged column. The desired probability is 800 / 10,304 = 0.07764, about 7.76%. The flag increases the probability from 1%, yet most flagged components are sound because the starting sound population is much larger. A conclusion can favor D relative to its prior without making D more probable than not D.

Expected counts among 100,000 fictional components: 800 true positives and 9,504 false positives. Conditioning on a flag gives 800/10,304, or 7.764%.
Expected counts among 100,000 fictional components: 800 true positives and 9,504 false positives. Conditioning on a flag gives 800/10,304, or 7.764%.

Derive Bayes' theorem

The product rule writes the joint probability in two ways: P(D and +) = P(+ | D)P(D) = P(D | +)P(+). The events D and not D partition the population, so P(+) = P(+ | D)P(D) + P(+ | not D)P(not D). Dividing the joint probability by this positive denominator gives Bayes' theorem. [1]

P(D | +) = (0.80 x 0.01) / [(0.80 x 0.01) + (0.096 x 0.99)] = 0.008 / 0.10304 = 0.07764.

The prior is P(D); the likelihood for the observed flag under D is P(+ | D); the marginal probability of the evidence is P(+); and the posterior is P(D | +). Bayes' theorem follows from ordinary probability rules. Bayesian parameter inference extends this calculation by assigning a probability distribution to an unknown parameter. That distribution represents uncertainty within a model, without requiring the parameter to physically change each time it is discussed. [2]

Update odds with likelihood ratios

For 0 < p < 1, odds are o = p / (1 - p), and the inverse conversion is p = o / (1 + o). Odds of 2 mean a probability of 2/3, not 2. For two complementary hypotheses with positive prior probabilities, dividing their Bayes formulas gives posterior odds = prior odds x likelihood ratio. [1]

Here the prior odds are 1/99 and the positive likelihood ratio is LR+ = 0.80 / 0.096 = 25/3. Posterior odds are 25/297; converting back gives 25/322 = 0.07764. A likelihood ratio is evidence relative to the competing hypothesis, not a posterior probability. [1]

A negative result uses LR- = (1 - 0.80) / (1 - 0.096) = 25/113, approximately 0.22124. Multiply the prior odds by 0.22124. Because this ratio is below one, the negative result lowers the odds. Dividing by 0.22124 would reverse the evidence. With a 1% prior, a negative gives probability 25/11212, approximately 0.002230.

The same detector in different populations

Hold sensitivity and false-positive rate fixed while changing the prior defect proportion. This is a controlled mathematical comparison; using operating rates from one real population in another would require justification.

Prior defect probabilityProbability after a flag
0.1%0.8273%
0.5%4.0193%
1%7.7640%
2%14.5349%
10%48.0769%

Moving from a 1% prior to a 10% prior multiplies prior odds by 11, since (1/9) / (1/99) = 11. Posterior odds also increase elevenfold when the likelihood ratio is fixed. Probabilities do not increase in the same proportion because converting odds back to probability is nonlinear.

Repeated evidence needs a joint model

Suppose three results on the same component are independent conditional on D, and also independent conditional on not D, with the same operating rates each time. Then the likelihood for three positive results is 0.80 cubed under D and 0.096 cubed under not D. The prior odds are multiplied by LR+ once per new result.

Evidence under the conditional-independence modelPosterior defect probability
One positive0.07764
Two positives0.41227
Three positives0.85392
One positive, then one negative0.01828

Conditional independence does not mean the results are independent after averaging over unknown defect status. Both results may tend to be positive because they share the same underlying status. What permits multiplication is the explicit independence assumption within each status group.

Consider a counterexample: the second report merely copies the first result. Given the first positive, a second positive has conditional probability one under both hypotheses. Its additional likelihood ratio is 1/1 = 1, so the posterior stays 0.07764. A copied report does not raise it to 0.41227.

In general, update using P(result 2 | D, result 1) / P(result 2 | not D, result 1). Use the simple repeated LR only if these conditional probabilities equal the original operating rates. The joint-likelihood form remains valid when results are dependent. [1]

With conditional independence and unchanged operating rates, one, two, and three positive results give defect probabilities 7.764%, 41.227%, and 85.392%. Exact copies stay at 7.764%.
With conditional independence and unchanged operating rates, one, two, and three positive results give defect probabilities 7.764%, 41.227%, and 85.392%. Exact copies stay at 7.764%.

Separate inference from a decision

The posterior answers a probability question under specified assumptions. It does not determine whether to discard, repair, retest, or release a component. Those actions have different consequences. Later decision lessons compare posterior expected losses. A 50% cutoff is not automatically appropriate.

Real sensitivity, false-positive rates, and defect prevalence are often estimated. Treating uncertain inputs as known suppresses part of the uncertainty. At minimum, examine plausible inputs and report the assumptions; a richer model assigns distributions to uncertain rates. A precise-looking posterior cannot repair an inappropriate population or a mismatched definition of the event.

Common misconceptions

"Sensitivity is the probability of a defect after a flag." Sensitivity conditions on defect status; the posterior conditions on the flag. The denominator changes.

"A second report always supplies new evidence." An exact copy adds none. Use the conditional probability of the new report given what is already known.

Retrieve before checking

Close the table. Write the denominator for P(D | +), convert odds of 1:4 to probability, and explain why a copied flag contributes no new evidence. Predict whether increasing the false-positive rate raises or lowers the posterior while holding everything else fixed.

Check your reasoning

The denominator includes both true positives and false positives. Odds 1:4 give probability 1/5. A copied flag has additional likelihood ratio one. Increasing the false-positive rate increases the denominator without changing the true-positive numerator, so the posterior falls.

Tomorrow, reconstruct the count table without notes. Several days later, change one input and solve again, then compare your answer with the formula. Record which conditioning direction caused an error. These are adjustable practice suggestions, not a measured optimal schedule.

What to carry forward

Key idea: A flag changes the reference group to all flagged components. Build that denominator, then check the same update using odds. Additional reports contribute only the evidence justified by their joint model.

Sources

  1. Orloff, J., and Bloom, J. (2022). Bayesian Updating: Odds. MIT 18.05, sections 2-4. Supports the probability and odds identities. The component examples, count table, and dependence counterexample are original calculations under the stated fictional model.
  2. Orloff and Bloom (2022). Bayesian Updating with Continuous Priors, MIT 18.05, sections 3-9. Parameter uncertainty and normalized posterior densities.
Key terms
Prior probability
Probability assigned before the specified new evidence is incorporated.
Likelihood ratio
Probability or density of the observed evidence under one hypothesis divided by that under another.
Posterior probability
Probability after conditioning on the observed evidence within the stated model.
Marginal probability of evidence
Evidence probability after averaging across the possible hypotheses.
Conditional independence
Factorization of a joint distribution given specified information; here it must hold within each defect-status group.

Likelihood, Sampling Plans, and Stopping Rules

  • Construct and compare likelihoods for a fixed sample and two stopping rules.
  • Derive a maximum likelihood estimate and distinguish relative likelihood, posterior probability, and a p-value.
  • Calculate inclusive one-sided tails with the direction determined by the alternative.
  • State the conditions under which a stopping mechanism cancels from a posterior, and distinguish that result from repeated-sampling error control.

The same counts under three plans

Three laboratories each report nine heads and three tails from a coin with unknown head probability theta. One planned twelve tosses. Another stopped at the third tail. The third stopped at the ninth head. Their reported counts agree, but their sampling plans differ. This lesson calculates exactly what changes and what stays the same under an independent Bernoulli model with a common theta.

Likelihood holds the observed data fixed

For a planned sample of n tosses, Y is the number of heads and P(Y = y | theta) = C(n,y) thetay(1 - theta)n-y. Before collecting data, this is a probability mass function over y for each fixed theta. After observing y = 9 and n = 12, the same expression, regarded as a function of theta, is the likelihood L(theta) = 220 theta9(1 - theta)3.

A likelihood need not integrate to one over the parameter. In this example, the kernel theta9(1 - theta)3 integrates from zero to one to 1/2860, approximately 0.00034965. Including the coefficient 220 makes the integral 1/13, still not one. Constants that do not depend on theta can be omitted when comparing parameter values within this model.

A posterior requires a prior and normalization: p(theta | y) = L(theta)p(theta) / integral L(u)p(u) du, with a finite positive denominator. Simply treating a normalized likelihood as a posterior implicitly selects a flat density in the chosen parameterization. A nonlinear change of parameter generally changes what flat means. [1]

Find the peak and compare parameter values

For 0 < theta < 1, the log likelihood, apart from a constant, is ell(theta) = 9 log(theta) + 3 log(1 - theta). Its derivative is 9/theta - 3/(1 - theta). Setting the derivative to zero gives the maximum likelihood estimate theta-hat = 9/12 = 0.75. The negative second derivative at this point is 9/0.752 + 3/0.252 = 64.

The local quadratic approximation therefore has a scale 1/sqrt(64) = 0.125. This is an approximate standard-error calculation, not an exact credible interval. Small samples and estimates near a boundary can make a symmetric approximation unreliable.

Divide L(theta) by L(0.75) to get relative likelihood. The value at 0.5 is approximately 0.20810: these observed counts have about 4.8054 times as much likelihood at theta = 0.75 as at theta = 0.5. That ratio does not say the two parameter values have those posterior odds unless a corresponding prior model is supplied.

The set with relative likelihood at least 1/8 runs approximately from 0.46070 to 0.93561. The endpoints solve L(theta)/L(0.75) = 1/8 numerically. This is a likelihood support interval at a chosen cutoff. It is not automatically an interval containing 87.5% of posterior probability or a confidence interval with a stated coverage.

The fixed-sample, third-tail, and ninth-head likelihoods have identical relative shapes with a maximum at theta=0.75. With the same uniform prior they give Beta(10,4), whose posterior mass above 0.5 is 0.95386.
The fixed-sample, third-tail, and ninth-head likelihoods have identical relative shapes with a maximum at theta=0.75. With the same uniform prior they give Beta(10,4), whose posterior mass above 0.5 is 0.95386.

Three designs, one likelihood shape

In the stop-at-third-tail design, let N be the total number of tosses. Observing N = 12 requires two tails among the first eleven tosses and a tail on toss twelve. Its probability is C(11,2) theta9(1 - theta)3 = 55 theta9(1 - theta)3. This is a negative-binomial sampling construction. Software conventions differ: some count failures before a target number of successes instead of total trials. [2]

In the stop-at-ninth-head design, observing N = 12 requires eight heads among the first eleven tosses and a head on toss twelve. Its probability is C(11,8) theta9(1 - theta)3 = 165 theta9(1 - theta)3.

Sampling plan and observationCoefficientCommon parameter-dependent kernel
Twelve planned tosses, nine heads220theta9(1 - theta)3
Third tail occurs at toss twelve55theta9(1 - theta)3
Ninth head occurs at toss twelve165theta9(1 - theta)3

These are the same counts, not one identical ordered sequence compatible with all three designs. A sequence stopping at the third tail ends in a tail; one stopping at the ninth head ends in a head. The parameter-dependent likelihoods are nevertheless proportional for the reported observations.

A p-value needs an alternative and a sampling plan

Test the simple null theta = 0.5 against theta > 0.5 using inclusive tails in the direction of more heads. In the fixed sample, large Y favors the alternative. Under the null, P(Y >= 9) = [C(12,9) + C(12,10) + C(12,11) + C(12,12)]/212 = 299/4096 = 0.07300.

When sampling stops at the third tail, a larger N supports a larger head probability. N >= 12 means that the first eleven tosses contain at most two tails. Thus P(N >= 12) = [C(11,0) + C(11,1) + C(11,2)]/211 = 67/2048 = 0.03271. The event includes the observed N = 12.

When sampling stops at the ninth head, a smaller N supports a larger head probability. N <= 12 means that at least nine heads occur in the first twelve tosses. Consequently P(N <= 12) = 299/4096 = 0.07300. The ninth-head and fixed-sample tails happen to agree for this observation and alternative.

Do not substitute P(N < 12) = 67/2048 for the last calculation. It omits the observed stopping time. The difference is P(N = 12) = 165/4096 = 0.04028. In a discrete distribution, changing an inclusive boundary to a strict boundary can materially change the answer. For the opposite alternative under the ninth-head design, the inclusive tail P(N >= 12) is 1981/2048 = 0.96729.

Under a fair coin and alternative theta greater than 0.5, the shaded inclusive tails are Y at least 9 for twelve fixed tosses, N at least 12 for the third-tail rule, and N at most 12 for the ninth-head rule. Their probabilities are 0.07300, 0.03271, and 0.07300.
Under a fair coin and alternative theta greater than 0.5, the shaded inclusive tails are Y at least 9 for twelve fixed tosses, N at least 12 for the third-tail rule, and N at most 12 for the ninth-head rule. Their probabilities are 0.07300, 0.03271, and 0.07300.

What the likelihood principle asserts

The likelihood principle treats proportional likelihoods for the same parameter as equivalent evidence about that parameter. The three examples have identical relative likelihoods and the same maximum likelihood estimate. Their one-sided p-values need not agree because a tail calculation also uses possible observations that did not occur.

With the same uniform Beta(1,1) prior, all three give density 2860 theta9(1 - theta)3, a Beta(10,4) posterior. Its mean is 10/14 = 0.71429 and P(theta > 0.5 | data) = 0.95386. The coefficient in each likelihood cancels between numerator and denominator. The next lesson derives the general beta update. [1][3]

The posterior tail 0.95386 is conditional on the observed data, the Bernoulli model, and the prior. The p-values are null probabilities of the specified tail events under repeated use of the designs. Neither is the probability that the other method is wrong. They answer different questions.

When stopping can be ignored in a posterior

Write the likelihood for the observed record and stopping information as p(record | theta) times g(stop | record, theta). If the second factor does not depend on theta once the relevant record is given, it cancels when normalizing the posterior. A deterministic rule based on the fully observed sequence has this property for a compatible sequence. The prior must also be held fixed in the comparison. [4]

This cancellation does not automatically give a chosen posterior-threshold procedure a 5% false-positive rate at every fixed null parameter. Stopping-rule independence, calibration under a prior predictive distribution, and repeated-sampling error control are distinct properties. Evaluate the property that the study actually needs. [4][5]

Additional information can matter when the recorded data are incomplete. For example, suppose a scientist also observes an unreported instrument reading related to theta and uses it to decide when to stop. Given the published counts alone, stopping may still carry information about theta. Likewise, changing the prior after seeing the outcome invalidates the claim that the same prior and proportional likelihoods were used. Reporting and selection need an explicit model; they do not universally either cancel or fail to cancel.

Common misconceptions

"A p-value is the probability the null is true." These p-values are tail probabilities under a fixed null and design. They are not posterior probabilities.

"The opposite inclusive tail is one minus the first inclusive tail." In a discrete distribution both tails contain the boundary mass. Track strict and inclusive inequalities explicitly.

Retrieve before checking

Without the table, write the three coefficients. For each design, say whether large or small values of its statistic favor theta > 0.5. Explain why the ninth-head p-value includes N = 12. State one extra condition needed before asserting identical posteriors.

Check your reasoning

The coefficients are 220, 55, and 165. Large head counts, large third-tail stopping times, and small ninth-head stopping times favor the alternative. The observed boundary belongs in an inclusive tail. Identical posteriors require the same prior on the same parameter, compatible likelihoods, and a finite positive normalizing integral.

After a day, reconstruct the tail events with words before evaluating them. Later in the week, change the head count or stopping target and check the new boundary. Retain the sampling plan with every numerical p-value.

Putting it together

Remember: A likelihood fixes the observed data and varies the parameter. A p-value also requires a sampling plan and an inclusive tail in the direction of the alternative. Proportional likelihoods and the same prior give the same posterior, subject to the stated observation model.

Sources

  1. Orloff and Bloom (2022). Bayesian Updating with Continuous Priors, MIT 18.05, sections 8-10. Posterior normalization and prediction.
  2. R Core Team. The Negative Binomial Distribution, stats documentation, Details and Arguments. Check the failure-count convention and strict upper-tail convention before using software.
  3. Orloff and Bloom (2022). Conjugate Priors: Beta and Normal, MIT 18.05, sections 3-4.
  4. Hendriksen, de Heide, and Grunwald (2021). Optional Stopping with Bayes Factors. Bayesian Analysis 16(3), 961-989, doi:10.1214/20-BA1234, especially sections 2.1-3.
  5. de Heide and Grunwald (2021). Why Optional Stopping Can Be a Problem for Bayesians. Psychonomic Bulletin & Review 28, 795-812. Distinguishes prior-dependent calibration and practical optional-stopping claims. The three-design arithmetic and support interval are independently derived here.
Key terms
Likelihood
The observed-data probability or density viewed as a function of the model parameter.
Relative likelihood
Likelihood divided by its maximum within the specified parameter space.
Sampling plan
Rules that determine which observations are collected and when collection stops.
Inclusive tail
A tail event that includes the observed value of the statistic.
Likelihood principle
The principle that proportional likelihoods for the same parameter contain equivalent evidence about that parameter.

Beta-Binomial Updating, Prior Sensitivity, and Prediction

  • Derive and normalize the beta posterior for conditionally independent Bernoulli observations.
  • Calculate posterior means, modes, variances, credible intervals, and tail probabilities.
  • Explain the distinct meanings of prior concentration and prior pseudo-count conventions. Check model assumptions and present a reproducible sensitivity analysis.
  • Derive one-trial and multi-trial posterior predictions, retaining parameter uncertainty.

Seven blemishes in twenty-three inspections

Seven of twenty-three inspected components have a specified surface blemish. Treat these as fictional teaching data. A blemish is the event of interest; it is not a catastrophic equipment failure. Estimate the common blemish probability, describe uncertainty, and predict the next inspections. The calculation is simple enough to verify by hand, while its assumptions deserve as much attention as its arithmetic.

Start with a generative model

Let theta be the unknown blemish probability. Conditional on theta, assume the inspection outcomes X1 through X23 are independent Bernoulli(theta) variables. Let Y be their sum. Then Y | theta follows Binomial(23,theta), and the observed-data likelihood is C(23,7) theta7(1 - theta)16.

This model requires a common rate, conditional independence, and a consistent definition and observation of blemishes. Random sampling or a defensible sampling model connects the inspected components to a target population. A convenient binomial formula does not establish those conditions. The sample proportion is 7/23 = 0.30435; it is the maximum likelihood estimate under this model.

The beta family and its normalizing constant

For a > 0 and b > 0, a Beta(a,b) density on 0 < theta < 1 is p(theta) = thetaa-1(1 - theta)b-1 / B(a,b), where B(a,b) is the integral of the numerator over this interval. Equivalently, B(a,b) = Gamma(a)Gamma(b)/Gamma(a+b). For positive integers, Gamma(a) = (a - 1)!, so factorials give the normalizing constant directly. [1][2]

The mean is a/(a+b), the variance is ab/[(a+b)2(a+b+1)], and the interior mode is (a-1)/(a+b-2) when a and b both exceed one. Do not use the interior-mode formula for every beta distribution. Beta(1,1) is uniform; Beta(0.5,0.5) is U-shaped with density increasing without bound near both endpoints. A density height is not a point probability.

Writing a = m kappa and b = (1-m) kappa separates prior mean m from concentration kappa = a+b. The prior variance becomes m(1-m)/(kappa+1). For fixed m, larger kappa concentrates the prior more strongly around m. Beta(2,18) has mean 0.10 and concentration 20. That is a modeling choice requiring evidence, not an engineering target that automatically becomes a defensible prior.

Derive the update by adding exponents

Multiply the beta prior by the binomial likelihood. Ignoring factors constant in theta, p(theta | y) is proportional to thetaa+y-1(1 - theta)b+n-y-1. This is the kernel of Beta(a+y,b+n-y). Recognizing its family supplies the normalization rather than eliminating the need to normalize. [2]

theta | y ~ Beta(a + y, b + n - y). The normalized density divides the kernel by B(a+y,b+n-y). The marginal probability of the observed count is C(n,y) B(a+y,b+n-y)/B(a,b). This last expression retains the binomial coefficient because it is a probability over observed counts, not merely a likelihood shape.

A prior family with a posterior in the same family is called conjugate for the specified likelihood. Conjugacy is a computational convenience. Bayesian analysis also works with nonconjugate models, often using numerical integration or simulation.

Summarize the Beta(8,17) posterior

A Beta(1,1) prior and seven blemishes among twenty-three inspections give Beta(1+7,1+16) = Beta(8,17). The mean is 8/25 = 0.32000; the mode is 7/23 = 0.30435; and the standard deviation is sqrt[136/(625 x 26)] = 0.09148. The mode agrees with the maximum likelihood estimate because this particular prior density is constant in theta.

The 2.5th and 97.5th percentiles are approximately 0.15630 and 0.51095. Thus the equal-tail 95% credible interval is [0.15630,0.51095]. Given the observed data, model, and prior, its posterior probability is 0.95. It is not a prediction that 95% of individual outcomes fall in that interval, nor does this definition establish 95% coverage for each fixed theta in repeated sampling. [3]

Integrating the same posterior gives P(theta > 0.5 | y) = 0.031957 and P(theta < 0.10 | y) = 0.001684. These are model-based probability statements, not declared safety thresholds. A continuous beta posterior assigns probability zero to any one exact value of theta even when its density is high there.

Check prior sensitivity explicitly

PriorPosteriorPosterior meanEqual-tail 95% interval
Beta(1,1)Beta(8,17)0.320000.15630 to 0.51095
Beta(0.5,0.5)Beta(7.5,16.5)0.312500.14772 to 0.50684
Beta(2,18)Beta(9,34)0.209300.10296 to 0.34118

The first two choices have the same prior mean but different shapes and concentrations. The third prior has a lower mean and a larger concentration. Its posterior remains materially different after these twenty-three inspections. Compare the full distributions and the quantities relevant to the intended use, not only the means.

For n > 0, the posterior mean can be written as [(a+b)/(a+b+n)] x [a/(a+b)] + [n/(a+b+n)] x [y/n]. Under Beta(2,18), this is (20/43)(0.10) + (23/43)(7/23) = 9/43 = 0.20930. Under the uniform prior, it is (2/25)(0.50) + (23/25)(7/23) = 0.32000.

In this identity, a+b behaves as an effective prior sample size for the posterior mean. It is a useful convention within this family, not a universal measure of information. The alternative statement that the prior resembles a-1 successes and b-1 failures refers to exponents relative to a uniform baseline. It cannot represent an actual nonnegative dataset when a or b is below one. Keep these conventions separate.

Equal concentrations do not imply equal practical influence for every target or dataset. Prior location, tail shape, disagreement with data, and the quantity being estimated also matter. A uniform density is not an absence of assumptions: under the log-odds transformation eta = log[theta/(1-theta)], a uniform theta implies density exp(eta)/(1+exp(eta))2 for eta.

Three prior densities and their updated posteriors for 7 events among 23 trials. Posterior means are 0.32000, 0.31250, and 0.20930. The stronger Beta(2,18) prior produces a visibly lower posterior rate.
Three prior densities and their updated posteriors for 7 events among 23 trials. Posterior means are 0.32000, 0.31250, and 0.20930. The stronger Beta(2,18) prior produces a visibly lower posterior rate.

Sequential updating without double-counting

Suppose the first ten inspections contain three blemishes, and the remaining thirteen contain four. The first update is Beta(1+3,1+7) = Beta(4,8). Using that posterior as the next prior gives Beta(4+4,8+9) = Beta(8,17), exactly the batch result.

Each observation enters once. Adding all twenty-three observations again after the first update would double-count the first ten. Order is irrelevant here because the conditional likelihood is a product of the same Bernoulli factors. If the rate changes over time, or the observation mechanism changes, this common-rate model needs revision. Sequential algebra alone supplies no general guarantee about the error rate of a stopping decision.

Prediction averages over uncertainty

Let Xnew be one additional conditionally independent inspection from the same modeled population. P(Xnew = 1 | y) = integral theta p(theta | y) dtheta = E(theta | y) = 8/25 = 0.32. The predictive probability averages the conditional Bernoulli probability over the posterior. [4]

For two new inspections, P(both blemished | y) = E(theta2 | y) = 8 x 9/(25 x 26) = 0.11077. Using 0.322 = 0.10240 would omit the uncertainty in their shared rate. The difference, 0.008369, equals the posterior variance of theta. The future indicators are independent conditional on theta but positively dependent after theta is integrated out.

For m future inspections, their total K has a beta-binomial predictive distribution: P(K=k | y) = C(m,k) B(A+k,B+m-k)/B(A,B), where A=a+y and B=b+n-y. This follows by integrating the binomial probability against the beta posterior. For m=10, A=8, B=17, E(K | y)=10 x 8/25=3.2. Its variance is mAB(A+B+m)/[(A+B)2(A+B+1)] = 2.92923. A binomial with the rate fixed at 0.32 instead has variance 2.176.

The multi-trial predictive count has extra variance from rate uncertainty. For a single binary future observation, however, the predictive law is exactly Bernoulli with probability equal to the posterior mean. There is no additional one-trial dispersion beyond that Bernoulli law. State which predictive quantity is being compared.

For ten future inspections, both predictive counts have mean 3.2. Integrating the Beta(8,17) rate posterior gives variance 2.92923 instead of the binomial variance 2.176 from fixing the rate at 0.32.
For ten future inspections, both predictive counts have mean 3.2. Integrating the Beta(8,17) rate posterior gives variance 2.92923 instead of the binomial variance 2.176 from fixing the rate at 0.32.

Reproduce the answer and examine the model

In R, use qbeta(c(0.025,0.975),8,17) for the interval and pbeta(0.5,8,17,lower.tail=FALSE) for the upper tail. In Python with SciPy, the corresponding calls are beta.ppf([0.025,0.975],8,17) and beta.sf(0.5,8,17). Check parameter order and use the unrounded values for later calculations. Numerical integration of the normalized density provides an independent check. [5][6]

Before using the result for a new production setting, inspect possible changes in material, temperature, machine, and detection procedure. If blemish risk depends on temperature, a constant theta cannot directly predict a new temperature outside the observed setting. Retain observations with and without blemishes when studying a relationship. Record the denominator, selection procedure, and covariates rather than keeping only the interesting cases.

Common misconceptions

"Uniform means no assumptions." Uniformity specifies a density on a chosen parameter scale and changes under nonlinear reparameterization.

"The next two outcomes are marginally independent because the model says independent." Independence was conditional on theta. Integrating a shared uncertain rate generally creates dependence.

Retrieve before checking

Starting from the two kernels, derive the updated exponents. Explain why the posterior mean and mode differ. Predict which is larger: E(theta2 | y) or E(theta | y)2. State when they would be equal.

Check your reasoning

The exponents become a+y-1 and b+n-y-1. The mean averages the posterior, whereas the mode locates its peak, so they need not coincide. E(theta squared) equals E(theta) squared plus Var(theta). Equality holds only when theta has zero posterior variance.

Tomorrow, redo the update with a different prior. A few days later, solve the practice problem without consulting the formula, then explain one assumption that would require a different likelihood. Keep an error log that distinguishes arithmetic, interpretation, and model errors.

Where this leaves us

What matters here: Add events and non-events to the matching beta parameters, retain the distribution rather than only its mean, and average predictions over that uncertainty. Then check whether the common-rate inspection model fits the population and setting.

Sources

  1. NIST/SEMATECH. Beta Distribution, e-Handbook section 1.3.6.6.17. Density, beta integral, mean, interior mode, and standard deviation.
  2. Orloff and Bloom (2022). Conjugate Priors: Beta and Normal, MIT 18.05, sections 3-4. Conjugate updating; the general positive-real beta formula is used here.
  3. Orloff and Bloom (2022). Probability Intervals, sections 2-3. Credible intervals and quantiles.
  4. Orloff and Bloom (2022). Bayesian Updating with Continuous Priors, section 10. Predictive averaging. All numerical examples and the beta-binomial count derivation are independently calculated from the stated model.
  5. R Core Team. The Beta Distribution, stats documentation. qbeta, pbeta, and tail conventions.
  6. SciPy contributors. scipy.stats.beta. Shape parameters, ppf, and sf.
Key terms
Conjugate prior family
A prior family whose posterior belongs to the same family for a specified likelihood.
Beta concentration
The sum a+b, which controls beta variance at fixed mean and weights the prior in the posterior-mean identity.
Credible interval
An interval with a specified posterior probability, conditional on the data, prior, and model.
Posterior predictive distribution
A future-data distribution obtained by averaging over the posterior uncertainty in parameters.
Prior sensitivity
How conclusions change under substantively plausible alternative prior specifications.

Module 2: Conjugate Models and the Prior

Derive conjugate updates and predictive distributions, evaluate priors on the observation scale, and compare interval probability statements with explicit assumptions and worked calculations.

Conjugate Models: Rates, Measurements, and Uncertainty

  • Derive a normalized gamma posterior for Poisson counts with unequal exposures, keeping rate and scale conventions explicit.
  • Derive the negative-binomial predictive distribution and distinguish rate uncertainty from future count variation.
  • Derive normal-mean updating with known measurement variance and distinguish posterior uncertainty from prediction and calibration error.
  • Compare model-specific weights, identify the limits of conjugacy, and use a real dataset to question the observation model.

Seventeen events, nine hours, and two different denominators

A fictional monitoring system records counts of 1, 4, 7, and 5 events during windows lasting 1, 2, 3, and 3 hours. There are 17 events in 9 hours. Dividing by the four windows would give 4.25 events per window, but a window is not a fixed amount of observation. The rate estimate is 17/9 = 1.88889 events per hour. The exposure belongs in the denominator.

We will combine these counts with a stated prior, then predict another observation period. A second example uses repeated mass measurements. Both examples have conjugate priors: updating leaves the posterior in the same distribution family. Their weights have different meanings. A rate model weights exposure; the normal model below weights inverse variance. Conjugacy makes calculations manageable, while the observation model determines what they mean.[1][3]

Derive the rate update with exposure

Let Yi be the count during exposure ti hours. Assume the counts are independent conditional on a common rate lambda, with Yi | lambda distributed as Poisson(ti lambda). Write S = sum Yi and T = sum ti. Multiplying the count probabilities gives

L(lambda) = [product tiyi/yi!] lambdaS exp(-T lambda).

The bracketed factor does not depend on lambda. It can be omitted when normalizing this posterior, although it remains part of the sampling probability. Different durations are allowed; a changing event rate, missed events, or dependence between windows requires additional modeling. Aggregating into S and T is sufficient for this common-rate likelihood, but the individual observations remain useful for checking it.

Use Gamma(a,b) with shape a and rate b, where a > 0 and b > 0. Its density is ba lambdaa-1 exp(-b lambda)/Gamma(a) for lambda > 0. Its mean is a/b and variance is a/b2. The scale parameter is 1/b, not b.[1]

Multiplication adds exponents: lambdaa-1 times lambdaS becomes lambdaa+S-1, and the exponential becomes exp[-(b+T)lambda]. To normalize, integrate that kernel over positive lambda. Substitution u = (b+T)lambda gives the integral Gamma(a+S)/(b+T)a+S. Therefore

lambda | y ~ Gamma(a+S, b+T).

For the stated teaching prior Gamma(3,4), the mean is 0.75 events per hour and the standard deviation is sqrt(3)/4 = 0.43301. The posterior is Gamma(20,13), with mean 1.53846, standard deviation 0.34401, and equal-tailed 95% interval [0.93973, 2.28237] events per hour. These are calculations under the fictional model, not estimates of an actual monitoring system.

A Gamma(3,4) shape-rate prior updates with 17 events in nine hours to Gamma(20,13). The posterior mean is 1.53846 events per hour and the shaded equal-tailed 95% interval is [0.93973,2.28237].
A Gamma(3,4) shape-rate prior updates with 17 events in nine hours to Gamma(20,13). The posterior mean is 1.53846 events per hour and the shaded equal-tailed 95% interval is [0.93973,2.28237].

Read the weights in their own units

For b > 0 and T > 0, rewrite the posterior mean as (b/(b+T))(a/b) + (T/(b+T))(S/T). Here the prior weight is 4/13 and the data weight is 9/13. The check is (4/13)(0.75) + (9/13)(17/9) = 20/13. The coefficient b has the same units as exposure. It is not the prior precision, which would be b2/a in this parameterization.

Calling b an equivalent exposure describes this mean identity. It does not prove that the prior came from b hours of historical observations or that b measures all of its influence. The exponent also matters: interpreting a or a-1 as a prior event count depends on the baseline prior used for that analogy. Record the actual density and the evidence behind it instead of inventing a historical dataset.

Sequential updating gives the same result when observations are used once and the common-rate model stays fixed. Six events in the first three hours change Gamma(3,4) to Gamma(9,7); eleven more events in six more hours give Gamma(20,13). Reusing the first batch in the second update would count its evidence twice.

A flat positive-rate prior is a different, improper object, with density proportional to 1. With T > 0 it gives the proper posterior Gamma(S+1,T). The notation Gamma(1,0) sometimes describes its kernel, but it is not a normalized gamma distribution. Do not pass a zero rate to a random-number generator and treat the output as prior draws.

Predict counts by integrating the uncertain rate

Let K count events during a new exposure t > 0. Given lambda, K is Poisson(t lambda). If the posterior is Gamma(a*,b*), average that Poisson mass over the posterior. Combining its powers with the gamma density and applying the same gamma integral gives

P(K=k | y) = Gamma(a*+k)/[Gamma(a*) k!] [b*/(b*+t)]a* [t/(b*+t)]k, k = 0,1,2,... .

This is a negative-binomial distribution with R's size = a* and prob = b*/(b*+t). Under that convention the count has mean a*(1-prob)/prob. It is a Poisson-gamma mixture; the word "success" in a library's parameter description does not change the physical interpretation of these event counts.[2]

The law of total expectation gives E(K | y) = t a*/b*. The law of total variance gives Var(K | y) = t a*/b* + t2 a*/b*2. The first term is expected Poisson variation conditional on the rate. The second is variation from the uncertain rate shared by future observations.

For Gamma(20,13) and two future hours, the predictive mean is 3.07692 and variance is 3.55030. The chance of zero is (13/15)20 = 0.05715, versus exp(-40/13) = 0.04610 when the rate is fixed at its posterior mean. The predictive chance of at least five events is 0.20848. A credible interval for lambda, measured in events per hour, is not a predictive interval for K, an integer count.

For a future two-hour exposure, integrating Gamma(20,13) gives a negative-binomial count distribution with mean 3.07692 and variance 3.55030. Fixing the rate at its posterior mean gives the same count mean but variance 3.07692 and a different zero-count probability.
For a future two-hour exposure, integrating Gamma(20,13) gives a negative-binomial count distribution with mean 3.07692 and variance 3.55030. Fixing the rate at its posterior mean gives the same count mean but variance 3.07692 and a different zero-count probability.

Complete the square for a normal mean

Now suppose observations Yi are independent normal measurements with mean mu and known variance sigma2. The likelihood for mu has kernel exp[-n(mu-ybar)2/(2 sigma2)]. Give mu a normal prior with mean m0 and variance v0. The combined exponent contains

(mu-m0)2/v0 + n(mu-ybar)2/sigma2.

Expand both squares. The coefficient of mu2 is 1/v0 + n/sigma2; the coefficient of -2mu is m0/v0 + n ybar/sigma2. Completing the square gives a normal posterior with

v* = 1/(1/v0 + n/sigma2), and m* = v*(m0/v0 + n ybar/sigma2).

The relevant data precision is n/sigma2, the inverse variance of the sample mean. It is not 1/sigma2, the precision of one measurement. These formulas require the specified known sampling variance and the normal likelihood and prior.[3]

In a fictional balance example, take m0 = 250.0 mg, prior standard deviation 0.3 mg, known measurement standard deviation 0.4 mg, n = 16 and ybar = 250.6 mg. Prior precision is 11.11111 per mg squared; data precision is 100. The posterior is normal with mean 250.54000 mg, variance 0.00900 mg squared, and standard deviation 0.09487 mg. The data receive weight 0.9. The equal-tailed 95% interval for mu is [250.35406, 250.72594] mg.

One future measurement has predictive variance sigma2 + v* = 0.16900 mg squared, so its standard deviation is 0.41110 mg. The mean of four future independent measurements, conditional on the same mu, instead has predictive variance sigma2/4 + v* = 0.04900. Prediction must include the measurement noise that a posterior interval for mu omits.

In a fictional balance model, a prior mean of 250 mg and SD 0.3 mg combines with 16 readings averaging 250.6 mg and known individual SD 0.4 mg. Precision weighting gives a posterior mean of 250.54 and SD 0.09487. The dashed likelihood is normalized as a function of mu for plotting.
In a fictional balance model, a prior mean of 250 mg and SD 0.3 mg combines with 16 readings averaging 250.6 mg and known individual SD 0.4 mg. Precision weighting gives a posterior mean of 250.54 and SD 0.09487. The dashed likelihood is normalized as a function of mu for plotting.

Uncertainty need not shrink after every possible dataset

For the known-variance normal model above, adding observations reduces v*. That statement does not extend to every posterior variance. Consider a Poisson rate with Gamma(1,1) prior variance 1. Observing nine events in one exposure unit gives Gamma(10,2), whose variance is 10/4 = 2.5. The posterior has moved to a higher-rate region and its absolute variance has increased.

With a proper prior and finite second moment, total variance instead says Var(lambda) = E[Var(lambda | Y)] + Var[E(lambda | Y)], with expectations over the prior predictive distribution of Y. The posterior variance decreases on average under that joint model. For this one-unit Gamma(1,1) example, E(Y) = 1 and E[(1+Y)/4] = 0.5. The average result does not prohibit an increase for the realized count nine.

Use the real measurement record to question the model

R's morley dataset contains Michelson speed-of-light measurements from 1879: five experiments, each with twenty consecutive runs. Its Speed variable is expressed in km/s after subtracting 299000. Recomputing all 100 values gives mean 852.4 and sample standard deviation 79.01055. The five experiment means are 909.0, 856.0, 845.0, 820.5, and 831.5.[4]

For an algebra illustration only, stipulate a prior N(800,202) and treat sigma = 79 as known. These are teaching assumptions, not a reconstruction of Michelson's beliefs or a claim that the variance was known. The calculation gives posterior mean 845.32774, standard deviation 7.34757, and interval [830.92678, 859.72870] in the coded units.

The SI defining speed of light in vacuum is exactly 299792458 m/s, or 792.458 in that coding.[5] It lies outside the illustrative interval. This comparison does not identify the historical cause of the discrepancy. The pooled iid normal model omits experiment structure, trends, and calibration effects. A common measurement offset cannot be separated from the true value using repeated readings alone without additional assumptions or external calibration.

Define the target carefully. If mu means the expected reported measurement, equating it with the physical constant adds an accuracy assumption. More repeated readings can estimate a biased measurement mean precisely. Check the experiment labels and run order, inspect residuals, and obtain calibration information before interpreting the interval as uncertainty about the physical constant itself.

The 100 Michelson measurements in R morley are plotted in run order across five experiments. Group means are 909,856,845,820.5,and 831.5 in km/s minus 299000. The modern exact speed-of-light reference is 792.458 on this coded scale. Group structure and the mismatch prompt model checking without establishing the cause.
The 100 Michelson measurements in R morley are plotted in run order across five experiments. Group means are 909,856,845,820.5,and 831.5 in km/s minus 299000. The modern exact speed-of-light reference is 792.458 on this coded scale. Group structure and the mismatch prompt model checking without establishing the cause.

Compare the models and reproduce the calculation

ModelPosterior mean weightsPredictive uncertainty
Beta-binomialPrior concentration a+b and number of trials nBeta-binomial for a future count
Gamma-PoissonPrior rate parameter b and total exposure TNegative binomial for a future count
Normal mean, known sigmaPrior precision 1/v0 and sample-mean precision n/sigma2Normal with measurement variance plus posterior mean variance

Each row has its own model and units. Conjugate families are useful examples of tractable updating, not a claim that these are the only analytically solvable models. When a model is inadequate, convenient arithmetic is not a reason to keep it.

For the gamma interval in R, use qgamma(c(0.025,0.975), shape=20, rate=13).[1] In SciPy use gamma.ppf([0.025,0.975], a=20, scale=1/13).[6] The SciPy calculations and independent integrals were executed for this lesson; the R call is checked against documentation. Always label shape-rate or shape-scale when recording a gamma distribution.

Common misconceptions

"A window count is already a rate." A count needs its exposure. Four windows of unequal duration are not four equal observation units.

"Every conjugate update adds precisions." That is the normal-mean calculation here. Gamma exposure weights and beta concentration weights have different units and interpretations.

"A narrow posterior establishes accuracy." Its width is conditional on the model, input assumptions, and target definition. Repetition alone does not identify a shared offset.

Retrieve before checking

Close the formulas. Explain why total exposure enters the gamma rate parameter, why a future count has more variance than a fixed-rate Poisson count, and which term a future normal measurement adds to v*. Then give the explicit counterexample to "posterior variance always decreases."

Check your reasoning

Exposure multiplies lambda in exp(-T lambda), so it adds to the gamma rate. Mixing over lambda contributes t squared times Var(lambda | y) to count variance. A new normal reading adds sigma squared to v*. Gamma(1,1) followed by nine events in one unit gives Gamma(10,2): variance rises from 1 to 2.5, although its prior-predictive average decreases.

What to carry forward

Key idea: derive the update from the likelihood, label every parameter and unit, and integrate parameter uncertainty when predicting. The formulas answer questions inside a specified model; a real measurement record is also evidence with which to examine that model.

Sources

  1. R Core Team. (2026 development documentation). The Gamma Distribution, stats 4.6.0. Density, moments, rate versus scale, and qgamma. Read the source
  2. R Core Team. (2026 development documentation). The Negative Binomial Distribution, stats 4.6.0. Gamma-Poisson mixture and size/prob parameterization. Read the source
  3. Orloff, J., and Bloom, J. (2022). Conjugate priors: Beta and normal. MIT 18.05, sections 4 and 7. Normal likelihood with known variance and normal-prior updating. Read the source
  4. R Core Team. (2026 development documentation). Michelson Speed of Light Data, datasets 4.6.0. Five experiments, twenty runs each, and measurement coding. The lesson recomputes the summaries from the original R data file. Read the source
  5. Bureau International des Poids et Mesures. SI base unit: metre. Exact defining value of the speed of light in vacuum. Read the source
  6. SciPy contributors. scipy.stats.gamma. Shape a, scale equal to the reciprocal rate, and quantile method ppf. Read the source
Key terms
Exposure
The amount of observation opportunity, such as hours, that scales an event count model.
Conjugacy
A prior family is conjugate when the stated likelihood produces a posterior in that family.
Gamma rate parameter
The positive coefficient b in exp(-b lambda); its reciprocal is the gamma scale.
Precision
The reciprocal of a variance, with the corresponding inverse-squared units.
Posterior predictive distribution
The distribution of new observations obtained by averaging their conditional distribution over the posterior.
Calibration error
An error in relating reported measurements to the target quantity; a shared offset is not removed simply by averaging repetitions.

Choosing Priors: Scale, Propriety, and Predictive Checks

  • Compare posterior means, tail probabilities and bounds under explicitly stated proper priors, including a model with a point mass.
  • Transform prior densities correctly and derive the one-parameter Jeffreys rule and its binomial example.
  • Determine posterior propriety for an improper prior and distinguish a formal kernel from a normalized distribution or a limiting proper model.
  • Design prior predictive checks and a documented sensitivity analysis that reflect the target, units, likelihood and available evidence.

Zero blemishes does not settle the rate

A fictional inspection finds no surface blemishes among ten components. Under a common independent Bernoulli model, the likelihood for the blemish probability theta is (1-theta)10. Its maximum occurs at theta = 0. That is an estimate, not proof that the process can never produce a blemish. Nor does the calculation prove that a structural zero rate is impossible. Those are different questions about uncertainty and model support.

Three proper priors illustrate sensitivity. Beta(1,1) is uniform on the probability scale. Beta(0.5,0.5) is the binomial Jeffreys prior. Beta(2,18) is a stated example with mean 0.1 and concentration 20. It has no claimed historical justification here; an applied analysis would have to supply one. Updating adds zero to the first shape and ten to the second.

PriorPosteriorMean95% upper credible boundP(theta > 0.2 | data)
Beta(1,1)Beta(1,11)0.083330.238400.08590
Beta(0.5,0.5)Beta(0.5,10.5)0.045450.170770.03239
Beta(2,18)Beta(2,28)0.066670.153390.01277

The upper bound is the posterior 0.95 quantile: it leaves 5% above it. It is not the upper endpoint of a two-sided equal-tailed 95% interval, which uses the 0.975 quantile. For Beta(1,11), those two numbers are 0.23840 and 0.28491. Compute quantiles, for example, with R's qbeta(0.95,1,11); the positive-shape beta density and quantile convention are documented in the R reference.[4]

The means alone hide a useful distinction: Beta(2,28) has a higher posterior mean than Beta(0.5,10.5), yet a lower 95% upper bound and less probability above 0.2. Their shapes differ. Choose the quantities relevant to the question before deciding that two analyses agree. A prior's influence is a property of the prior, likelihood, observations, and target together.[2]

Posterior CDFs after zero events in ten trials under three stated priors. Their one-sided 95% bounds are 0.23840,0.17077,and 0.15339. The Beta(2,28) posterior has a larger mean than Beta(0.5,10.5) but a smaller upper bound.
Posterior CDFs after zero events in ten trials under three stated priors. Their one-sided 95% bounds are 0.23840,0.17077,and 0.15339. The Beta(2,28) posterior has a larger mean than Beta(0.5,10.5) but a smaller upper bound.

Support is part of the prior

Each continuous beta prior assigns probability zero to the single point theta = 0, even when its density is largest near that boundary. After these finite observations, the continuous posterior still gives that point probability zero. A high density near zero is not a positive probability of an exactly zero rate.

If a structural zero is a substantive possibility, it needs an explicit model. As a mathematical illustration, assign prior probability one half to theta = 0 and one half to a uniform distribution over positive theta. Zero blemishes in ten has probability 1 under the point hypothesis and probability integral01(1-theta)10 dtheta = 1/11 under the continuous part. Bayes' rule makes the posterior point mass (1/2)/[(1/2)+(1/2)(1/11)] = 11/12. The remaining mass is on Beta(1,11). Changing the prior point mass changes this answer.

This example is not a reason to add point masses to every analysis. It shows why the model must represent the question. A purely continuous prior cannot answer a point-hypothesis question by reporting the density at that point.

Check that a posterior exists

The formal Haldane prior has kernel 1/[theta(1-theta)] on 0 < theta < 1. Its integral diverges, so it is improper. For y events in n trials, its posterior kernel is thetay-1(1-theta)n-y-1. The integral is finite exactly when y > 0 and n-y > 0. Both kinds of outcome must have occurred.

For zero out of ten, the kernel is theta-1(1-theta)9. Near zero it behaves like 1/theta, whose integral diverges. There is no normalized posterior density and therefore no posterior mean, quantile, or valid posterior predictive distribution from this kernel. Writing Beta(0,10) does not repair it.

Distinguish this calculation from taking a limit of proper models. Beta(epsilon,epsilon) with epsilon > 0 gives a proper Beta(epsilon,10+epsilon) posterior. As epsilon tends to zero, that family concentrates at zero. The limiting probability measure and the nonintegrable density kernel at epsilon = 0 are different objects. Some software defines boundary-parameter distributions as such limits; its output cannot establish that the formal improper posterior normalized.[4]

With an improper prior, show that the posterior normalizing integral is finite and positive. A numerical routine returning finite-looking numbers is not a proof. There is also no ordinary prior predictive simulation from an unnormalizable prior. Multiplicative constants in improper priors can cancel in a posterior yet remain problematic in marginal likelihoods used for model comparison.[1]

Transform the density, not only the parameter name

Suppose theta is uniform on (0,1), and define psi = theta2. Since theta = sqrt(psi), the change-of-variables rule gives p(psi) = 1/(2 sqrt(psi)) on (0,1). The singularity at zero is integrable: its integral over (0,1) is 1. Consequently P(psi < 0.25) = P(theta < 0.5) = 0.5. A separately chosen uniform prior on psi gives 0.25 instead.

Both are legitimate proper priors, but they are different probability measures. Changing coordinates for one prior preserves its event probabilities. Choosing a new uniform density on the new coordinate changes the prior. Uniformity cannot hold under every nonlinear transformation.[1]

For the log-odds eta = log[theta/(1-theta)], the inverse is theta = 1/(1+exp(-eta)) and its derivative is theta(1-theta). A uniform theta therefore induces the logistic density p(eta) = exp(eta)/(1+exp(eta))2. Its mode is eta = 0, but a density's mode changes with the coordinate and the reference measure. It does not make theta = 0.5 more probable than another exact point under the original continuous uniform prior.

The probability of -1 < eta < 1 is 0.73106-0.26894 = 0.46212. A constant density over the entire real eta line cannot be normalized. Transforming that improper kernel gives the Haldane kernel on theta. A proper uniform eta on a specified finite interval is a third, different model whose support and bounds must be stated.

If theta is uniform on zero to one, psi=theta squared has CDF sqrt(psi), so P(psi<0.25)=0.5. Making psi uniform instead gives P(psi<0.25)=0.25 and a different distribution for theta. A coordinate change of one probability model preserves event probabilities.
If theta is uniform on zero to one, psi=theta squared has CDF sqrt(psi), so P(psi<0.25)=0.5. Making psi uniform instead gives P(psi<0.25)=0.25 and a different distribution for theta. A coordinate change of one probability model preserves event probabilities.

Derive the Jeffreys rule and state its limits

For a regular one-parameter sampling model, the Jeffreys rule sets the prior proportional to sqrt(I(theta)), where I is expected Fisher information. Under a smooth one-to-one reparameterization theta = g(psi), information transforms as Ipsi = Itheta [dtheta/dpsi]2. Its square root acquires the absolute Jacobian needed for a density. Thus applying the rule before or after the transformation gives the same prior measure, when the rule is defined.[1]

For n fixed Bernoulli trials, log likelihood is y log(theta)+(n-y)log(1-theta). Taking the negative expected second derivative, with E(y)=n theta, gives I(theta)=n/[theta(1-theta)]. The factor sqrt(n) is constant in theta. The resulting density is proportional to theta-1/2(1-theta)-1/2, the proper Beta(0.5,0.5) distribution. That derivation justifies the formal rule for this sampling model; it does not establish that the prior matches knowledge about a particular process.

Regular model and parameterInformationOne-parameter Jeffreys kernel
Binomial probability thetan/[theta(1-theta)]1/sqrt(theta(1-theta)), proper after normalization
Poisson rate lambda, exposure TT/lambdalambda-1/2, improper on positive lambda
Normal mean mu, known sigman/sigma2Constant on the real line, improper
Normal sigma, known mu2n/sigma21/sigma on positive sigma, improper

In several dimensions the general Jeffreys rule uses the square root of the determinant of the information matrix. It need not match applying separate one-parameter rules. For a normal model with both mu and sigma unknown, the general rule has density proportional to 1/sigma2 relative to dmu dsigma. A common alternative location-scale reference prior is proportional to 1/sigma relative to those same coordinates. They are different priors. Specify the coordinates and joint density instead of using "Jeffreys prior" without qualification.[1]

Separate the purpose of a prior from whether it is proper

An informative prior encodes substantial domain evidence or restrictions. A weakly informative prior regularizes an analysis while allowing a deliberately broad range relative to the problem. A formal reference rule supplies a reproducible convention for a stated model and inferential goal. These descriptions concern motivation or influence. Proper versus improper asks a separate mathematical question: does the density integrate to one after normalization?

A proper prior may be informative, weakly informative, or selected by a formal rule. An informative prior is not automatically justified, and a proper prior can still be poorly chosen. To assess a prior, name its source, units, parameter scale, support, and the quantities it implies. A single equivalent-sample-size number cannot summarize every tail, dependence, or prediction.[2]

Inspect predictions before seeing the new sample

A prior predictive distribution averages the sampling model over a proper prior: p(y) = integral p(y | theta) p(theta) dtheta. To simulate it, draw a parameter value from the prior, draw a complete dataset conditional on that value, and repeat. Compare features of those datasets with substantive knowledge. Drawing a fresh rate for every trial would instead define a different model when the intended dataset shares one rate.[3]

For twenty Bernoulli inspections with a common theta, the prior predictive count K is beta-binomial. Its mass is C(20,k) B(a+k,b+20-k)/B(a,b). Under Beta(1,1), every count from 0 through 20 has probability 1/21. Under Beta(0.5,0.5), the probability of zero is 0.12537 and the same holds for twenty. Under Beta(2,18), the expected count is 2, the probability of zero is 0.23077, and P(K >= 10) is 0.00219. These differences can be easier to evaluate than an abstract prior density.

A useful check starts with a concrete question: would ten or more blemishes in twenty inspections contradict what is known about this particular process? If so, the first two priors deserve attention. If such batches occur, the third may be too restrictive. A check identifies tension with the specified context; it does not mechanically select the correct prior. Prior predictive checks are designed to expose implications of the joint model, not to make prior simulations mimic the observed sample exactly.[3]

Exact beta-binomial prior predictive probabilities for twenty trials under three proper priors. The common rate is drawn once per simulated dataset. Beta(1,1) gives a uniform count distribution; Beta(0.5,0.5) emphasizes extreme counts; Beta(2,18) predicts a mean of two events.
Exact beta-binomial prior predictive probabilities for twenty trials under three proper priors. The common rate is drawn once per simulated dataset. Beta(1,1) gives a uniform count distribution; Beta(0.5,0.5) emphasizes extreme counts; Beta(2,18) predicts a mean of two events.

Scaling a regression coefficient changes its implications

Consider the deliberately simple model logit(p) = beta x, with intercept fixed at zero. At x = 1, p < 0.01 or p > 0.99 exactly when |beta| > log(99) = 4.59512. If beta has a N(0,102) prior, that event has probability 0.64587. Under N(0,1), it has probability about 0.000004325. A wide normal prior on the log-odds scale can put considerable mass near nearly deterministic predictions.

Neither result proves a universal default. The conclusion depends on the predictor units, its relevant range, the intercept, other coefficients, and the domain. Standardizing a predictor does not settle all of those choices. The N(0,1) prior's 95% odds-ratio range, approximately 0.14 to 7.10 for a one-unit contrast, does not cover every real effect. Large finite odds ratios are not mathematically impossible. Evaluate the predictions where the model will be used.[2]

For the stipulated model logit(p)=beta with predictor one and intercept zero, extreme predicted probabilities below 0.01 or above 0.99 occur when absolute beta exceeds log(99). Normal coefficient SD one puts probability 0.000004325 there; SD ten puts probability 0.64587. Predictor scaling and the model context matter.
For the stipulated model logit(p)=beta with predictor one and intercept zero, extreme predicted probabilities below 0.01 or above 0.99 occur when absolute beta exceeds log(99). Normal coefficient SD one puts probability 0.000004325 there; SD ten puts probability 0.64587. Predictor scaling and the model context matter.

Write a sensitivity analysis that someone can reproduce

  1. Specify the target and likelihood, including population, units, detection, dependence and exposure.
  2. Record a primary prior with its evidence, date, support and parameterization. Distinguish external data from observations already used in the likelihood.
  3. Choose plausible alternatives that vary meaningful features, such as location, concentration, tails, or point mass, rather than only convenient parameter values.
  4. Inspect prior predictive datasets and document any revisions. If the observed data motivated a revision, say so and account for how information was reused.
  5. Fit each stated model and compare the quantities the decision or scientific question requires: means, intervals, tail probabilities, predictions, or posterior model probabilities.
  6. Report both what is stable and what changes. Similar means do not establish similar tail risks or equal model adequacy.

As an example, one blemish in 25 inspections gives Beta(2,25), Beta(1.5,24.5), and Beta(3,44) from priors Beta(1,1), Beta(0.5,0.5), and Beta(2,20). Their means are 0.07407, 0.05769, and 0.06383, but their 95% upper bounds are 0.16983, 0.14607, and 0.13061. The third prior contributes concentration 22 against 25 observations, so its mean weight is 22/47 = 0.46809. It is not negligible merely because 25 is larger than 22.

Large-sample arguments require conditions on the model, identification, parameter dimension and prior support. They are not a guarantee that a chosen prior is irrelevant to every target. If the prior excludes a region entirely, multiplying by a likelihood cannot create posterior mass there. Inspect the actual sensitivity instead of using sample size alone as a substitute.[2]

Common misconceptions

"Uniform means no assumptions." It is uniform on a named scale and support. A Jacobian changes the density on a new scale.

"Proper means scientifically defensible." Normalization is necessary for prior probabilities, but does not establish domain relevance.

"A density mode is a point probability." A continuous distribution assigns zero probability to an individual point. A point hypothesis needs an atom or another explicit model.

"Software accepting zero beta shapes proves that Haldane updating works." A software-defined limiting distribution is not the normalization of a divergent posterior kernel.

Retrieve before checking

Without the table, state the three posterior distributions for zero of ten. Derive the density of theta squared when theta is uniform. Explain what must be checked before using an improper prior and why a prior predictive dataset must share its drawn rate across the trials.

Check your reasoning

The three proper posteriors are Beta(1,11), Beta(0.5,10.5), and Beta(2,28). The transformed density is 1/(2 sqrt(psi)), with total integral one. An improper-prior update needs a finite, positive normalizing integral. Shared-rate trials require one theta draw per simulated dataset; drawing a new theta per trial removes the intended within-dataset shared uncertainty.

What to remember

What matters here: a prior is a quantitative part of a model. State its scale and support, verify that the posterior exists, inspect the data it predicts, and report sensitivity for the quantities that matter. No label such as "flat," "objective," or "weak" performs those checks for you.

Sources

  1. Kass, R. E., and Wasserman, L. (1996). The selection of prior distributions by formal rules. Journal of the American Statistical Association, 91(435), 1343-1370. Section 2.2, especially p. 1345: transformation, Jeffreys rules and the normal location-scale distinction. Read the source
  2. Gelman, A., Simpson, D., and Betancourt, M. (2017). The prior can often only be understood in the context of the likelihood. Entropy, 19(10), 555. Sections 1-3. doi:10.3390/e19100555. Read the source
  3. Stan Development Team. (2026 documentation, version 2.40). Posterior and prior predictive checks. Stan User's Guide, prior predictive checks section. Read the source
  4. R Core Team. (2026 development documentation). The Beta Distribution, stats 4.6.0. Density, quantiles and boundary-parameter extensions. Only proper positive-shape beta distributions are passed to software in this lesson. Read the source
Key terms
Proper prior
A probability distribution whose density or mass normalizes to one.
Improper prior
A nonnegative prior kernel with no finite normalizing constant; a proper posterior requires a separate check.
Jacobian
The derivative factor that adjusts a density when variables are transformed.
Jeffreys rule
A prior rule based on the square root of Fisher information, or its determinant in several dimensions, under the required regularity conditions.
Prior predictive check
Examination of data simulated or calculated from the likelihood averaged over a proper prior.
Point mass
Positive probability assigned to an exact parameter value, distinct from a continuous density at that value.
Prior sensitivity
Changes in relevant posterior or predictive quantities when specified prior assumptions are varied.

Credible Intervals, Confidence Procedures, and Prediction

  • State posterior probability and repeated-sampling coverage separately, with the required assumptions and target.
  • Calculate and compare equal-tailed, highest-density, Wilson, exact binomial and Wald intervals without confusing their guarantees.
  • Derive unconditional and range-conditional coverage in a uniform-location model and distinguish these from posterior probability.
  • Use the appropriate normal or Student t result for a mean and distinguish it from a predictive interval for a new observation.

Two readings and a misleading label

A fictional gauge reports 3.10 and 3.90. Suppose, exactly for this model, that each reading is independent and uniform between theta-0.5 and theta+0.5. The unknown theta is a fixed location. Consider the procedure that reports the interval from the smaller reading L to the larger U. Before observing any data, this procedure covers theta with probability 0.5: the two readings must fall on opposite sides of theta, which happens with probability 2(1/2)(1/2).

For these particular readings, the model also requires theta to lie between 3.40 and 3.60. That entire compatible set lies inside the reported [3.10,3.90]. We have more information than the procedure's unconditional 50% label conveys. This rescaled uniform-location example develops a distinction discussed in the interval-estimation literature. We will derive both the frequentist and Bayesian calculations, rather than use one to stand in for the other.[4]

Name the probability statement

A confidence procedure C(Y) is evaluated with the parameter theta fixed and hypothetical samples Y generated from the specified sampling model. Its coverage function is c(theta) = Ptheta{theta in C(Y)}. A procedure with exactly 95% coverage has coverage 0.95 at each allowed theta; a conservative 95% procedure has coverage at least 0.95. A nominal 95% approximate procedure may miss that target. A particular calculated interval does not acquire a posterior probability merely from its nominal label.[3][4]

A 95% credible set C(y) instead satisfies integral over C(y) p(theta | y) dtheta = 0.95, for a continuous posterior and an exactly chosen probability content. It conditions on the observed data, likelihood, and prior. The distribution expresses uncertainty about theta; it need not mean that a physical constant changes from one repetition to the next.[1]

These are different properties, and an interval can have both. You can evaluate the repeated-sampling coverage of a Bayesian interval procedure, or compute the posterior mass of a confidence interval under a specified prior. Neither property follows from the name of the other. Likewise, coverage and credibility both rely on their stated models; neither removes measurement bias or repairs a wrong sampling model automatically.

Compare five intervals for the same inspection count

Return to the fictional seven blemishes in twenty-three inspections. For independent Bernoulli observations with common theta and prior Beta(1,1), the posterior is Beta(8,17). Let qr denote its r quantile. The central equal-tailed 95% interval is [q0.025,q0.975], leaving 2.5% posterior probability below and above.[1]

Interval constructionLowerUpperWidth
Equal-tailed credible, Beta(8,17)0.156300.510950.35465
Highest-density credible, Beta(8,17)0.147670.500200.35253
Wilson score, nominal 95%0.156040.508660.35262
Clopper-Pearson, at least 95% coverage0.132100.529190.39709
Wald approximation, nominal 95%0.116300.492390.37609

Here the Wilson and equal-tailed Bayesian intervals are close, but their upper endpoints differ by about 0.00229. That is not an identity and does not establish agreement to three decimal places at both ends. The prior and the construction still determine what each interval asserts.

To reproduce the Wilson interval, put phat = y/n, z = the standard normal 0.975 quantile, and d = 1+z2/n. The center is (phat+z2/(2n))/d and the half-width is (z/d) sqrt[phat(1-phat)/n+z2/(4n2)]. This comes from inverting the binomial score test, whose variance under a candidate theta uses that candidate value. It is an approximation to a sampling-model calculation, not a posterior probability calculation.[2]

The Clopper-Pearson limits invert exact binomial tails. For 0 < y < n, they can be computed as Beta(y,n-y+1)'s 0.025 quantile and Beta(y+1,n-y)'s 0.975 quantile. Set the lower endpoint to 0 at y=0 and the upper endpoint to 1 at y=n. The two beta distributions here are computational identities for tail inversion, not the single posterior of this lesson. Discreteness generally makes coverage exceed the target rather than equal it everywhere.[2]

Five 95% intervals for seven events in twenty-three trials: posterior equal-tail [0.15630,0.51095], posterior HPD [0.14767,0.50020], Wilson [0.15604,0.50866], Clopper-Pearson [0.13210,0.52919], and Wald [0.11630,0.49239]. Similar endpoints do not establish identical interpretations.
Five 95% intervals for seven events in twenty-three trials: posterior equal-tail [0.15630,0.51095], posterior HPD [0.14767,0.50020], Wilson [0.15604,0.50866], Clopper-Pearson [0.13210,0.52919], and Wald [0.11630,0.49239]. Similar endpoints do not establish identical interpretations.

Check coverage by summing the sampling probabilities

The Wald interval is phat +/- z sqrt[phat(1-phat)/n]. At y=0 it collapses to [0,0]. That realized interval misses every positive theta. It does not follow that the whole procedure has zero coverage at every positive theta: other samples produce other intervals. The coverage must average over all possible samples.[2]

For any chosen interval rule with endpoints L(y) and U(y), the fixed-parameter binomial coverage is

c(theta) = sum from y=0 to n of 1{L(y) <= theta <= U(y)} C(n,y) thetay(1-theta)n-y.

For n=10 and true theta=0.1, no events occurs with probability 0.910 = 0.34868. Direct summation of all eleven outcomes gives Wald coverage 0.64969, far below its nominal 0.95. Clipping a negative lower endpoint to zero does not change whether a positive theta was included, so it cannot repair this coverage problem. The figure evaluates the procedures across parameter values using exact sums, not a simulation.

A Bayesian interval also has a fixed-theta coverage function, which need not equal 0.95 at every theta. For a proper prior and a credible set with posterior mass 0.95 for every dataset, its coverage averaged over that same prior is 0.95: integrate the joint probability of theta being in C(Y), first conditional on Y and then over Y. This prior-predictive calibration is a different averaging statement from uniform coverage at every fixed theta.

Exact binomial sampling coverage for four nominal 95% procedures with n=10, calculated by summing the probabilities of every possible count whose interval includes the fixed theta. The Wald coverage at theta=0.1 is 0.6496866225. A 95% posterior mass does not guarantee 95% coverage at each fixed theta.
Exact binomial sampling coverage for four nominal 95% procedures with n=10, calculated by summing the probabilities of every possible count whose interval includes the fixed theta. The Wald coverage at theta=0.1 is 0.6496866225. A 95% posterior mass does not guarantee 95% coverage at each fixed theta.

One-sided bounds are not two-sided endpoints

For zero events in ten trials, the exact one-sided 95% upper confidence bound solves (1-U)10 = 0.05, giving U = 0.25887. The two-sided equal-tailed Clopper-Pearson interval instead allocates 0.025 to that tail and ends at 0.30850. Under the uniform prior, the 95% upper credible bound is 0.23840, while the equal-tailed 95% posterior interval is [0.00230,0.28491]. Label the method, sidedness and probability level before comparing numbers.

Condition on the gauge range without introducing a prior

For the uniform gauge, let D = U-L. Its density is fD(d) = 2(1-d), for 0 < d < 1, independent of theta. This makes the range ancillary for the location parameter. To derive conditional coverage frequentistically, keep theta fixed and write A = L-theta+0.5. Given D=d, A is uniform over (0,1-d): the ordered pair of unit-uniform errors has constant joint density 2, and fixing its separation leaves a line of length 1-d.

The reported interval [L,U] covers theta when A <= 0.5 <= A+d. For d < 0.5, the permitted A segment has length d within the total length 1-d. For d >= 0.5, every allowed A covers theta. Hence

Ptheta{L <= theta <= U | D=d} = min(1,d/(1-d)).

This calculation did not assign a probability distribution to theta. It describes repeated samples grouped by their observed range. Integrating against fD recovers unconditional coverage: integral00.5 2d dd plus integral0.51 2(1-d) dd = 0.25+0.25 = 0.5. A procedure with constant unconditional coverage can have strongly varying conditional coverage.

For two independent Uniform(theta-0.5,theta+0.5) readings, conditional coverage of the observed min-max interval is min(1,d/(1-d)). The range density is 2(1-d). Integrating their product gives unconditional coverage 0.5. This is a repeated-sampling calculation with theta fixed, separate from a posterior calculation.
For two independent Uniform(theta-0.5,theta+0.5) readings, conditional coverage of the observed min-max interval is min(1,d/(1-d)). The range density is 2(1-d). Integrating their product gives unconditional coverage 0.5. This is a repeated-sampling calculation with theta fixed, separate from a posterior calculation.

Now calculate the posterior from the complete readings

Take the explicit improper flat prior p(theta) proportional to 1 on the real line. The observed-data likelihood is constant when both readings are within 0.5 of theta, and zero otherwise. For d < 1 the compatible set is [U-0.5,L+0.5], of length 1-d. Normalization gives a proper uniform posterior on that set. Here we have conditioned on the complete readings and used a prior; this is a separate calculation from conditioning the sampling distribution on D.

ReadingsRange dPosterior supportPosterior mass inside [L,U]
3.10, 3.900.80[3.40,3.60]1.00000
3.10, 3.600.50[3.10,3.60]1.00000
3.10, 3.400.30[2.90,3.60]0.42857
3.10, 3.150.05[2.65,3.60]0.05263

The numbers equal the range-conditional coverage function in this particular location model. Equality is established by the two derivations, not by treating a fixed theta as uniformly distributed in the frequentist calculation. If readings differ by more than one unit, the model is incompatible with them; a narrower interval cannot repair that failure.

A central 50% credible interval has midpoint M=(L+U)/2 and half-width (1-d)/4. For the first row it is [3.45,3.55], length 0.10; for the last it is [2.8875,3.3625], length 0.475. This central procedure also has 50% frequentist coverage conditional on every d in (0,1), because M-theta conditional on D=d is uniform over [-(1-d)/2,(1-d)/2]. Thus a well-chosen procedure can have both properties. Conditional analysis is available to frequentists too.

Under the specified uniform gauge and a flat location prior, readings 3.1 and 3.9 give posterior support [3.4,3.6] and central 50% interval [3.45,3.55]. Readings 3.1 and 3.15 give support [2.65,3.6] and central 50% interval [2.8875,3.3625]. The posterior mass in the observed range is one and 1/19 respectively.
Under the specified uniform gauge and a flat location prior, readings 3.1 and 3.9 give posterior support [3.4,3.6] and central 50% interval [3.45,3.55]. Readings 3.1 and 3.15 give support [2.65,3.6] and central 50% interval [2.8875,3.3625]. The posterior mass in the observed range is one and 1/19 respectively.

Choose the posterior set and its coordinate

For a continuous posterior, an equal-tailed interval selects quantiles. Under a continuous strictly increasing transformation, transform both endpoints; under a strictly decreasing one, transform and reverse their order. The resulting interval remains equal-tailed with the same posterior probability.

A highest posterior density, or HPD, set instead collects parameter values above a density threshold relative to a specified coordinate measure, allowing a portion of an equal-density boundary when needed. Among sets with the required probability, it minimizes length or volume under suitable regularity conditions. For a unimodal scalar density it is usually an interval. For separated modes it can be disconnected; forcing one interval can include a low-density gap. For a uniform posterior, many highest-density choices tie.

For the unimodal Beta(8,17) posterior, solving for 0.95 mass and equal density at the two interior endpoints gives [0.14767,0.50020]. For the decreasing Beta(1,11) density, the 95% HPD interval is [0,0.23840]. The latter includes a boundary density mode, not a positive point probability at zero.

A nonlinear transformation changes density through a Jacobian, so a transformed HPD set need not be HPD in the new coordinate. It still has its original 95% posterior probability. Those are not inconsistent probability statements; they optimize different coordinate-dependent lengths. State the coordinate and construction instead of calling one interval universally better.

Known variance and estimated variance give different calculations

For independent normal observations with known sigma and a flat prior on mu, the posterior is N(ybar,sigma2/n). Its central 95% interval is ybar +/- z0.975 sigma/sqrt(n). The same endpoints define an exact 95% normal-model confidence procedure. A proper informative normal prior generally changes the Bayesian endpoints. Replacing sigma by an estimate without changing the calculation is a different approximation.

When both mu and v=sigma2 are unknown, consider the explicit joint improper prior p(mu,v) proportional to 1/v, relative to dmu dv. This is equivalent to 1/sigma relative to dmu dsigma, and differs from the general joint Jeffreys rule described in the preceding lesson.[5] The joint posterior kernel is

v-(n/2+1) exp[-{(n-1)s2 + n(mu-ybar)2}/(2v)].

Integrating over positive v gives a kernel proportional to [1+n(mu-ybar)2/((n-1)s2)]-n/2. For n > 1 and positive sample sum of squares, this is a proper Student t posterior: (mu-ybar)/(s/sqrt(n)) ~ tn-1. The quantity s/sqrt(n) is the t distribution's scale, not generally its standard deviation. The central posterior interval matches the usual normal-model t confidence interval under this specific prior.[3]

For fictional measurements 7.8, 8.0, 8.1, 8.3, and 8.8, ybar=8.2 and s2=0.145. The posterior for mu has four degrees of freedom, scale 0.17029, and standard deviation 0.24083. Its central 95% interval is [7.72719,8.67281]. The same values have the confidence interpretation only under the independent normal sampling assumptions used to derive that procedure.

Predict a new observation, not another interval for the mean

Under the same unknown-variance normal model and joint prior, a new observation has a Student t predictive distribution with n-1 degrees of freedom, center ybar, and scale s sqrt(1+1/n). Integrating over uncertainty in both mu and v produces this distribution. For the five measurements, its central 95% interval is [7.04185,9.35815], substantially wider than the interval for mu.

Ask what should lie inside an interval: a parameter, a future observation, or a proportion of an entire population. These are different targets. Posterior, confidence, predictive and tolerance intervals cannot be exchanged just because each is labeled 95%. The independent-normal formulas do not account for an unknown common calibration offset.

Common misconceptions

"Nominal 95% means verified 95% coverage." Compute or justify coverage under the stated model. The small-sample Wald calculation above does not meet its nominal target.

"Confidence procedures cannot condition on observed precision information." The range-conditional calculation keeps theta fixed and uses the sampling model.

"Transforming an HPD set invalidates its probability." Its probability is preserved; its highest-density or shortest-length property may change.

"A t scale is always its standard deviation." For nu > 2, variance is scale squared times nu/(nu-2). The distinction matters when degrees of freedom are small.

Retrieve before checking

State the two probability statements without using the word "confidence" as an explanation. Derive the gauge's conditional coverage with theta fixed. Explain why a transformed HPD set can remain 95% credible, and name the extra variability in the interval for a new normal observation.

Check your reasoning

Coverage averages inclusion of a fixed theta over repeated samples; credibility integrates a posterior over a set for observed data. Given range d, the lower-error coordinate is uniform over a segment of length 1-d; the covering segment has length d for d<0.5 and otherwise the full length. A transformation preserves event probabilities but changes density and length. A new observation contains its own sampling noise as well as uncertainty in parameters.

Pulling it together

Remember: report the target, model, construction, sidedness and probability level with an interval. Use a posterior calculation for a posterior claim and a sampling calculation for a coverage claim. Agreement of endpoints can be useful, but only the assumptions and derivation establish what that agreement means.

Sources

  1. Orloff, J., and Bloom, J. (2022). Probability Intervals. MIT 18.05, sections 2-3. Posterior probability intervals and equal-tail construction. Read the source
  2. NIST/SEMATECH. e-Handbook of Statistical Methods, section 7.2.4.1, Confidence intervals. Wilson score formula and exact binomial-tail inversion. Read the source
  3. NIST/SEMATECH. e-Handbook of Statistical Methods, section 1.3.5.2, Confidence Limits for the Mean. Student t interval and repeated-sampling interpretation. Read the source
  4. Morey, R. D., Hoekstra, R., Rouder, J. N., Lee, M. D., and Wagenmakers, E.-J. (2016; online 2015). The fallacy of placing confidence in confidence intervals. Psychonomic Bulletin & Review, 23, 103-123. Formal coverage versus posterior probability and uniform-location examples. doi:10.3758/s13423-015-0947-8. Read the source
  5. Kass, R. E., and Wasserman, L. (1996). The selection of prior distributions by formal rules. Journal of the American Statistical Association, 91(435), 1343-1370. Section 2.2, especially p. 1345: transformation, Jeffreys rules and the normal location-scale distinction. Read the source
Key terms
Coverage function
At each fixed parameter value, the sampling probability that a specified random interval contains that value.
Credible set
A set containing a stated posterior probability conditional on the observed data and model.
Ancillary statistic
A statistic whose sampling distribution does not depend on the parameter under consideration.
Equal-tailed interval
For a continuous distribution, an interval that leaves equal specified probability in its two tails.
Highest-density set
A set of specified posterior probability that includes no lower-density points than those excluded, relative to a chosen coordinate measure; it may be disconnected.
Predictive interval
An interval for a future observation, accounting for its sampling variation as well as relevant parameter uncertainty.
Student t scale
The scale in a location-scale t distribution; it differs from the standard deviation when the latter exists.

Module 3: Evidence, Actions, and Information

Compare hypothesis tests and model evidence, derive loss-based actions, and value additional information with explicit predictive branches and finite-horizon policies.

Hypothesis Tests, Bayes Factors, and the Jeffreys-Lindley Comparison

  • Distinguish a p-value, a test procedure's error rates, a Bayes factor, and a posterior model probability.
  • Derive the normal point-null Bayes factor and update model odds without confusing densities with event probabilities.
  • Explain what stays fixed in a Jeffreys-Lindley comparison and examine prior-scale sensitivity and limiting cases.
  • Report effect size, uncertainty, model assumptions, and evidence together, without turning one threshold into a scientific conclusion.

One estimate, several different questions

A fictional calibration experiment records n independent measurements from Normal(theta,1), where the variance 1 is known in squared measurement units. The target theta is a common offset. An observed mean of 0.0196 from n=10000 gives z=0.0196/(1/100)=1.96. Is that an unusually large standardized discrepancy from zero? Does a model fixing theta at zero predict this dataset better than a specified alternative? Is the offset large enough to matter? These are three separate questions.

The ASA cautions that a p-value does not give the probability that a hypothesis is true and does not measure the importance of an effect. A threshold alone is insufficient for a scientific or practical conclusion.[1] This lesson derives the quantities needed to make those distinctions concrete. The normal model, known variance, independence, and prior choices are teaching assumptions.

Keep the testing traditions and their targets distinct

Three familiar approaches emphasize different summaries. Significance testing associated with Fisher uses a discrepancy statistic and its null tail probability. Neyman-Pearson testing studies a specified decision rule through Type I error and power. Bayesian model comparison associated with Jeffreys compares model predictions and updates model odds. This is a methodological map, not a complete account of any person's changing views. Berger explicitly makes that qualification when discussing their possible reconciliation.[2]

QuantityWhat is averaged or conditioned on?What it does not supply
p-valueA tail of a statistic under a specified null sampling modelThe probability of the null given the data
Type I error alphaRejection frequency under the null for the whole procedureThe probability that this rejection is mistaken
Power at thetaRejection frequency when theta generates repeated samplesA probability distribution over theta
BF01Predictive density under H0 divided by that under H1Posterior model odds until prior model odds are included

For a statistic T whose larger values are more discrepant, write p=P(T(Y)>=T(y) | H0). Here y is observed and Y represents a new sample under the null model. The definition depends on the statistic, sampling design, and null assumptions. A two-sided normal test uses T=|Z| and p=2 Phi(-|z|), where Phi is the standard normal cumulative distribution function.

Compute error rates for a complete rule

Take the rule reject H0 when |Z|>1.96, where Z=sqrt(n) times the sample mean. Under theta=0, Z is standard normal, so its rejection probability is 0.04999579, approximately 0.05. The observed value z=1.96 gives that same rounded p-value, but the two numbers serve different roles: one describes a rule before observing the sample, the other summarizes the observed statistic. Strict versus non-strict inequalities have no probability effect in this continuous model.

At another fixed theta, Z is Normal(sqrt(n) theta,1). Therefore power(theta)=Phi(-1.96-sqrt(n) theta) + 1-Phi(1.96-sqrt(n) theta). At n=100, power is 0.17007 for theta=0.1, 0.51599 for theta=0.2, and 0.99882 for theta=0.5. A large p-value can occur when a test has little power against a relevant effect. It does not establish equivalence to zero.

The sampling rule must match the procedure actually used. Choosing outcomes after inspecting them, searching many analyses, or repeatedly testing until a threshold is crossed can change the error rate. A reported alpha does not automatically describe those altered procedures. Full reporting of the analysis choices is part of the ASA's guidance.[1]

Sampling densities of Z for null theta zero and effects 0.1 and 0.2 with n=100. The rejection cutoffs remain plus or minus 1.96. Null rejection probability is approximately 0.05, whereas power is 0.17007 and 0.51599 for the two nonzero effects.
Sampling densities of Z for null theta zero and effects 0.1 and 0.2 with n=100. The rejection cutoffs remain plus or minus 1.96. Null rejection probability is approximately 0.05, whereas power is 0.17007 and 0.51599 for the two nonzero effects.

Compare predictive densities and then update odds

Specify H0: theta=0 and H1: theta follows Normal(0,tau squared), with tau>0 fixed before this comparison. Let w=P(H0), with 0<w<1. There are two distinct prior choices: the probability w assigned to the null model and the distribution of theta within the alternative. The alternative prior is proper. An arbitrary multiplicative constant in an improper prior generally leaves an ordinary marginal likelihood undefined.[3]

For model j, its marginal likelihood is m_j(y)=integral f(y | theta,Hj) pi_j(theta) dtheta, with the fixed parameter substituted under H0. Then BF01=m_0(y)/m_1(y) and posterior odds H0:H1 = BF01 times w/(1-w). Solving for a probability gives P(H0 | y)=w BF01/[w BF01+(1-w)]. A Bayes factor uses the within-model priors but does not require w; the posterior model probability does.

For continuous data, m_j(y) is a density, not the probability of the exact observed vector. Taking the ratio on the same observation scale removes its units. Model probabilities are conditional on the candidate models and their assumptions. Even a large factor for H0 over H1 cannot establish that either is an adequate description of reality.

Derive the normal comparison

The identity sum(y_i-theta)^2 = sum(y_i-ybar)^2 + n(ybar-theta)^2 separates the likelihood into a residual factor shared by the two models and a factor depending on the sample mean. The shared factor cancels in their ratio. Under H0, ybar is Normal(0,1/n). Under H1, integrating the normal prior gives ybar distributed as Normal(0,tau squared+1/n). This is the predictive distribution before seeing the data under that model.

Divide these two normal densities at ybar. Their standard-deviation ratio is sqrt(1+n tau squared). Their exponent difference is -n ybar^2/2 + ybar^2/[2(tau^2+1/n)]. Substitute z=sqrt(n) ybar to obtain

BF01 = sqrt(1+n tau^2) exp[-(z^2/2) n tau^2/(1+n tau^2)].

For a known measurement standard deviation sigma other than 1, replace n tau squared by r=n tau squared/sigma squared and set z=sqrt(n) ybar/sigma. The variance ratio r is dimensionless. For numerical work calculate logBF01 = 0.5 log(1+r) - 0.5 z^2 r/(1+r) first. Substituting an estimated standard deviation into this known-variance derivation does not make it an exact t-model Bayes factor.

Hold z fixed and watch the effect shrink

Set tau=1 and w=0.5, then compare hypothetical datasets that all have z=1.96. The corresponding p-value is 0.04999579, not exactly 0.05. Exact 0.05 would use z=1.9599639845. We retain 1.96 so every displayed calculation is reproducible from its stated inputs.[5]

nObserved meanBF01P(H0 | y)
50.8765390.4942140.330752
420.3024351.0044800.501117
1000.1960001.5004700.600075
10000.0619814.6436290.822809
100000.01960014.6525190.936113
10000000.001960146.4900780.993220

At fixed z and fixed positive tau, the exponential term approaches exp(-z squared/2), while sqrt(1+n tau squared) grows. Thus BF01 eventually increases without bound. Numerically the positive nonzero crossover BF01=1 occurs at n=41.57975; among integer sample sizes the crossing is between 41 and 42. This is one normal-model illustration of the Jeffreys-Lindley comparison, whose history predates Lindley's 1957 paper.[4]

This is a sequence of specially chosen datasets, each with ybar=1.96/sqrt(n). It is not a prediction that accumulating observations from a fixed nonzero theta will keep z at 1.96. If ybar instead remains near a fixed nonzero value as n grows, the negative exponential in the Bayes factor can overwhelm its square-root factor and favor H1. The distinction resolves the misleading claim that larger samples necessarily favor the null.

At z=1.96 the observed mean shrinks as 1.96 divided by square root n. With fixed alternative prior Normal(0,1), BF01 eventually grows, reaching 1.50047 at n=100 and 14.65252 at n=10000. This comparison holds z fixed across hypothetical datasets, not a fixed nonzero true effect.
At z=1.96 the observed mean shrinks as 1.96 divided by square root n. With fixed alternative prior Normal(0,1), BF01 eventually grows, reaching 1.50047 at n=100 and 14.65252 at n=10000. This comparison holds z fixed across hypothetical datasets, not a fixed nonzero true effect.

Change the prior on a scientifically meaningful scale

At n=10000 and z=1.96, tau values 0.25, 1, and 4 produce BF01 values 3.67644, 14.65252, and 58.59678. A broader alternative assigns lower predictive density near the observed small mean in these examples. It still has its highest density at zero; saying that it could not predict a small offset would be wrong. The issue is how much density each model assigns locally.

The relationship is not globally monotone in tau. As tau approaches zero, H1's predictive distribution approaches H0's, so BF01 approaches 1. Put r=n tau squared. Differentiating the log factor gives d logBF01/dr = [(1+r)-z^2]/[2(1+r)^2]. When z squared exceeds 1, BF01 initially falls, reaches a minimum at r=z squared-1, then rises. The explorer below makes this turn visible. Choosing tau after seeing the data to obtain a preferred factor would change the analysis and needs explicit treatment.

Keeping n and z fixed while sending tau to infinity is a different limiting operation, commonly discussed as Bartlett's diffuse-prior issue. Keep it distinct from increasing n at fixed z and fixed tau.[3] Multiplying tau by ten does not multiply BF01 by exactly ten for every finite r. The linear approximation applies in the sufficiently diffuse regime of this stated model.

Prior model odds matter separately. At n=100 and tau=1, BF01=1.50047. Equal prior odds give P(H0 | y)=0.60008. With w=0.1, that probability is about 0.14290; with w=0.9, it is about 0.93105. Changing w leaves BF01 unchanged. Explain both choices instead of presenting a posterior model probability as a data-only fact.

Left: at n=10000 and z=1.96, BF01 approaches one for vanishing alternative prior scale, initially decreases, and later increases with scale. Right: with BF01 fixed at 1.50047, changing prior null probability changes posterior null probability but leaves the factor unchanged.
Left: at n=10000 and z=1.96, BF01 approaches one for vanishing alternative prior scale, initially decreases, and later increases with scale. Right: with BF01 fixed at 1.50047, changing prior null probability changes posterior null probability but leaves the factor unchanged.

Report practical importance and model limitations

Suppose a stated application regards offsets between -0.05 and 0.05 as practically negligible. In a separate estimation model with theta following Normal(0,1), n=10000 and ybar=0.0196 give posterior mean 0.01959804 and standard deviation 0.00999950. The posterior probability that |theta|<0.05 is about 0.99882. This probability concerns a region in a continuous posterior. It is not the 0.93611 probability of the point-null model in the two-model mixture.

A useful report states the observed mean and standard error, the relevant effect scale, the sampling assumptions, the two candidate models, tau and w, the factor's direction, and sensitivity results. Discuss measurement bias or dependence when the setting suggests them. Replacing a point null with an interval changes the model comparison; it does not guarantee that every discrepancy between testing approaches disappears.[4]

Left: the continuous Normal(0,1) estimation prior produces posterior mean 0.01959804 and SD 0.00999950, with approximately 0.99882 probability within the stated practical region. Right: a separate point-null mixture with equal prior model odds gives null probability 0.93611. The events and models are different.
Left: the continuous Normal(0,1) estimation prior produces posterior mean 0.01959804 and SD 0.00999950, with approximately 0.99882 probability within the stated practical region. Right: a separate point-null mixture with equal prior model odds gives null probability 0.93611. The events and models are different.

Common misconceptions

"p=0.05 means H0 has probability 0.05." It is a null tail calculation. Model probability requires a model space and prior probabilities.

"BF01=15 is a 15 percent probability." It is an odds multiplier. Equal prior odds give posterior probability 15/16.

"A larger sample must make the methods agree or disagree." State which quantities and data sequence are fixed. There is no such unconditional rule.

"A Bayes factor chooses the action." Actions also depend on consequences. The next lesson introduces losses.

Retrieve before checking

Without copying, define the four rows of the first table. Derive the two predictive variances and explain why a point-null probability cannot come from an entirely continuous prior alone. Predict what changing only w does in the interactive explorer.

Check your reasoning

The p-value averages over null samples; alpha and power describe a complete rule; BF01 compares integrated model predictions. Predictive variances are 1/n and tau squared+1/n. Positive probability at the exact point zero must be explicitly represented, here by the model weight w. Changing w changes posterior odds, while the predictive densities, p-value, and Bayes factor remain fixed.

What to carry forward

Key idea: identify the probability question before interpreting a number. Derive the comparison from explicit models, keep prior scale separate from model odds, and assess the effect and its consequences alongside evidence.

Sources

  1. American Statistical Association (2016). Statement on Statistical Significance and P-Values: official release and six principles, p. 2. Read source.
  2. Berger, J. O. (2003). Could Fisher, Jeffreys and Neyman have agreed on testing? Statistical Science, 18(1), 1-12, with discussion to p. 32. Sections 1-3. Read source.
  3. Kass, R. E., and Raftery, A. E. (1995). Bayes factors. Journal of the American Statistical Association, 90(430), 773-795. Sections 3 and 5. Read source.
  4. Wagenmakers, E.-J., and Ly, A. (2023; online 2022). History and nature of the Jeffreys-Lindley paradox. Archive for History of Exact Sciences, 77, 25-72. Read source.
  5. SciPy developers. scipy.stats.norm reference: normal density, survival function, location and scale. Accessed November 10, 2026. Read source.

All inspection examples, loss tables, and numerical experiments in this lesson are stipulated teaching models. Their calculations are derived here and independently checked; they are not observations from an actual inspection program.

Key terms
p-value
A tail probability of a specified statistic under the null sampling model.
Power
The probability that a specified rule rejects the null at a particular data-generating parameter.
Marginal likelihood
The probability or density of observed data after averaging over a model's parameter prior.
Bayes factor BF01
The ratio m0(y)/m1(y), which multiplies prior odds H0:H1.
Prior model probability
The probability assigned to a candidate model before the observations being analyzed.
Jeffreys-Lindley comparison
A comparison in which fixed standardized discrepancy and growing sample size can increasingly favor a precise null under specified priors.
Practical equivalence region
A range of effects judged negligible for a stated application; it is distinct from an exact point null.

From Posterior to Action: Loss, Thresholds, and Decision Risk

  • Construct a state-by-action loss table and minimize posterior expected loss over feasible actions.
  • Derive mean, median, and quantile decisions under their stated loss functions, including the distinction between continuous and discrete zero-one loss.
  • Calculate a binary decision threshold, ties, sensitivity, and expected regret without treating a probability as an action.
  • Distinguish posterior loss, frequentist risk, Bayes risk, admissibility, and minimaxity in explicit finite examples.

A probability does not choose the action

A fictional inspection model assigns probability p=0.08 that a component is defective. A supervisor must either repair it or release it. Eight percent is a statement about uncertainty. It does not specify the consequences of unnecessary repair or releasing a defective component. To choose, we need the possible states, feasible actions, and a loss assigned to each state-action combination.

Let L(a,theta) be the loss of taking action a when the state is theta. Conditional on observed data y, calculate rho(a | y)=E[L(a,theta) | y]. A Bayes action minimizes this posterior expected loss among the available actions. A decision rule maps every possible dataset to an action; it is more than the single action chosen after the dataset in hand.[1]

The units in this lesson are fictional loss units. They can represent consequences on a coherent scale, but are not measured repair costs. Choosing that scale requires the people responsible for the consequences. A calculation can expose a tradeoff without proving that its numerical values are appropriate. If a consequence remains unresolved, report sensitivity to it instead of silently assigning a value.

Read every cell before deriving a threshold

ActionDefective, probability pSound, probability 1-p
Repair01
Release150

These four stipulated losses define the initial exercise. In particular, successful repair has zero loss in this table. That is a simplifying assumption, not a claim that actual repair is free. The expected losses are rho(repair)=1-p and rho(release)=15p. Repair has smaller expected loss when 1-p<15p, or p>1/16=0.0625. At p=0.0625 the two actions tie. State a tie convention if software must select one.

At p=0.08, repair has loss 0.92 and release has loss 1.20, so repair minimizes expected loss. With false-alarm loss cFP>0, missed-defect loss cFN>0, and zero diagonal losses, the threshold is cFP/(cFP+cFN). Thus a high missed-defect cost can justify acting below probability one-half. This threshold is a consequence of the four-cell model, not a universal probability cutoff.[4]

Now change the loss for repairing a defective component to 0.4 and retain the other three cells. Expected repair loss becomes 0.4p+(1-p)=1-0.6p. Equating it with 15p gives p=1/15.6=0.06410256. Plugging only the two error costs into the old threshold would miss this change. For general losses r1,r0 for repair and d1,d0 for release, compare p(r1-d1)+(1-p)(r0-d0) with zero. The inequality may reverse, an action may dominate throughout, or no interior threshold may exist.

For repair losses zero and one in defective and sound states, and release losses fifteen and zero, posterior loss lines cross at p=1/16. At p=0.08 repair loss is 0.92 and release loss is 1.20; releasing incurs expected regret 0.28 relative to the current optimum.
For repair losses zero and one in defective and sound states, and release losses fifteen and zero, posterior loss lines cross at p=1/16. At p=0.08 repair loss is 0.92 and release loss is 1.20; releasing incurs expected regret 0.28 relative to the current optimum.

Check sensitivity and the cost of a wrong choice

Return to zero diagonal losses and cFP=1. At p=0.08, repair is preferred when the missed-defect cost exceeds (1-p)/p=11.5. At cFN=12, release loss is 0.96 and repair loss remains 0.92, so repair is still preferred. At cFN=11, release loss is 0.88, so release is preferred. The boundary is 11.5, with a tie there. Compare the expected losses rather than declaring a flip because a threshold moved.

The posterior expected regret of action a is rho(a | y)-min_b rho(b | y). In the original p=0.08, cFN=15 case, releasing has expected regret 1.20-0.92=0.28. This is the loss from choosing a suboptimal action relative to the best currently available decision. It is not the uncertainty that perfect information could remove.

Regret depends on the available action set. If a new action called quarantine has stipulated loss 0.6 in either state, it beats repair at p=0.08. Its operational feasibility matters: an unavailable action cannot be selected merely because its row has a low number. Likewise, a capacity constraint coupling decisions across components is a different optimization problem.

Multiplying every cell by the same positive constant preserves the ordering of expected losses. Adding a quantity depending on theta but not on the action also preserves the ordering, provided the relevant expectations exist. Transforming only selected cells, or applying a nonlinear transformation to all losses, need not preserve the decision. Units, ratios, and action-independent baselines are different issues.

Squared loss selects a mean when its moments exist

Suppose the action is a real-valued report a for an unknown rate theta. Under squared error, L(a,theta)=(a-theta) squared. With finite posterior second moment and mu=E(theta | y), expand around mu:

E[(a-theta)^2 | y]=(a-mu)^2+Var(theta | y).

The cross term vanishes because E(theta-mu | y)=0. The variance term is constant in a, so the unique minimizing real report is a=mu. If the allowed reports form a finite grid, choose the grid point nearest mu, with a tie if equally close. If the needed moment is infinite, this finite-risk argument does not apply. Chen's treatment derives posterior minimization and the squared-loss rule explicitly.[1]

Reuse the fictional seven-defects-in-twenty-three posterior Beta(8,17) from earlier lessons. Its mean is 8/25=0.32 and variance is (8 times 17)/(25 squared times 26)=0.00836923. Reporting a=0.30 incurs squared risk 0.0004+0.00836923=0.00876923. This simple decomposition lets you audit the calculation without simulation.

Absolute and asymmetric losses select quantiles

For absolute loss |a-theta| and a continuous posterior with cumulative distribution F, split the expectation at a. Its derivative is F(a)-(1-F(a))=2F(a)-1, where differentiation is justified. A median minimizes the risk. For a distribution with atoms, the general condition is F(a-)<=0.5<=F(a); a derivative need not exist and the median need not be unique. A finite posterior first absolute moment ensures the expected absolute loss is finite.

Unequal costs change the target. Let an underestimate cost cU>0 per unit and an overestimate cost cO>0 per unit:

L(a,theta)=cU max(theta-a,0)+cO max(a-theta,0).

The continuous derivative is -cU[1-F(a)]+cO F(a). Setting it to zero gives F(a)=cU/(cU+cO). More costly underestimation moves the preferred report upward. Quantiles minimize these asymmetric piecewise-linear losses; Gneiting gives a broader characterization of this forecasting result.[2] Here we apply the same expectation argument to a posterior for theta rather than a predictive distribution for a future observation.

With Beta(8,17), cU=4 and cO=1 select the 0.8 quantile, 0.39707732. The median is 0.31513199, and the interior density mode is (8-1)/(8+17-2)=0.30434783. Software's beta quantile and moment conventions match these calculations.[3]

ReportaExpected squared lossExpected absolute lossExpected asymmetric loss, cU=4,cO=1
Mean0.3200000.0083690.0735520.183881
Median0.3151320.0083930.0734520.190932
Density mode0.3043480.0086140.0739480.208348
0.8 quantile0.3970770.0143100.0997270.133701

Compare values within each column. Squared errors have squared-rate units, whereas the other columns use rate-error units with different cost weights. Their numerical magnitudes are not directly comparable across columns. The posterior stays the same throughout; the loss changes what one-number report is best.

For the fixed Beta(8,17) posterior, squared loss is minimized at mean 0.32, absolute loss at median 0.31513199, and asymmetric loss with underestimation cost four and overestimation cost one at quantile 0.39707732. Compare risks within a loss function, not across differently scaled loss units.
For the fixed Beta(8,17) posterior, squared loss is minimized at mean 0.32, absolute loss at median 0.31513199, and asymmetric loss with underestimation cost four and overestimation cost one at quantile 0.39707732. Compare risks within a loss function, not across differently scaled loss units.

Exact zero-one loss needs special care

If theta has finitely many possible values and L(a,theta)=0 for an exactly correct label and 1 otherwise, posterior risk is 1-P(theta=a | y). A label with greatest posterior probability is optimal. For example, state probabilities 0.2,0.5,0.3 give risks 0.8,0.5,0.7, so choose the middle state.

If theta has a continuous density and no atoms, P(theta=a | y)=0 for every fixed a. Under that exact same zero-one loss, every report has risk 1. Maximizing a density does not minimize this risk uniquely. Probability and density are not interchangeable.

A different loss assigns zero whenever |a-theta|<epsilon and one otherwise. Now the optimal report maximizes posterior mass in a window of width 2 epsilon. Smooth interior density modes can emerge as limits of such window optimizers, with suitable conditions, but a finite window need not be centered at the mode. For Beta(1,11) on [0,1], density decreases from the boundary. With epsilon=0.05, a=0.05 covers [0,0.10], whereas a=0 covers only [0,0.05]. The first has strictly greater probability. A tolerance window and exact equality are different decision problems.[2]

A Beta(1,11) density has mode zero but no point mass. Under tolerance plus or minus 0.05, reporting 0.05 covers [0,0.10], which has more mass than the [0,0.05] covered by reporting zero. Under exact zero-one equality loss, all fixed reports instead have expected loss one.
A Beta(1,11) density has mode zero but no point mass. Under tolerance plus or minus 0.05, reporting 0.05 covers [0,0.10], which has more mass than the [0,0.05] covered by reporting zero. Under exact zero-one equality loss, all fixed reports instead have expected loss one.

Separate posterior loss from sampling risk

Posterior loss fixes the observed data and averages over theta. Frequentist risk instead fixes theta and averages over all data that could be sampled: R(theta,delta)=E_theta[L(delta(Y),theta)]. Bayes risk averages that risk over a proper prior: r(pi,delta)=integral R(theta,delta) pi(theta) dtheta. Under conditions allowing the expectations to be interchanged, minimizing posterior expected loss at each dataset yields a Bayes rule. These are distinct expectations, even when they evaluate the same rule.[1]

A rule is dominated if another has no greater risk at every state and smaller risk somewhere. An admissible rule has no such competitor. A minimax rule minimizes the maximum risk over the state space. Neither definition requires nature to be a literal adversary. They describe performance criteria, and the state space and allowed rules are part of each claim.

A finite example makes the distinctions visible

Use the original two-state loss table, and suppose no observation is available. Allow a randomized rule that repairs with probability q. Its risk when defective is 15(1-q); its risk when sound is q. Minimizing the larger of the two equalizes them at q=15/16=0.9375. The resulting maximum risk is 0.9375. If randomization were forbidden, always repairing would be minimax with maximum risk 1. The allowed rule class matters.

Under a prior defective probability 0.08, always repairing is Bayes optimal with average loss 0.92, less than the randomized minimax average of 0.9375. Yet the randomized rule has sound-state risk 0.9375, below always repairing's risk 1, and defective-state risk 0.9375, above always repairing's risk 0. Neither rule dominates the other. Calling minimax worse in every realistic situation would misstate this tradeoff.

For the least-favorable defective probability 1/16, every q has average loss 15/16. The equal-risk randomized rule is therefore Bayes for that prior and minimax. This is an explicit example of a connection between the two criteria, not proof that every Bayes rule is minimax.[1]

One useful admissibility result has a short proof: with a finite state space, positive prior mass at every state, and finite risks, a Bayes rule cannot be dominated. Any improvement somewhere without a worsening anywhere would strictly lower its prior-average risk, contradicting optimality. Dropping full support breaks that argument. With prior probabilities (1,0) and two no-data actions having state risks A=(0,2) and B=(0,1), both minimize Bayes risk, but B dominates A. General complete-class results require their own hypotheses; they do not make admissibility and Bayesian optimality universally identical.

With no observation, repairing with probability q has state risks 15(1-q) and q. Their maximum is minimized at q=15/16. Prior-average loss for defect probability 0.08 is instead minimized by q=1. Neither of these rules dominates the other state by state.
With no observation, repairing with probability q has state risks 15(1-q) and q. Their maximum is minimized at q=15/16. Prior-average loss for defect probability 0.08 is instead minimized by q=1. Neither of these rules dominates the other state by state.

Common misconceptions

"The most probable state determines what to do." That follows for discrete equal-error loss, not for arbitrary consequences.

"Zero-one loss always gives the density mode." Exact equality under an atomless continuous posterior gives risk 1 for every report.

"Changing the threshold means the action changed." Recompute both expected losses at the actual p.

"A decision threshold reveals the real loss ratio." Only within the stated unconstrained, two-action, zero-diagonal model. Other costs, constraints, or objectives can produce the same operational cutoff.

Retrieve before checking

Derive the 1/16 threshold from all four cells. Explain why a 4:1 underestimation cost selects the 0.8 quantile. Give the exact continuous zero-one counterexample. Finally state what stays fixed in posterior loss and what stays fixed in frequentist risk.

Check your reasoning

Equating 1-p and 15p gives p=1/16. The asymmetric derivative gives F(a)=4/5. An atomless posterior gives P(theta=a)=0, hence exact zero-one loss has expectation 1 for all a. Posterior loss fixes y and integrates theta; frequentist risk fixes theta and integrates the possible data and any decision randomization.

What to carry forward

Key idea: choose an action using its full consequences and the uncertainty relevant to those consequences. A preferred estimate, threshold, or rule is always relative to a loss, an action set, and a performance criterion.

Sources

  1. Chen, Y.-C. (2026). Elementary Decision Theory. University of Washington STAT 581, Chapter 1: Bayes risk, posterior minimization, minimaxity and admissibility. Read source.
  2. Gneiting, T. (2008). Quantiles as Optimal Point Predictors. University of Washington technical report. Published as Quantiles as optimal point forecasts (2011), International Journal of Forecasting, 27, 197-207. Read source.
  3. SciPy developers. scipy.stats.beta reference: beta density, moments and quantiles. Accessed November 10, 2026. Read source.
  4. Kochenderfer, M. J. (2015). Decision Making Under Uncertainty: Theory and Application. MIT Press. Sections 3.2.1-3.2.2 and 4.2.4; author-hosted copy dated June 29, 2026. Read source.

All inspection examples, loss tables, and numerical experiments in this lesson are stipulated teaching models. Their calculations are derived here and independently checked; they are not observations from an actual inspection program.

Key terms
Bayes action
An available action minimizing posterior expected loss for the observed data.
Decision rule
A mapping from possible datasets to actions, potentially including randomization.
Posterior expected regret
An action's posterior loss minus the minimum attainable posterior loss using current information.
Quantile decision
A report at probability cU/(cU+cO) under the stated asymmetric linear underestimation and overestimation costs.
Frequentist risk
Expected loss over possible samples at a fixed state or parameter.
Admissibility
Absence of a competing rule whose risk is no larger everywhere and smaller somewhere.
Minimax rule
A rule minimizing the largest risk over the specified state space and permitted rule class.

Value of Information and Sequential Decisions

  • Compute expected value of sample information by updating on every possible observation and optimizing within each branch.
  • Distinguish gross information value, net benefit, and the upper bound from perfect information.
  • Explain why decision relevance and dependence matter, and calculate the value of a repeated versus duplicated reading.
  • Use backward induction for a finite testing horizon and compare an adaptive policy with always testing or stopping.

What would an additional reading change?

Continue the fictional component decision. Current information gives defective probability p=0.08. Repair has loss 0 when defective and 1 when sound; release has loss 15 when defective and 0 when sound. The minimum current expected loss is min(1-p,15p)=0.92, achieved by repair. A new instrument reading could change that action. How much is that opportunity worth before the result is known?

Value-of-information analysis compares the best current decision with a policy that can respond to future data. It averages over those future data under their predictive distribution. It does not evaluate only the result one hopes to receive. Decision-theoretic research design uses this expected improvement to compare possible data collection with its cost.[1]

All probabilities and costs below are stipulated for an exercise, not estimated performance of a real inspection system. The reading does not alter the component state, the terminal actions remain available, and a stated additive test cost accounts for its consequences. A destructive test or time-varying defect state would require a different model.

Build a four-cell joint distribution

Assume sensitivity s=P(+ | defective)=0.80 and false-positive rate f=P(+ | sound)=0.096. These probabilities describe this new reading conditional on the current information as well as the state. The joint probabilities are obtained by multiplying a state probability by a conditional reading probability.

StatePositiveNegativeTotal
Defective0.08 times 0.80 = 0.064000.08 times 0.20 = 0.016000.08000
Sound0.92 times 0.096 = 0.088320.92 times 0.904 = 0.831680.92000
Total0.152320.847681.00000

Thus the positive branch occurs with probability q+=ps+(1-p)f=0.15232. Its posterior is p+=ps/q+=0.42016807. The negative branch has probability q-=p(1-s)+(1-p)(1-f)=0.84768, and posterior p-=p(1-s)/q-=0.01887505. The posteriors are conditional probabilities within columns; the branch probabilities come from the column totals.

A useful check is the law of total expectation: q+ p+ + q- p- = p. Here 0.064+0.016=0.08. Before seeing the new result, the expected updated defect probability is the current probability. Information creates value by allowing different actions, not by systematically increasing or decreasing the average posterior probability.

The joint table for defect probability 0.08, sensitivity 0.8, and false-positive rate 0.096 has defective-positive 0.064, defective-negative 0.016, sound-positive 0.08832, sound-negative 0.83168. Repair after positive and release after negative incurs expected terminal loss 0.32832 in the two highlighted error cells.
The joint table for defect probability 0.08, sensitivity 0.8, and false-positive rate 0.096 has defective-positive 0.064, defective-negative 0.016, sound-positive 0.08832, sound-negative 0.83168. Repair after positive and release after negative incurs expected terminal loss 0.32832 in the two highlighted error cells.

Optimize inside each branch before averaging

With zero diagonal losses, the repair threshold remains 1/16. After a positive, p+=0.42016807 exceeds it: repair loss is 0.57983193 and release loss is 6.30252101, so repair. After a negative, p-=0.01887505 is below it: release loss is 0.28312571 and repair loss is 0.98112495, so release.

Average those branchwise minima, not the posteriors themselves and not a single action chosen in advance:

R_after = 0.15232(0.57983193) + 0.84768(0.28312571) = 0.32832.

There is a shorter independent check using the joint table. Under the policy repair after positive and release after negative, loss occurs only for a positive sound item or a negative defective item. Thus R_after = 1(0.08832)+15(0.016)=0.32832. The two routes must agree. Optimizing an action after each observation is the key operation in the standard value-of-information expression.[2]

The gross expected value of sample information is EVSI = R_now-E_Z[min_a E(L(a,theta) | y,Z)]. Here it is 0.92-0.32832=0.59168 loss units. If the reading has additive cost c=0.10 in those same units, total expected loss with it is 0.42832, and net improvement is 0.49168. With c=0.60, testing gives total loss 0.92832 and is worse than acting immediately. At c=0.59168 the two options tie.

Perfect information gives a bound, not a prediction

For the same actions and losses, perfect information would reveal the state before the action. Its residual expected loss is R_perfect=E_theta[min_a L(a,theta) | y]. Expected value of perfect information is EVPI=R_now-R_perfect. Perfect information does not generally make loss zero: unavoidable costs may remain. It does give zero in this particular table because each state has a zero-loss action.[1]

Here EVPI=0.92. For free information under a coherent fixed model, with the option to ignore it and the same feasible actions, 0<=EVSI<=EVPI. To see the first inequality, the old optimal action is still an available policy after observing Z. To see the second, knowledge of the true state can imitate any observation-based action choice and then choose a statewise minimizing action. These comparisons use the same loss and state model throughout.

This reading captures 0.59168/0.92=0.64313043, about 64.3 percent of the available gross improvement. A proposed reading costing 1.5 units cannot be worthwhile in this model because even perfect information is worth only 0.92. Additive cost can make net improvement negative without contradicting the nonnegative gross-value result.

Immediate expected loss is 0.92. One reading reduces terminal loss to 0.32832 before adding its cost. At cost 0.10 its total is 0.42832; at cost 0.60 it is 0.92832. Perfect information leaves zero terminal loss in this particular table, giving EVPI 0.92.
Immediate expected loss is 0.92. One reading reduces terminal loss to 0.32832 before adding its cost. At cost 0.10 its total is 0.42832; at cost 0.60 it is 0.92832. Perfect information leaves zero terminal loss in this particular table, giving EVPI 0.92.

Accuracy is not the same as decision value

If s=f, the reading has the same distribution in both states. Every possible branch leaves p unchanged, so EVSI=0. A different route to zero value occurs when one action is optimal on every positive-probability branch. Then using it after observing or before observing has the same expected loss, by total expectation. Information may still reduce uncertainty about the state, while being useless for this particular terminal decision.[2]

At p=0.9 with s=0.8 and f=0.096, even a negative gives p-=0.66568047, above 1/16. Repair is optimal on both branches, so this one reading has zero gross value for this table. This is a statement about the full reading model. A positive likelihood ratio alone is insufficient: it says nothing by itself about how strongly a negative result changes belief.

For a counterexample, keep p=0.9 but set s=0.999 and f=0.01998. The positive likelihood ratio is exactly 50. A negative gives p-=0.00909992, below 1/16, and now the optimal action changes. The post-reading expected loss is 0.1(0.01998)+15(0.9)(0.001)=0.015498. Immediate repair costs 0.1 in expectation, so gross EVSI is 0.084502. A large positive likelihood ratio did not make the test worthless or valuable on its own.

Lower posterior entropy and lower decision loss are different objectives. A reading could clarify distinctions among states that all require the same action. Conversely, modest probability changes near a costly action boundary can matter. State the target decision before ranking instruments by information value.

A duplicate reading is not another independent test

Repeating a test requires P(Z2 | theta,Z1,current information), not just its marginal sensitivity and false-positive rate. Conditional independence would set that conditional distribution equal to the original reading model. Identical error mechanisms, a shared specimen, or simply copying a recorded result need not satisfy it. Conditional independence is a model assumption to investigate, not a consequence of taking two readings.

After one positive in our base case, p1=0.42016807. Under conditionally independent repeats, a second positive gives p2 = p s^2/[p s^2+(1-p) f^2], about 0.85793. If the second reading is an exact copy of the first, P(Z2=+ | theta,Z1=+)=1 in both states. Its likelihood ratio conditional on the first result is 1 and the posterior remains 0.42016807. Multiplying the original likelihood ratio a second time would double-count evidence.

The explorer includes a duplicate-output scenario. It represents an exact copy with zero new information, not a fitted model for partial dependence. Modeling partial dependence would require conditional probabilities or a shared-error model. The first lesson on repeated evidence supplies the same probability principle; here its consequence is a potentially wrong spending or stopping decision.

Left: gross EVSI for the fixed inspection test varies with the current defect probability and is zero at p=0.9 because both results still lead to repair. Right: a second conditionally independent positive updates beyond the first-positive posterior, whereas an exact copy keeps the posterior at 0.42016807.
Left: gross EVSI for the fixed inspection test varies with the current defect probability and is zero at p=0.9 because both results still lead to repair. Right: a second conditionally independent positive updates beyond the first-positive posterior, whereas an exact copy keeps the posterior at 0.42016807.

Plan two opportunities with backward induction

For a finite horizon, decide backward from the last possible observation. Let R(p)=min(1-p,15p). If zero further tests are allowed, define V0(p)=R(p). With k tests still available, identical conditionally independent readings, and additive cost c per test, define

Vk(p)=min{R(p), c + sum_z P(z | p) V(k-1)(p_z)}.

The first entry means stop and act; the second means pay for one observation and retain the right to stop or continue afterward. This is backward induction on the belief p, specialized from finite-horizon sequential decision methods.[2] Outcomes with zero predictive probability are omitted; their posterior need not be defined. Treating such a branch as zero-probability evidence for a state would be an error.

At p=0.08 and c=0.10, V0=0.92 and V1=0.42832. With two opportunities, first consider each possible result of the first test. After a positive, both outcomes of one more test still favor repair, so its gross value is zero: stop and repair. After a negative, a second positive gives posterior 0.13816735 and a second negative gives 0.00423819. These straddle the threshold. The conditional gross value of that second test is 0.13231257, exceeding c=0.10, so test again on that branch.

The optimal two-opportunity policy is therefore: test once; repair immediately after a positive; after a negative, test again and repair only if the new result is positive. Its expected number of readings is 1+0.84768=1.84768, so expected testing cost is 0.184768. Its terminal error loss is 0.92[0.096+0.904(0.096)] + 15(0.08)(0.20)^2 = 0.21616128. The total is 0.40092928, below V1. Always taking both tests would add 0.20 and yield 0.41616128 for the same terminal action pattern, wasting a second test on the first-positive branch.

Optimized expected losses for zero through three allowed future readings are 0.92,0.42832,0.40092928,0.36713650 at cost 0.10, and 0.92,0.47832,0.47832,0.47343295 at cost 0.15. For two opportunities at cost 0.10, test again only after a first negative, giving total loss 0.40092928.
Optimized expected losses for zero through three allowed future readings are 0.92,0.42832,0.40092928,0.36713650 at cost 0.10, and 0.92,0.47832,0.47832,0.47343295 at cost 0.15. For two opportunities at cost 0.10, test again only after a first negative, giving total loss 0.40092928.

One-step lookahead can miss a useful sequence

With c=0.15, a second test after a first negative has gross value 0.13231257, below its cost. With at most two opportunities, the optimal total remains V2=V1=0.47832. But with three opportunities, backward induction gives V3=0.47343295. Having two remaining observations can justify continuing after that first negative even though one remaining observation would not.

This is why a greedy rule that stops whenever the next single reading is not worth its price can miss the value of a sequence. A finite-horizon policy evaluates later options as part of the present choice. The value depends on the allowed horizon, dependence model, cost, available actions, and current belief.[2] More allowed opportunities cannot worsen the optimized value when stopping remains available; forcing more tests can worsen it.

For a real application, test reliability is often uncertain. A complete analysis can place a joint posterior over defect state and reliability parameters and average over it. Plugging in estimated sensitivity and false-positive rate omits that uncertainty and can also conceal dependence between future readings. The literature on information value extends the same decision principle to uncertain parameters and research designs.[1]

Common misconceptions

"The positive result is valuable, so the test is valuable." Evaluate all possible results before seeing them, including their probabilities and optimal actions.

"A perfect test is worth the current loss in every problem." Subtract the remaining statewise minimum loss; it is zero only for suitable loss tables.

"Repeating a reading repeats its likelihood ratio." Only with the required conditional reading model. An exact copy contributes no new evidence.

"The next test's EVSI settles the whole plan." Later opportunities can change the best current choice. Backward induction evaluates that possibility.

Retrieve before checking

Reconstruct the four joint cells without looking. Derive 0.32832 by both branch averaging and error-cell counting. Explain the order of expectation and minimization. Then describe why a copied result has zero new value and why a two-step plan can differ from a one-step plan.

Check your reasoning

The cells are 0.064,0.016,0.08832,0.83168. After a positive repair; after a negative release. Multiplying their conditional minimum losses by the branch probabilities equals 0.08832+15(0.016)=0.32832. Minimization is inside the predictive expectation because actions may depend on results. A copy is already known and cannot change belief or the best action. A longer horizon preserves additional contingent choices that a one-step calculation omits.

What to carry forward

Key idea: information is worth the improvement in the best feasible policy that it enables. Update on each possible result, optimize within each branch, average before the result is known, and include the cost and dependence assumptions.

Sources

  1. Jackson, C., Presanis, A., Conti, S., and De Angelis, D. (2019). Value of information: sensitivity analysis and research design in Bayesian evidence synthesis. JASA, 114(528), 1436-1449. Section 2. Read source.
  2. Kochenderfer, M. J. (2015). Decision Making Under Uncertainty: Theory and Application. MIT Press. Sections 3.2.1-3.2.2 and 4.2.4; author-hosted copy dated June 29, 2026. Read source.

All inspection examples, loss tables, and numerical experiments in this lesson are stipulated teaching models. Their calculations are derived here and independently checked; they are not observations from an actual inspection program.

Key terms
EVSI
Current minimum expected loss minus the predictive average of minimum posterior loss after a proposed observation, before its cost.
EVPI
Current minimum expected loss minus expected loss when the true decision-relevant state is known before acting.
Net value
Gross expected improvement minus the cost of obtaining the information on the same loss scale.
Preposterior analysis
Averaging future posterior decisions over the current predictive distribution of possible data.
Policy
A rule specifying actions or further observations conditional on information available at each stage.
Backward induction
Solving a finite sequential problem from terminal decisions back to the present.
Conditional dependence
A situation in which a new result's distribution still depends on earlier results after conditioning on the stated state or parameter.

Module 4: Computation and Diagnostic Reasoning

Build and verify Monte Carlo estimators, importance weights, Metropolis-Hastings, Gibbs and Hamiltonian transitions; assess quantity-specific precision and modern diagnostics without overclaiming convergence.

Monte Carlo Precision, Rejection Sampling, and Importance Weights

  • Express posterior means and event probabilities as expectations, and distinguish simulation error from posterior uncertainty.
  • Calculate an iid Monte Carlo standard error and plan simulation effort under explicit moment assumptions.
  • Derive a valid rejection sampler and explain its envelope and acceptance probability.
  • Construct importance weights from the actual proposal, assess support and tail behavior, and interpret weight ESS cautiously.

Start with the quantity you need

Suppose a fictional inference problem has posterior theta~Beta(8,17). We will use its known answers to audit computational methods: E(theta)=8/25=0.32, posterior variance 136/16250=0.00836923, and P(theta>0.5)=0.0319573283. This is a deliberately convenient benchmark, not an account of a real engineering investigation. The beta density is proportional to theta^7(1-theta)^16 on 0<theta<1.[4]

Before reading further, explain why the posterior mean and this tail probability are different summaries. Recall that a posterior probability conditions on the data and the model. A computer's approximation to that probability introduces a second source of uncertainty: variation between simulation runs with the same model and data.

Turn an integral into an average

For a normalized posterior p(theta), an expectation is mu_g=integral g(theta)p(theta)dtheta. If theta_1,...,theta_S are independent draws from p, estimate it by the average of g(theta_s). Use g(theta)=theta for the mean, and g(theta)=1(theta>0.5) for the tail probability. The latter average is simply the fraction of draws exceeding 0.5.

An iid law of large numbers applies when E|g(theta)| is finite. A usual normal central limit approximation additionally requires finite variance sigma_g squared. These conditions concern the function being averaged. A distribution can have well-defined event probabilities while its mean or variance fails to exist. Increasing the run length does not make an undefined posterior mean meaningful.[1]

Not every summary is itself one fixed expectation. A variance can be estimated using first and second moments or a sample-variance formula. A quantile is obtained by inverting a cumulative distribution function. The empirical CDF at t averages 1(theta<=t), but quantile uncertainty also depends on how steep the CDF is near the quantile. A standard quantile approximation requires regularity such as positive density there. Do not apply the mean's standard-error formula directly to a percentile.

Separate posterior spread from Monte Carlo error

For independent draws with finite variance, Var(average g)=sigma_g squared/S and MCSE=sigma_g/sqrt(S). In practice the sample standard deviation of g estimates sigma_g. The posterior standard deviation of theta describes uncertainty about theta under the model. The MCSE of the simulated mean describes uncertainty in our numerical estimate of E(theta). Only the latter tends toward zero as more draws from the same posterior are generated.

For the beta mean with S=10000, the benchmark MCSE is about 0.00091483, while the posterior standard deviation remains about 0.09148350. For its tail probability p=0.0319573283, the indicator variance is p(1-p), so the benchmark MCSE is about 0.00175886. The same draw count therefore gives different precision for different summaries. We know p here because this is a test problem; an actual unknown probability generally uses an estimated variance.[1]

An approximate 95 percent Monte Carlo interval is estimate plus or minus 1.96 times MCSE when the normal approximation is justified. It concerns repeated numerical runs, not a 95 percent posterior interval for theta. A standard error is not a promise about the last printed decimal. Report precision suited to the intended decision, and assess rare-event approximations separately.

The fixed Beta(8,17) posterior has mean 0.32 and SD 0.0914835. The shaded region above 0.5 has probability 0.03195733. Numerical standard errors for its mean and event probability decrease as one over square root draw count, whereas the posterior SD stays fixed.
The fixed Beta(8,17) posterior has mean 0.32 and SD 0.0914835. The shaded region above 0.5 has probability 0.03195733. Numerical standard errors for its mean and event probability decrease as one over square root draw count, whereas the posterior SD stays fixed.

Worked example: reproduce two runs

The explorer uses a seeded pseudo-random generator, Mulberry32 with uniforms shifted by half a 32-bit grid cell to avoid endpoints. For each beta draw, sum eight independent negative log uniforms to obtain A, and sum seventeen new negative log uniforms to obtain B. These are Gamma(8,1) and Gamma(17,1) draws; A/(A+B) follows Beta(8,17). The sums are independent. This construction exploits integer shape parameters and is an instructional sampler, not a general beta-software implementation.

To check the beta construction, set T=A+B and theta=A/T. Substitution into the joint gamma density with Jacobian T gives a factor proportional to T^24 exp(-T) theta^7(1-theta)^16. Integrating over T leaves exactly the beta kernel. The generation rule therefore has an independent algebraic justification in addition to its numerical checks.

Running estimates from the stated integer-gamma beta sampler and Mulberry32 seeds 410 and 411. At 10000 draws, mean estimates are 0.31978264 and 0.31996680; tail estimates are 0.0315 and 0.0336. A dotted line marks each analytic answer. Individual paths need not approach monotonically.
Running estimates from the stated integer-gamma beta sampler and Mulberry32 seeds 410 and 411. At 10000 draws, mean estimates are 0.31978264 and 0.31996680; tail estimates are 0.0315 and 0.0336. A dotted line marks each analytic answer. Individual paths need not approach monotonically.

Two reproducible simulation runs

SeedDrawsEstimated meanCount above 0.5Estimated tail
410100000.319782643150.0315
411100000.319966803360.0336

Both runs differ from the exact tail 0.03195733. Their errors are approximately -0.00045733 and +0.00164267. Replaying a seed reproduces the arithmetic. Comparing several seeds shows numerical variation, but agreement alone cannot detect a shared coding mistake. Here the independent analytic benchmark provides a stronger check.

Plan effort and recognize rare-event failure

Halving iid MCSE requires four times as many draws, all else equal. For a Bernoulli average, obtaining MCSE at most epsilon requires S>=p(1-p)/epsilon squared if p is known. To target approximately 95 percent half-width h, the planning expression is S>=1.96 squared p(1-p)/h squared. These are different precision targets. Replace p(1-p) by 1/4 for a conservative variance bound, but the resulting normal interval still needs an adequate approximation.

If zero events occur, the plug-in MCSE sqrt(phat(1-phat)/S) equals zero. It does not prove p=0. With independent Bernoulli trials, observing zero gives the one-sided 95 percent upper bound 1-0.05^(1/S). At S=10000 it is about 0.00029953. This follows by solving (1-p)^S=0.05, and remains separate from any prior-based posterior interval.

The square-root rate has no dimension in its exponent, but that does not make high-dimensional integration free. The variance of g, the cost of a draw, and the difficulty of sampling can all grow with dimension. Record what is held fixed before comparing computational costs.

Rejection sampling needs a valid envelope

Let ftilde be an unnormalized nonnegative target, Z=integral ftilde, and q a normalized proposal covering its support. Find a finite M such that ftilde(theta)<=M q(theta) everywhere. Propose theta from q and independently U from Uniform(0,1). Accept if U<=ftilde(theta)/(M q(theta)); otherwise try again. The accepted density is proportional to q times the acceptance probability, hence ftilde. The acceptance probability is Z/M.[2]

If the target p is already normalized, Z=1 and the probability becomes 1/M. Independent proposal-uniform pairs produce independent accepted draws. Rejected proposals do not become target draws in this algorithm. This is different from the Markov-chain rejection rule in the next lesson.

For normalized Beta(8,17) and Uniform(0,1) proposals, the maximum density occurs at theta=7/23 and is 4.2807642803. Choose M=4.3, safely above it. Accept with probability p(theta)/4.3. The overall probability is 1/4.3=0.232558, so the expected number of proposals per acceptance is 4.3. Actual counts vary. Rounding the maximum downward, even slightly, would invalidate the claimed envelope. Clipping probabilities at one does not repair an incorrect envelope.

In d dimensions, consider the specific target Normal(0,I) and proposal Normal(0,c squared I), c>=1. The supremum of p/q is c^d, so this envelope accepts at rate c^(-d). For c=2 and d=10 that is 1/1024. This example explains one dimensional difficulty; it is not a theorem that every rejection sampler deteriorates with dimension. When q=p, M=1 at every dimension. When c<1, this Gaussian proposal has tails too thin for a finite global envelope.

Left: a constant 4.3 envelope exceeds the entire normalized Beta(8,17) density; accepted proportion is 1/4.3. Right: for a specific d-dimensional standard-normal target and normal proposal of SD 2 in each coordinate, acceptance is 2 to the minus d. This is an example, not a universal dimension law.
Left: a constant 4.3 envelope exceeds the entire normalized Beta(8,17) density; accepted proportion is 1/4.3. Right: for a specific d-dimensional standard-normal target and normal proposal of SD 2 in each coordinate, acceptance is 2 to the minus d. This is an example, not a universal dimension law.

Importance sampling uses the actual proposal

Instead of rejecting proposals, importance sampling weights them. With theta_s independently drawn from q, a normalized target p gives the ordinary estimate average[g(theta_s)p(theta_s)/q(theta_s)]. It is unbiased when the integral is well-defined and q covers all regions contributing to it. For general posterior expectations, require q>0 wherever p>0. Adequate moment conditions are also needed for useful variance and normal-error estimates.[3]

If only ftilde is known, compute w_s=ftilde(theta_s)/q(theta_s), normalized weights wbar_s=w_s/sum w, and the self-normalized estimate sum wbar_s g(theta_s). This ratio is generally biased at finite S, although it is consistent under the required support and integrability conditions. Compute log weights, subtract their maximum before exponentiating, and normalize afterward. This avoids some numerical overflow without fixing a poor proposal.

Worked example: correct the weights before interpreting them

For target Beta(8,17) and proposal Beta(1,99), q(theta)=99(1-theta)^98. Constants cancel from self-normalization, leaving log w = 7 log(theta) - 82 log(1-theta) + constant. Using just the target density would omit division by q. Calling the proposal a prior does not justify that omission unless the actual target is proportional to that same prior times the likelihood being used.

The Beta(1,99) proposal is concentrated far to the left of the Beta(8,17) target despite full support. Using log weight 7 log(theta)-82 log(1-theta), the largest of five stipulated points gets weight 0.98828540. Weighted mean is 0.03085930 and weight ESS is 1.02370. The other tiny bars are not zero weights.
The Beta(1,99) proposal is concentrated far to the left of the Beta(8,17) target despite full support. Using log weight 7 log(theta)-82 log(1-theta), the largest of five stipulated points gets weight 0.98828540. Weighted mean is 0.03085930 and weight ESS is 1.02370. The other tiny bars are not zero weights.

Five proposal points with normalized weights

Stipulated proposal pointNormalized weight
0.0310.9882854040
0.0190.0117035292
0.0080.0000110046
0.0040.0000000618
0.0020.0000000004

These five supplied points are an arithmetic exercise, not a claimed random run. Their weighted mean is 0.03085930, far from 0.32. The proposal puts probability 0.8^99=2.5463 times 10^-10 above 0.2, even though much target mass lies there. Full support alone cannot ensure useful finite-run coverage.

There is a second problem: near theta=1, p(theta) squared/q(theta) is proportional to theta^14(1-theta)^(-66). Its integral diverges, so the ordinary importance weight has infinite second moment under this proposal. A finite sample might never reach the problematic tail. A seemingly tame set of observed weights therefore cannot prove that the variance exists.

Weight ESS is a concentration summary

The common weight diagnostic is ESS_w=(sum w)^2/sum(w squared)=1/sum(wbar squared). It lies between 1 and S for positive finite weights, reaches S for equal weights, and approaches 1 when a single weight dominates. The five bad-proposal points yield ESS_w=1.02370. This is a useful warning about concentration, not a calibrated count of information for every g and not a guarantee of accuracy.[3]

For contrast, five stipulated Uniform(0,1) proposals 0.31, 0.52, 0.18, 0.63, 0.09 give normalized weights 0.67300552, 0.07564575, 0.23704483, 0.00450311, 0.00980079. Their mean estimate is 0.29435460 and ESS_w=1.94188. Five points remain inadequate evidence of precision. A proposal that omits part of the target support cannot be repaired by a large weight ESS.

Pareto-smoothed importance sampling modifies extreme weights and estimates a tail-shape diagnostic, khat.[5] A fitted khat is uncertain. The theoretical generalized-Pareto variance boundary k=1/2 is distinct from a practical reliability warning such as the current loo threshold min(1-1/log10(S),0.7). A threshold exceedance calls for investigation or another computation; a value below it does not prove convergence. Use a vetted implementation and its version-specific guidance rather than inventing a universal cutoff.[6]

Common misconceptions

"More posterior draws reduce uncertainty about theta." They reduce numerical error for the fixed posterior. More informative observations would change the posterior itself.

"No observed tail events means zero risk." Rare events can be missed, and a zero plug-in standard error is not a certificate.

"Any proposal works if enough weights look similar." Support, tail behavior, and the specific estimand matter.

"A weight ESS can replace the draw count in every standard-error formula." That substitution is not generally valid for self-normalized estimates.

Retrieve before checking

Close the formulas and reconstruct the rejection acceptance probability Z/M. Explain why ordinary and self-normalized importance estimates have different bias properties. Predict how the explorer's tail estimate changes when the proposal concentrates near zero, then compare at several seeds.

Check your reasoning

Integrating q(theta) times ftilde(theta)/(M q(theta)) gives Z/M. The ordinary estimator averages a correctly weighted integrand; self-normalization divides two random averages. Concentrating proposals near zero can miss relevant target regions and produce unstable estimates, even with positive support throughout (0,1).

What to carry forward

Key idea: define the posterior quantity, validate the sampler or weights, and measure numerical precision for that quantity. A longer simulation cannot repair an incorrect target or an invalid weighting rule.

Sources

  1. Owen, A. B. Monte Carlo Theory, Methods and Examples. Author manuscript, Chapters 1-2: accuracy, standard errors, probabilities, and quantiles. Read source.
  2. Owen, A. B. Monte Carlo Theory, Methods and Examples. Chapter 4: non-uniform random numbers and acceptance-rejection sampling. Read source.
  3. Owen, A. B. Monte Carlo Theory, Methods and Examples. Chapter 9: importance sampling and self-normalized estimates. Read source.
  4. SciPy developers. scipy.stats.beta: beta density, moments, and survival function. Accessed November 10, 2026. Read source.
  5. Vehtari, A., Simpson, D., Gelman, A., Yao, Y., and Gabry, J. (2024). Pareto Smoothed Importance Sampling. Journal of Machine Learning Research, 25(72), 1-58. Read source.
  6. loo developers. Pareto k diagnostics and sample-size-dependent reliability thresholds. Accessed November 10, 2026. Read source.

All datasets and simulated examples here are constructed teaching examples. Figures are original calculations, not observations from an actual study. Reproducible seeds identify a particular numerical experiment; they do not establish that an algorithm works for every target.

Key terms
Monte Carlo standard error
The standard deviation of a numerical estimator across repeated simulations under its assumptions.
Rejection envelope
A global bound ftilde(theta)<=M q(theta) used to construct an accept-reject sampler.
Importance weight
The target density divided by the proposal density at a sampled point, possibly known only up to a common factor.
Self-normalization
Dividing each importance weight by the total before averaging; generally biased at finite sample size.
Weight ESS
The concentration summary 1/sum of squared normalized weights, not a universal precision guarantee.
Support coverage
A proposal assigns positive density wherever the target has relevant positive density.

Metropolis-Hastings, Gibbs Sampling, and Hamiltonian Dynamics

  • Apply the full Metropolis-Hastings ratio, retain rejected states, and distinguish invariance from finite-run convergence.
  • Calculate a short chain by hand and investigate proposal scale without treating acceptance rate as a universal objective.
  • Derive Gaussian Gibbs conditionals and relate coordinate correlation to slow exploration.
  • Explain Hamiltonian energy, leapfrog correction, and the role and limitations of NUTS.

Build a chain with a specified target

A fictional measurement is y=3 under y|theta~Normal(theta,1), with a standard Cauchy prior for theta. The unnormalized posterior is ftilde(theta)=exp[-(3-theta)^2/2]/(1+theta^2). Its log, ignoring an additive constant, is ell(theta)=-log(1+theta squared)-(3-theta) squared/2. The prior is proper, the likelihood is bounded, and the normal likelihood makes all posterior moments finite.

This one-dimensional posterior can be integrated numerically, giving mean 2.28513943, standard deviation 1.05587106, and mode approximately 2.25992. We will use those separate calculations as benchmarks. They are properties of this constructed target, not results inferred from the eight steps below. Recall why a normalized posterior constant cancels in a density ratio.

Invariance and convergence answer different questions

A Markov chain chooses its next state from a transition distribution that depends on its current state. A target distribution p is invariant if starting the chain from p leaves the next state's distribution equal to p. This property alone does not ensure that a chain started at an arbitrary point will reach or adequately explore p. For a finite state space, irreducibility and aperiodicity supply standard sufficient conditions for convergence to the unique stationary distribution. Continuous-state chains require appropriate analogues and regularity conditions.[1]

Detailed balance equates the joint probability measures p(x)dx K(x,dy) and p(y)dy K(y,dx) for a target density p, or their probability-mass counterparts for discrete states. This equality is a sufficient condition for invariance. It equates probability flow in opposite directions under the stationary target. It is not necessary for all valid MCMC algorithms, and it is not a statement that every state receives equal visitation. A finite trace that appears settled is evidence to inspect, not a proof of convergence.

Use the full Metropolis-Hastings acceptance rule

At x, propose y from q(y|x). Accept with probability alpha(x,y)=min(1, ftilde(y) q(x|y) / [ftilde(x) q(y|x)]), otherwise set the next state to x. The unknown target normalizer cancels. The proposal ratio cancels only when the proposal is symmetric. For mutually positive densities, the accepted stationary flow is the minimum of p(x)q(y|x) and p(y)q(x|y), which is symmetric.[1]

For numerical stability calculate log r=ell(y)-ell(x)+log q(x|y)-log q(y|x) and accept when log U<min(0,log r), with U uniform on (0,1). A proposal outside target support is rejected. Define support handling explicitly; undefined arithmetic such as infinity minus infinity is not a valid acceptance decision.

Record a state after every iteration, including a repeated state after rejection. Recording only accepted changes constructs a different jump process and generally changes the stationary distribution. This differs from independent rejection sampling, where rejected proposals are discarded and an entirely new trial is drawn.

Worked example: eight steps with every rejection retained

Start at theta=0. Use the symmetric Uniform(theta-1,theta+1) proposal theta'=theta+2u1-1. The supplied pairs (u1,u2) are (0.62,0.41), (0.18,0.93), (0.91,0.22), (0.35,0.67), (0.77,0.12), (0.08,0.88), (0.54,0.50), (0.83,0.31). These are fixed teaching inputs. They illustrate the rule, not a sufficient posterior simulation.

The eight worked steps record 0.24,0.24,1.06,0.76,1.30,1.30,1.38,2.04. Proposals -0.4 and 0.46 are rejected at steps two and six, so the previous state repeats. A dashed reference marks the posterior mean 2.28513943 from separate integration, not an inference from this short trace.
The eight worked steps record 0.24,0.24,1.06,0.76,1.30,1.30,1.38,2.04. Proposals -0.4 and 0.46 are rejected at steps two and six, so the previous state repeats. A dashed reference marks the posterior mean 2.28513943 from separate integration, not an inference from this short trace.

Eight recorded Metropolis-Hastings transitions

StepProposalell(proposal)Ratio ru2DecisionRecorded state
10.24-3.86481.88740.41Accept0.24
2-0.40-5.92840.12700.93Reject0.24
31.06-2.63493.42090.22Accept1.06
40.76-2.96470.71910.67Accept0.76
51.30-2.43451.69920.12Accept1.30
60.46-3.41770.37410.88Reject1.30
71.38-2.37841.05770.50Accept1.38
82.04-2.10201.31830.31Accept2.04

At step 4, the log difference is -2.96470470-(-2.63491276)=-0.32979194. Thus r=0.71907333 and u2=0.67 leads to acceptance even though the move is downhill. At step 6 the proposed 0.46 has r=0.37411180, below u2=0.88, so 1.30 appears twice in the recorded sequence. Six of eight proposals are accepted. That small count does not locate an optimal proposal width or establish where warmup should end.

Worked example: why the reverse proposal matters

Take states A and B with target probabilities p(A)=0.8 and p(B)=0.2. Let q(B|A)=0.9 and q(A|B)=0.1, with the remaining probabilities proposing the same state. Then alpha(A,B)=min(1,0.2 times 0.1/(0.8 times 0.9))=1/36, and alpha(B,A)=1. The resulting transition probabilities are K(A,B)=0.025 and K(B,A)=0.1. Target flow in each direction is 0.02, so the desired target is invariant.

If you mistakenly use only the target ratio, K(A,B)=0.9 times 0.25=0.225 while K(B,A)=0.1. The resulting stationary probability of B is 0.225/(0.225+0.1)=9/13, about 0.6923, rather than 0.2. More iterations would estimate the wrong distribution more precisely. Even the correct chain, when reduced to changes only, alternates A,B,A,B and has equal frequencies. Repeated states carry necessary waiting-time information.

For a two-state target with probabilities 0.8 and 0.2, correct MH transitions 0.025 and 0.1 preserve probability 0.2 at B. Omitting the reverse-proposal term changes that stationary probability to 9/13. Keeping only changes makes the correct two-state chain alternate, with stationary frequency one half and periodic behavior.
For a two-state target with probabilities 0.8 and 0.2, correct MH transitions 0.025 and 0.1 preserve probability 0.2 at B. Omitting the reverse-proposal term changes that stationary probability to 9/13. Keeping only changes makes the correct two-state chain alternate, with stationary frequency one half and periodic behavior.

Explore movement, not acceptance alone

The native explorer varies the uniform proposal half-width h. Very small h often accepts many proposals but can move slowly across the posterior. Very large h can reject many proposals. Compare traces and estimates with the numerical benchmark, using multiple seeds and starting points. Report the retained count and chosen warmup cutoff. A cutoff reduces the influence of a transient start but does not certify its removal.

Proposal shape, blocking, parameterization, and cost per evaluation also matter. Adaptation is commonly performed during warmup, with the retained sampling phase using fixed settings. Valid continuing adaptation requires additional theory; arbitrary history-dependent tuning is not automatically an ordinary invariant Markov chain.

The often quoted acceptance value 0.234 comes from a high-dimensional limit for a particular class of regular product targets and Gaussian random-walk proposals in stationarity. In that analysis proposal variance scales like 1/d, so its standard deviation scales like d^(-1/2). It is not a universal prescription for this one-dimensional uniform proposal, nor for Gibbs, HMC, or multimodal targets.[3] Compare efficiency for the quantity of interest per unit computation, after checking validity. An independent sampler drawing exactly from p accepts every draw and works perfectly, showing why high acceptance alone cannot imply failure.

Gibbs sampling updates exact conditional distributions

For a standardized bivariate normal (X,Y) with correlation rho, the full conditionals are X|Y=y~Normal(rho y,1-rho squared) and Y|X=x~Normal(rho x,1-rho squared). A systematic sweep samples X given the current Y and then Y given the newly sampled X. Each exact conditional update preserves the joint target, so their composition does too. A whole systematic sweep need not itself satisfy detailed balance. Exact Gibbs updates have acceptance probability one, yet can remain highly dependent.[1]

At rho=0.8, the conditional standard deviation is 0.6. Start at (3,3), using standard normal inputs (-0.5,0.8), (0.3,-1.2), and (0.6,-0.1). Sweep 1 gives X=0.8(3)+0.6(-0.5)=2.10 and Y=0.8(2.10)+0.6(0.8)=2.16. Sweep 2 gives (1.908,0.8064), and sweep 3 gives (1.00512,0.744096). The normal inputs are stipulated for hand calculation. Sampling is not optimization, so the chain should not settle permanently at (0,0).

Substitute one conditional update into the next: Y_t=rho squared Y_(t-1)+rho sqrt(1-rho squared) Z_(x,t)+sqrt(1-rho squared) Z_(y,t). The fresh standard normals are independent. In stationarity the coordinate sequence has autocorrelation (rho squared)^k at lag k, so its mean's integrated autocorrelation time is (1+rho squared)/(1-rho squared). For rho=0.8,0.95,0.99 it is approximately 4.5556,19.5128,99.5025. These are coordinate-mean results for this specific Gaussian systematic sampler, not ESS formulas for every Gibbs quantity.

Left: alternating coordinate updates move from (3,3) through the three specified Gibbs sweeps to (1.00512,0.744096), against bivariate-normal contours with correlation 0.8. Right: coordinate-mean integrated autocorrelation time (1+rho squared)/(1-rho squared) grows sharply near unit correlation despite acceptance probability one.
Left: alternating coordinate updates move from (3,3) through the three specified Gibbs sweeps to (1.00512,0.744096), against bivariate-normal contours with correlation 0.8. Right: coordinate-mean integrated autocorrelation time (1+rho squared)/(1-rho squared) grows sharply near unit correlation despite acceptance probability one.

Hamiltonian dynamics adds momentum

Hamiltonian Monte Carlo introduces momentum p with a normal distribution of covariance M, a positive definite mass matrix. For position q, define potential U(q)=-log ftilde(q), kinetic energy K(p)=p-transpose M-inverse p/2, and total energy H=U+K. Hamilton's equations are dq/dt=M-inverse p and dp/dt=-gradient U(q). Under exact flow, total energy is conserved. Potential energy alone can change as it is exchanged with kinetic energy.[2]

Refresh momentum, integrate a trajectory approximately, and use an acceptance correction based on min(1,exp(H_start-H_end)). A standard construction uses a reversible, volume-preserving leapfrog map, together with momentum reversal as needed in its proposal definition. The correction accounts for numerical energy error. It does not fix every mixing or geometry problem, and a gradient does not guarantee that separate posterior modes will be visited.

Worked example: one leapfrog step

Use a standard normal position target, so U(q)=q squared/2, and M=1. Starting from q=1,p=1 with step size epsilon=0.5, apply three substeps: p_half=1-(0.5/2)(1)=0.75; q_new=1+0.5(0.75)=1.375; p_new=0.75-(0.5/2)(1.375)=0.40625. The initial energy is 1. The final energy is (1.375 squared+0.40625 squared)/2=1.02783203125.

The acceptance probability is exp(-0.02783203125)=0.97255171. A supplied uniform 0.98 rejects this proposal, while 0.50 accepts it. The potential energy has increased from 0.5 to 0.9453125; comparing potential alone would give the wrong acceptance probability. This single step is an arithmetic exercise, not a complete independent draw from the normal target.

Under specific regular iid product-target assumptions and fixed integration time, leapfrog step size can scale as d^(-1/4) while maintaining a nonvanishing acceptance probability. This differs from the random-walk standard-deviation scaling d^(-1/2). The result has explicit conditions and is not a universal runtime guarantee. Gradient evaluations, parameterization, mass matrix, and trajectory length still affect cost.[4]

A leapfrog step takes (q,p)=(1,1) to (1.375,0.40625) via momentum half-steps around a position full-step. Total energy changes from 1 to 1.02783203125, giving acceptance 0.97255171. Potential rises while kinetic falls. The dashed exact-energy circle is distinct from the numerical substep path.
A leapfrog step takes (q,p)=(1,1) to (1.375,0.40625) via momentum half-steps around a position full-step. Total energy changes from 1 to 1.02783203125, giving acceptance 0.97255171. Potential rises while kinetic falls. The dashed exact-energy circle is distinct from the numerical substep path.

NUTS adapts trajectory length within a valid algorithm

The No-U-Turn Sampler builds candidate trajectories and stops expansion according to a reversal criterion, reducing the need to choose a fixed leapfrog count. Candidate construction and selection are part of the invariance argument. Simply stopping a trajectory when it turns and always returning the endpoint is not equivalent to NUTS.[5]

Stan 2.40 uses a multinomial NUTS implementation by default, with warmup adapting quantities such as step size and a mass-matrix representation. The original 2014 paper and current software should not be assumed to implement identical selection details. Record the actual software version and settings. Standard HMC requires a differentiable continuous representation; discrete unknowns need another update method or, when feasible, marginalization. Stan samples continuous parameters, so a discrete latent parameter must be handled in the model rather than declared as a sampled discrete parameter.[6]

Common misconceptions

"Correct acceptance algebra proves this finite run converged." It establishes a target-preservation property under assumptions, while exploration still needs investigation.

"Rejected states are wasted and can be deleted." Keeping repeated states is part of the Markov-chain estimator.

"Gibbs acceptance of one guarantees independence." Exact conditionals can create very slow coordinate exploration.

"HMC conserves the posterior density along its path." Exact flow conserves total energy, including momentum; numerical flow requires correction.

Retrieve before checking

Write the four factors in the full acceptance ratio from memory. Explain the asymmetric two-state counterexample to a classmate. Reproduce the Gibbs substitution and the leapfrog half-step, full-step, half-step order. Return after a day and solve the four continuation steps without the table.

Check your reasoning

The numerator contains target at the proposal and reverse proposal density; the denominator contains target at the current state and forward proposal density. Gibbs composition introduces rho squared for the coordinate's one-sweep autoregression. Leapfrog updates momentum by half a step, position by a full step, then momentum by another half step.

What to carry forward

Key idea: target-preserving transitions, efficient exploration, and reliable finite-run estimates are separate requirements. The next lesson examines evidence for the latter two.

Sources

  1. Owen, A. B. Monte Carlo Theory, Methods and Examples. Chapters 11-12: Markov chain Monte Carlo, stationarity, Metropolis-Hastings, and Gibbs sampling. Read source.
  2. Neal, R. M. (2011). MCMC Using Hamiltonian Dynamics. Handbook of Markov Chain Monte Carlo, Chapter 5, 113-162. Author manuscript. Read source.
  3. Roberts, G. O., Gelman, A., and Gilks, W. R. (1997). Weak convergence and optimal scaling of random walk Metropolis algorithms. Annals of Applied Probability, 7(1), 110-120. Read source.
  4. Beskos, A., Pillai, N., Roberts, G., Sanz-Serna, J.-M., and Stuart, A. (2013). Optimal tuning of the hybrid Monte Carlo algorithm. Bernoulli, 19(5A), 1501-1534. DOI: 10.3150/12-BEJ414. Read source.
  5. Hoffman, M. D., and Gelman, A. (2014). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. JMLR, 15(47), 1593-1623. Read source.
  6. Stan Reference Manual, version 2.40. MCMC Sampling: Hamiltonian dynamics, adaptation, and NUTS. Accessed November 10, 2026. Read source.

All datasets and simulated examples here are constructed teaching examples. Figures are original calculations, not observations from an actual study. Reproducible seeds identify a particular numerical experiment; they do not establish that an algorithm works for every target.

Key terms
Invariant distribution
A distribution preserved by a transition when the current state has that distribution.
Detailed balance
Equality of opposing stationary probability flows, a sufficient condition for invariance.
Metropolis-Hastings ratio
The target ratio multiplied by the reverse-to-forward proposal-density ratio.
Gibbs sweep
A sequence of updates from full conditional distributions, using newly updated values as specified.
Hamiltonian energy
Potential energy from the target plus kinetic energy from auxiliary momentum.
Leapfrog integrator
A reversible, volume-preserving numerical integrator built from momentum and position substeps.
NUTS
A Hamiltonian sampling algorithm that constructs and selects from trajectories using a valid no-U-turn stopping mechanism.

MCMC Diagnostics: R-hat, Effective Sample Size, and Divergences

  • Compute classical R-hat and distinguish it from rank-normalized split and folded diagnostics.
  • Relate dependence to the numerical error of a specific posterior summary, separating bulk ESS, tail ESS, and mean MCSE.
  • Investigate HMC divergences and changing posterior geometry without treating a diagnostic threshold as proof.
  • Compare a valid reparameterization with a change of model, and document a reproducible diagnostic workflow.

Ask what the computation has demonstrated

A sampler can use the correct transition rule and still explore poorly within the available run. Conversely, several chains can agree while all miss the same region or target the wrong distribution. This lesson combines comparisons across chains, dependence within chains, numerical integration warnings, and checks against known answers. None alone proves convergence or scientific adequacy.[1]

Recall the previous lesson's asymmetric-proposal mistake: a long stable run would estimate the wrong target. Diagnostics of that run cannot replace checking the target density and transition. Throughout this lesson, short traces are constructed arithmetic examples. They are not evidence from a real fitted model, and changing a diagnostic does not demonstrate that a real posterior has been repaired.

Compute the classical variance comparison

For m chains with n retained draws each, let mean_j and s_j squared be each chain's mean and sample variance, with denominator n-1. Let grand mean be the mean of the m chain means. Define W=average(s_j squared) and B=n sum(mean_j-grand mean)^2/(m-1). The classical estimate is varPlus=((n-1)/n)W+B/n, followed by Rhat_basic=sqrt(varPlus/W), when W is positive.

B measures variation in chain means on a scale comparable to within-chain variance. The formula can reveal chains occupying different locations. Its historical interpretation as potential scale reduction depends on assumptions; it does not forecast how much a reported credible interval will shrink. The current recommended diagnostic adds splitting, ranks, and folding rather than relying on this raw-scale calculation alone.[1]

Worked example: why the basic result is 2.364

Chain A contains 5.2,1.1,4.5,2.1,3.7,0.8,4.9,1.5,3.9,2.3. Chain B contains 5.7,9.7,6.5,9.1,7.4,10.3,6.3,9.5,6.9,8.6. These stipulated values have means 3 and 8. For each chain, the sum of squared deviations from its own mean is 24, so its sample variance is 24/9=2.66666667.

The grand mean is 5.5. Therefore W=8/3 and B=10[(3-5.5) squared+(8-5.5) squared]=125. Combining gives varPlus=0.9(8/3)+0.1(125)=14.9 and Rhat_basic=sqrt(14.9/(8/3))=2.36378933. The traces disagree strongly in location. This result does not say that a future interval will be exactly 2.3638 times narrower, and two ten-draw chains are too short to support a serious precision claim.

Two constructed ten-draw chains have means 3 and 8 and equal within-chain sample variance 8/3. Their classical unsplit R-hat is 2.36378933 because B=125 and varPlus=14.9. The number diagnoses disagreement; it does not predict exact future interval shrinkage.
Two constructed ten-draw chains have means 3 and 8 and equal within-chain sample variance 8/3. Their classical unsplit R-hat is 2.36378933 because B=125 and varPlus=14.9. The number diagnoses disagreement; it does not predict exact future interval shrinkage.

Split the chains to expose within-run changes

Splitting treats each chain's first and second halves as separate chains before computing the comparison. A chain that drifts from low to high values can have the same full-run mean as another chain; splitting makes the time difference visible. For an odd length, define the convention explicitly; a common convention drops the central draw. The explorer uses even lengths so halves are unambiguous.

For the preceding two ten-draw chains, raw-scale split R-hat is 1.93626391, different from the unsplit result. A change in value does not mean the draws have improved. It means a different diagnostic has been calculated. Keep the label and algorithm with the number.

Use rank normalization and folding

Pool the retained draws and replace each with its rank r, using average ranks for ties. If S is the total number of pooled draws, transform the rank to a normal score z=Phi_inverse((r-3/8)/(S+1/4)). Compute split R-hat using those scores. The denominator is S+1/4. The paper's June 22, 2021 correction explicitly repaired an earlier minus sign, and the version 1.7.1 implementation agrees with the corrected expression.[1][3]

Then fold each original draw around the pooled median by replacing it with its absolute deviation from that median. Rank-normalize the folded values and calculate split R-hat again. Report the maximum of the rank-normalized and folded rank-normalized results. Folding helps detect differing scales that can be hidden when chain means agree. Ranking reduces dependence on the existence of raw moments. These improvements do not make unvisited regions observable.[2]

For the short example, the rank-normalized split result is 1.74972751 and the folded result is 0.92437484, so their maximum is 1.74972751. The diagnostic still flags disagreement. Finite-sample estimates can fall below one; do not clamp an individual component to one and then claim that is the stated formula. Undefined results, including constant-chain cases, need investigation rather than replacement by a reassuring value. The teaching model returns an undefined result for a constant split chain, consistent with the conservative convention used here.

The Stan guidance recommends multiple independent chains, generally at least four, R-hat below 1.01, and adequate effective sample sizes for final inference. Treat these as screening recommendations. A value of 1.009 does not prove a correct result, and 1.011 is not a quantified amount of inferential bias.[4]

Left: a deterministic constructed trace with drift shows why comparing first and second halves can reveal differences hidden by the full-run mean. Right: normal distributions with the same mean but different scales illustrate why ranking absolute deviations from a pooled median adds scale sensitivity. These pictures illustrate mechanisms, not diagnostic estimates from fitted models.
Left: a deterministic constructed trace with drift shows why comparing first and second halves can reveal differences hidden by the full-run mean. Right: normal distributions with the same mean but different scales illustrate why ranking absolute deviations from a pooled median adds scale sensitivity. These pictures illustrate mechanisms, not diagnostic estimates from fitted models.

An explorer that can agree and still be wrong

The native diagnostic explorer starts with four stationary Gaussian AR(1) sequences, each having marginal Normal(0,1) and a selected correlation coefficient a with |a|<1. It then allows explicit distortions: a shared location shift, offsets between chains, differing scales, or a time trend. These modified traces are diagnostic demonstrations, not draws claimed to come from a fitted posterior.

Predict which diagnostic responds before changing a control. Between-chain offsets should reveal disagreement; a time trend can be exposed by splitting; differing scales motivate folding. Shift every chain by the same constant and both rank order and centered variances are unchanged. Thus R-hat is unchanged even though the samples no longer represent the intended Normal(0,1) reference. This controlled counterexample explains why chain agreement cannot establish target correctness.

Effective sample size belongs to a quantity

For a stationary scalar sequence X_t=g(theta_t), marginal variance sigma_g squared, and lag correlations rho_t, the exact variance of a length-N average is sigma_g^2/N * [1+2 sum_(t=1)^(N-1) (1-t/N) rho_t]. This follows by summing all diagonal and off-diagonal covariances. An asymptotic integrated autocorrelation time is tau=1+2 sum_(t=1)^infinity rho_t when the sum and relevant limiting theory are well-behaved. Then ESS is approximately N/tau and mean MCSE approximately sigma_g/sqrt(ESS).[6]

The function g matters. The parameter itself, a squared parameter, and an indicator of a tail event can have different autocorrelations and precision. A favorable ESS for one summary does not establish precision for every posterior report. The usual normal MCMC approximation also requires appropriate central-limit conditions; a finite variance alone is not sufficient for arbitrary dependent chains.

Worked example: positive and negative dependence

For a stationary unit-variance AR(1) process with coefficient a, rho_t=a^t and tau=(1+a)/(1-a). At a=0.85, tau=12.33333333. With N=4000, the asymptotic ESS is 324.3243 and approximate mean MCSE is sqrt(12.33333333/4000)=0.05552777. The exact finite-length covariance formula gives 0.05548523 for one chain of length 4000.

For four independent stationary chains of length 1000, total draw count is also 4000, but the finite correction uses each chain length before combining their independent averages. The resulting exact MCSE is 0.05535742. Do not invent correlations across chain boundaries by concatenating their traces as though they formed one continuous chain.

Keeping only lags 1 through 10 in the infinite-sum approximation at a=0.85 gives ESS about 395.9577, overstating the asymptotic information by omitting a positive remaining tail. Real autocorrelations must be estimated and become noisy at long lags. Practical ESS implementations use stabilization and truncation rules, including paired autocorrelation sequences, rather than an arbitrary fixed cutoff. Use a vetted implementation and record its convention.[3]

At a=-0.5, tau=1/3 and asymptotic ESS=12000 for N=4000. Negative correlation can reduce variance below the iid benchmark, so ESS need not be bounded by the number of draws. This is a variance-equivalent comparison, not the literal number of independent observations. It is different from the weight ESS in importance sampling, whose finite positive-weight formula is at most S.

For stationary AR(1), lag correlation is a to the lag and coordinate-mean tau=(1+a)/(1-a). Positive persistence at a=0.85 reduces asymptotic ESS to about 8.11 percent of the draw count. Alternating correlation at a=-0.5 gives ESS three times the draw count. These are theoretical variance comparisons, not estimated ESS from a finite trace.
For stationary AR(1), lag correlation is a to the lag and coordinate-mean tau=(1+a)/(1-a). Positive persistence at a=0.85 reduces asymptotic ESS to about 8.11 percent of the draw count. Alternating correlation at a=-0.5 gives ESS three times the draw count. These are theoretical variance comparisons, not estimated ESS from a finite trace.

Bulk ESS, tail ESS, and the error you will report

Bulk ESS uses rank-normalized draws. Tail ESS is based on the smaller effective sample size associated with the 5th and 95th percentiles, using localized indicator information. These help screen central and tail exploration. Bulk ESS is not literally the ESS for the raw parameter mean and should not be silently substituted into every raw-scale MCSE formula. Use the software's MCSE for the actual reported mean, quantile, probability, or contrast.[3][4]

The current Stan guidance recommends bulk ESS above 100 times the number of chains for final results, alongside R-hat and other checks; with four chains this is 400. Required numerical precision can demand much more. Compare MCSE with the tolerance relevant to the application. For example, a probability estimate near a decision threshold needs enough precision to distinguish the numerical uncertainty from the margin to that threshold.

Routine thinning is not a cure for poor mixing or bias. Keeping every kth draw may lower correlation among retained values while discarding most of them. For a fixed computed run it often reduces useful information, and it can be especially harmful to negative-correlation sequences. Storage limits or expensive downstream calculations can change the tradeoff; evaluate that actual cost rather than asserting a universal rule that thinning is always beneficial or always worse under every covariance structure.[6]

Diagnose Hamiltonian warnings separately

A divergent transition signals excessive numerical integration error under the sampler's criterion. It can indicate difficult geometry and biased exploration, even when R-hat appears acceptable. Investigate where divergences occur and how parameters interact. A flagged transition does not by itself prove exactly which region is missed, and deleting flagged draws does not repair the simulation.[4]

A smaller integration step, often encouraged through a higher target acceptance setting during renewed warmup, may help. Persistent problems call for inspecting scaling, parameterization, identification, data, and substantive prior choices. A maximum-tree-depth warning mainly concerns trajectory truncation and efficiency, and is not identical to a divergence. Low energy Bayesian fraction of missing information, or E-BFMI, can indicate difficulty exploring the energy distribution. Read software-specific guidance for each warning instead of collapsing them into a single pass/fail number.

Worked example: transform a funnel without changing its model

Consider the two-dimensional prior model v~Normal(0,3 squared), theta|v~Normal(0,exp(v)), where exp(v) is the conditional variance. The conditional standard deviation is exp(v/2). Its narrow neck at negative v and broad mouth at positive v produce strongly varying curvature in the centered coordinates (v,theta). For example, the theta-direction curvature of the negative log density is exp(-v), changing by a factor exp(12) between v=-6 and v=6.

Define z~Normal(0,1) independently of v and theta=exp(v/2)z. In the coordinates (v,z), this prior factorizes into two independent normals. The induced joint distribution of (v,theta) is unchanged. If directly transforming the centered density into a density in (v,z), include the Jacobian factor exp(v/2). If instead declaring the generative model v~Normal(0,9), z~Normal(0,1) and defining theta as a deterministic transformation, those sampling statements already specify the correct distribution.[5]

For a hierarchical model theta_j~Normal(mu,tau squared), the corresponding non-centered form is theta_j=mu+tau z_j with z_j~Normal(0,1) and tau>0. It often helps when group data are weak. A likelihood can restore dependence among transformed variables, and a centered parameterization can work better with strong group data. Non-centering does not universally eliminate difficult posterior geometry.

A substantive change to the prior changes the statistical model. A valid reparameterization preserves its induced distribution. Both can be reasonable, but document which one was done and why. Do not present a different prior's improved diagnostics as proof that the original model's computation was repaired.

In the prior v~Normal(0,9), theta|v~Normal(0,exp(v)), conditional plus-or-minus-one-SD bands widen as exp(v/2). In transformed coordinates z=theta exp(-v/2), the conditional bands are constant at plus or minus one and z is independent of v. The induced model is unchanged. A likelihood can create dependence again.
In the prior v~Normal(0,9), theta|v~Normal(0,exp(v)), conditional plus-or-minus-one-SD bands widen as exp(v/2). In transformed coordinates z=theta exp(-v/2), the conditional bands are constant at plus or minus one and z is independent of v. The induced model is unchanged. A likelihood can create dependence again.

A reproducible diagnostic workflow

First check the target, units, parameter constraints, and simple known cases. Run multiple chains from suitably dispersed valid starts, recording model version, software, seeds, warmup, and retained draws. Inspect traces or rank plots, modern R-hat, bulk and tail ESS, and HMC-specific warnings. Calculate MCSE for the quantities that drive the conclusion. Investigate failures, rerun adaptation when settings or parameterization change, and compare independent runs and available analytic benchmarks.

Finally separate computational checks from model checks. Accurate posterior simulation does not establish realistic priors, independence assumptions, measurement quality, or predictive adequacy. Later lessons address hierarchical models and posterior predictive assessment. A clear report distinguishes unresolved numerical issues, modeling assumptions, and the practical decision's sensitivity.

Common misconceptions

"R-hat below 1.01 proves convergence." It is a screening result that can miss shared failures.

"ESS is a fraction of draws that are real." It is a variance comparison for a particular summary and can exceed the draw count.

"Divergent draws should be deleted." Investigate and repair the computation rather than selectively discarding warning evidence.

"Non-centering changes the prior to a different scientific assumption." A correctly constructed transformation preserves the induced prior; changing its distribution is a separate modeling choice.

Retrieve before checking

Without looking, list the four stages of modern R-hat: splitting, ranking, folding, and taking a maximum of the two comparisons. Explain why shifting all chains equally can defeat a target-correctness claim. Derive the AR(1) geometric sum and describe which diagnostics you would examine after a divergence.

Check your reasoning

Compute a rank-normalized split comparison and a rank-normalized folded split comparison, then take their maximum. A shared shift preserves ranks and centered variances but changes the intended marginal distribution. Summing a+a squared+... gives a/(1-a), so tau=(1+a)/(1-a). Divergences require examining integration, geometry, and model setup, together with the other diagnostics.

What to carry forward

Key idea: use several diagnostics with explicit definitions and quantity-specific precision. Good diagnostics support a computational argument; they do not replace checking the model, algorithm, or unvisited possibilities.

Sources

  1. Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., and Burkner, P.-C. (2021). Rank-Normalization, Folding, and Localization: An Improved R-hat for Assessing Convergence of MCMC (with Discussion). Bayesian Analysis, 16(2), 667-718. Corrected June 22, 2021; DOI: 10.1214/20-BA1221. Read source.
  2. posterior package, version 1.7.1. Rhat definition and diagnostic limitations. Accessed November 10, 2026. Read source.
  3. posterior package, version 1.7.1. R/convergence.R: rhat, z_scale, backtransform_ranks, and ESS implementations. Read source.
  4. Stan developers. How to Diagnose and Resolve Convergence Problems: divergences, R-hat, ESS, tree depth, and energy diagnostics. Accessed November 10, 2026. Read source.
  5. Stan User Guide, version 2.40. Efficiency Tuning: Neal's funnel and centered/non-centered parameterizations. Accessed November 10, 2026. Read source.
  6. Owen, A. B. Monte Carlo Theory, Methods and Examples. Chapters 11-12: Markov chain Monte Carlo, stationarity, Metropolis-Hastings, and Gibbs sampling. Read source.

All datasets and simulated examples here are constructed teaching examples. Figures are original calculations, not observations from an actual study. Reproducible seeds identify a particular numerical experiment; they do not establish that an algorithm works for every target.

Key terms
Classical R-hat
The square root of a between/within-chain variance estimate divided by within-chain variance.
Rank-normalized split R-hat
A variance comparison applied to normal scores of pooled ranks after splitting chains.
Folded R-hat
A rank-normalized split comparison of absolute deviations from the pooled median, sensitive to scale differences.
Integrated autocorrelation time
One plus twice the summed lag correlations, when the series and limiting argument are appropriate.
Divergence
An HMC warning of excessive numerical integration error under the implementation's criterion.
Non-centered parameterization
Representing a hierarchical effect through a standardized latent variable and a deterministic location-scale transformation.

Module 5: Hierarchical Models, Shrinkage, and Model Checking

Derive partial pooling, integrate uncertain hyperparameters, interpret James-Stein risk and empirical Bayes, compare reproducible regularization methods, and introduce predictive model checking.

Eight Schools: Partial Pooling and Uncertain Group Differences

  • Distinguish sampling uncertainty, between-group variation, and exchangeability in a normal hierarchical model.
  • Derive and calculate a conditional partial-pooling mean and variance, including their limiting cases.
  • Integrate uncertain hyperparameters and compare properly specified prior-sensitivity analyses.
  • Explain the limits of pooling for causal interpretation, ranking, prediction, and computational diagnostics.

Start with eight uncertain effects

The Eight Schools example concerns estimates of SAT coaching effects in eight schools. Rubin's 1981 article is the historical reference. We use the rounded teaching dataset reproduced in the official RStan example, with effects y=(28,8,-3,7,-1,1,18,12) and standard errors s=(15,10,16,11,9,11,10,18). These are estimates and their standard errors, not eight students' test scores, individual-score standard deviations, or exact copies of every digit in the historical experiment.[1][2]

Before calculating, compare school A's estimate 28 with its standard error 15. A large estimated effect can result from a large underlying effect, substantial sampling noise, or both. The table alone cannot tell us the exact contribution of each. Our task is to express uncertainty and make the assumptions connecting schools explicit.

Eight observed school effects are shown with plus or minus 1.96 supplied standard errors. All eight bars cross zero. A dashed line marks the complete-pooling mean 7.6856 under a common effect and flat prior. These sampling-error bars are not full hierarchical posterior intervals.
Eight observed school effects are shown with plus or minus 1.96 supplied standard errors. All eight bars cross zero. A dashed line marks the complete-pooling mean 7.6856 under a common effect and flat prior. These sampling-error bars are not full hierarchical posterior intervals.

The rounded teaching data

SchoolEstimated effect yStandard error s
A2815
B810
C-316
D711
E-19
F111
G1810
H1218

Separate the two levels of variation

Write y_j|theta_j ~ Normal(theta_j,s_j squared), independently across schools conditional on their effects. The standard errors are treated as known in this teaching model. Then theta_j|mu,tau ~ Normal(mu,tau squared), independently conditional on the common mean mu and nonnegative between-school standard deviation tau. Here Normal(mean,variance) uses variance as its second argument. Some software, including Stan, instead supplies a standard deviation.

The first level describes repeated-sampling uncertainty within a school. The second describes a distribution of school effects. A noisy estimate does not prove a highly variable population, and a small fitted tau does not prove that all schools have exactly the same effect. With eight uncertain observations, the data can leave considerable uncertainty about tau.[1][3]

Exchangeability means that, before seeing these school outcomes and conditional on the information included in the model, permuting school labels does not change the joint prior. It is a statement about the information represented in the analysis. If school resources, student preparation, or coaching methods predict different effects, include those predictors or reconsider the grouping. Independence conditional on mu and tau does not imply marginal independence after those shared quantities are integrated out.

Compare no pooling, complete pooling, and partial pooling

No pooling analyzes each school separately. With a flat prior on each theta_j, its posterior is Normal(y_j,s_j squared). The posterior mean equals the observed estimate, but its uncertainty remains. Complete pooling instead assumes one common effect theta. A flat prior on this common effect gives precision sum(1/s_j squared), mean sum(y_j/s_j squared)/sum(1/s_j squared), and standard deviation 1/sqrt(sum(1/s_j squared)). For these data, the mean is 7.68561672 and the standard deviation is 4.07191916.

Complete pooling is a substantive common-effect assumption. No pooling declines to share information through a common effect distribution. Partial pooling allows distinct effects while connecting their estimates through a hierarchy. None is automatically correct for every scientific problem. Compare the assumptions with the study design, prior knowledge, predictive behavior, and intended use.

Derive the conditional update

For tau>0 and fixed mu and tau, multiply the normal likelihood and prior and complete the square. The conditional posterior precision is 1/s_j squared + 1/tau squared. Define B_j=s_j squared/(s_j squared+tau squared), the weight on mu. Then

E(theta_j | y,mu,tau) = (1-B_j)y_j + B_j mu
Var(theta_j | y,mu,tau) = s_j squared * tau squared / (s_j squared+tau squared)

The data-retention weight is 1-B_j. At fixed tau, a larger standard error gives more weight to the group mean. At fixed standard error, larger tau gives less pooling. As tau approaches zero with mu fixed, the distribution collapses to theta_j=mu. As tau grows without bound, the conditional posterior approaches the no-pooling normal. Those are conditional limits, not instructions to estimate tau at infinity.[1][3]

At fixed tau, schools with larger supplied standard errors have larger weights on mu. As tau increases, school-specific conditional means move from mu=8 toward their observed effects. The curves condition on hyperparameters; they do not integrate their uncertainty.
At fixed tau, schools with larger supplied standard errors have larger weights on mu. As tau increases, school-specific conditional means move from mu=8 toward their observed effects. The curves condition on hyperparameters; they do not integrate their uncertainty.

Worked example: condition on mu=8 and tau=10

For school A, B_A=225/(225+100)=9/13. The conditional mean is (4/13)28+(9/13)8=14.15384615. Its variance is 22500/325=69.23076923, giving standard deviation 8.32050294. Because this conditional posterior is normal, a central approximate 95 percent interval is mean plus or minus 1.96 standard deviations, about [-2.15,30.46]. It includes both negative and positive effects.

The number 14.15 answers a question that fixes mu and tau at specified values. It is not a uniquely mandated report for the experiment. If mu and tau are unknown, their uncertainty must be handled. Report the model and the conditioning alongside the estimate. The fixed-parameter calculation is valuable because its arithmetic can be checked by hand.

Conditional school estimates at those settings

SchoolWeight on muConditional meanConditional SD
A0.692314.15388.3205
B0.50008.00007.0711
C0.71914.91018.4800
D0.54757.54757.3994
E0.44753.02766.6896
F0.54754.83267.3994
G0.500013.00007.0711
H0.76428.94348.7416

Specify a full Bayesian teaching model

For a reproducible extension, assign independent proper priors mu~Normal(0,400) and tau~HalfNormal(h). The first prior has standard deviation 20 effect points. HalfNormal(h) is the distribution of the absolute value of a Normal(0,h squared) variable, with density proportional to exp(-tau squared/(2h squared)) for tau>=0. We examine h=5,10,20. These are teaching choices to compare, not priors estimated from the historical investigators' beliefs.[3]

After integrating theta_j out, y_j|mu,tau ~ Normal(mu,s_j squared+tau squared). For a fixed tau, set v_j=s_j squared+tau squared, V_mu=1/(1/400+sum(1/v_j)), and m_mu=V_mu sum(y_j/v_j). Then mu|tau,y is Normal(m_mu,V_mu). Integrate this normal density to obtain a one-dimensional posterior for tau, multiply by the half-normal prior, and normalize.

A concrete calculation uses the unnormalized log density -.5[sum(log(v_j))+log(400/V_mu)+sum(y_j squared/v_j)-m_mu squared/V_mu+tau squared/h squared]. Terms constant in tau may be omitted. Adaptive quadrature over tau from zero to infinity supplies the reference answers below. The interactive model uses a fine finite grid and is checked against that separate integration.

Propagate uncertainty with total variance

After integrating mu but conditioning on tau, the school mean is m_j(tau)=(1-B_j)y_j+B_j m_mu. Its variance is W_j(tau)=s_j squared*tau squared/(s_j squared+tau squared)+B_j squared*V_mu. The second term carries uncertainty in mu. Finally, integrate over tau:

E(theta_j|y) = E_tau[m_j(tau)|y]
Var(theta_j|y) = E_tau[W_j(tau)|y] + Var_tau[m_j(tau)|y]

The last nonnegative term measures how the conditional school mean changes across plausible tau values. Dropping it understates variance relative to averaging the conditional variances in this same model. This identity does not imply that every fully Bayesian interval is wider than every interval obtained by plugging in some selected hyperparameter values. The comparison depends on the selected values, the prior, and the summary.

Conditional means and SDs at mu=8,tau=10 are compared with full posterior summaries under independent mu~Normal(0,400) and tau~HalfNormal(10). School A changes from 14.153846 +/- 8.320503 to 9.810351 +/- 6.944604. These are different conditioning assumptions; total variance does not guarantee every full posterior is wider than every plug-in choice.
Conditional means and SDs at mu=8,tau=10 are compared with full posterior summaries under independent mu~Normal(0,400) and tau~HalfNormal(10). School A changes from 14.153846 +/- 8.320503 to 9.810351 +/- 6.944604. These are different conditioning assumptions; total variance does not guarantee every full posterior is wider than every plug-in choice.

Prior sensitivity: school A under three proper priors

Half-normal scale hPosterior mean of tauA posterior meanA posterior SD
53.2968178.7247395.692422
104.8059789.8103516.944604
205.82169410.5451617.740853
The same Eight Schools data yield different posterior distributions of tau under half-normal scales 5,10,20. School A means are 8.724739,9.810351,10.545161; SDs are 5.692422,6.944604,7.740853. The mean prior stays Normal(0,400). Density curves are normalized on the displayed 0-to-50 range; numeric school summaries integrate tau to infinity.
The same Eight Schools data yield different posterior distributions of tau under half-normal scales 5,10,20. School A means are 8.724739,9.810351,10.545161; SDs are 5.692422,6.944604,7.740853. The mean prior stays Normal(0,400). Density curves are normalized on the displayed 0-to-50 range; numeric school summaries integrate tau to infinity.

Interpret the sensitivity calculation

At h=10, school A's posterior mean is 9.810351 and standard deviation 6.944604. This differs from the conditional answer 14.153846 because the full analysis averages over mu and tau under the specified priors. The three posterior distributions do not describe three different datasets. They describe the same data interpreted under three prior models. Inspect scientifically meaningful conclusions, such as whether effects are practically large, as well as changes in means.

A marginal mixture of normals need not be normal. In the figures, bars labeled mean plus or minus one posterior standard deviation are spread summaries, not 68 percent credible intervals. To obtain a central credible interval, integrate the mixture CDF and find its requested quantiles, or compute quantiles from verified posterior draws. Do not automatically apply normal probability labels to these bars.

Proper priors and small-group problems

A density constant for every tau>=0 is an improper prior for tau regardless of the number of schools. A posterior obtained from an improper prior can nevertheless be proper. For the known-positive-standard-error normal model with flat mu and flat tau, the large-tau marginal tail is proportional to tau^(-(J-1)), so at least three groups are needed for integrability at infinity; near zero the known errors keep the likelihood regular. Different likelihoods or priors require their own propriety analysis. Properness also does not guarantee finite posterior moments of every order.[3]

The half-normal and normal priors used here are proper, and the bounded known-error likelihood gives a finite positive normalizing constant. Their parameters still matter. A very broad proper prior is not automatically harmless. Inspect plausible effect sizes through prior prediction and examine sensitivity, particularly when few groups inform the between-group scale.

Computation, new groups, and scientific conclusions

The non-centered representation z_j~Normal(0,1), theta_j=mu+tau*z_j induces the same hierarchy. It can improve sampling when school effects are weakly informed, especially near small tau. With strongly informative data, centering can work better. There is no universal sample-size threshold that makes one representation preferable. Recheck divergences, modern R-hat, effective sample sizes, and precision after fitting.[4]

For an exchangeable new school, the latent effect is drawn from Normal(mu,tau squared), then averaged over the posterior of mu and tau. Its variance is E(tau squared|y)+Var(mu|y). Predicting a new noisy estimate additionally includes that estimate's sampling variance. A latent effect and an observed future estimate therefore need different predictive distributions.

The hierarchy shares information; it does not repair confounding, measurement bias, omitted treatment differences, or an inappropriate exchangeability assumption. Causal interpretation depends on the experiment and analysis that produced each effect. Choosing a school, estimating each effect, and ranking all schools are different decision problems. Posterior means minimize posterior squared error for estimating individual effects, but a ranking or deployment policy needs its own loss and uncertainty analysis. Partial pooling alone is not a universal multiple-testing error guarantee.

Common misconceptions

  • A larger observed effect does not establish a larger true effect.
  • The shrinkage formula conditional on mu and tau is not the full marginal posterior when they are unknown.
  • Small tau does not remove uncertainty about mu.
  • A proper posterior does not make its improper prior proper.
  • A reparameterization that preserves the induced model changes computation, not the scientific prior.

Retrieve before checking

Close the equations. Reconstruct B_j from the requirement that a highly imprecise school receives more weight on mu. Explain the two sources of variance remaining after mu and tau become uncertain. On a later day, derive the conditional precision and recompute school A with tau=5. Interleave this with the earlier normal-normal updating lesson: identify which quantity is being treated as known in each problem.

What to carry forward

Key idea: Partial pooling is a model-based compromise whose amount and uncertainty depend on both sampling errors and the hierarchy. Keep conditional and marginal answers separate, justify the grouping, and state the prior settings whenever reporting an estimate.

Sources

  1. Stan developers. RStan: the R interface to Stan. Eight Schools data and hierarchical model. Accessed November 13, 2026. Read source.
  2. Rubin, D. B. (1981). Estimation in Parallel Randomized Experiments. Journal of Educational Statistics, 6(4), 377-401. ETS publication record. Read source.
  3. Gelman, A. (2006). Prior distributions for variance parameters in hierarchical models. Bayesian Analysis, 1(3), 515-533. Author-hosted paper. Read source.
  4. Stan User Guide, version 2.40. Efficiency Tuning: hierarchical models and non-centered parameterizations. Accessed November 13, 2026. Read source.

Original calculations and diagrams in this lesson use the stated data, models, and settings. Historical tables are identified separately from constructed examples. Numerical agreement checks arithmetic; it does not establish that a model describes a new population.

Key terms
Partial pooling
Sharing information through a model while allowing distinct group effects.
Exchangeability
Invariance of a joint distribution to relabeling after conditioning on the information included in the model.
Hyperparameter
A parameter of the distribution assigned to other parameters, such as mu or tau in this hierarchy.
Conditional posterior
A posterior that treats explicitly named quantities as fixed, such as theta_j given y, mu, and tau.
Total variance
Marginal variance equals the expected conditional variance plus the variance of the conditional expectation.
Non-centered parameterization
A representation such as theta_j=mu+tau*z_j that samples standardized latent variables while preserving the induced hierarchy.

Empirical Bayes and James-Stein: What Shrinkage Guarantees

  • State the known-variance normal-means model, total squared-error loss, and repeated-sampling meaning of risk.
  • Calculate fixed-target and grand-mean James-Stein estimates, including positive-part versions and dimension requirements.
  • Connect hierarchical Bayes and empirical Bayes while distinguishing estimated from integrated hyperparameters.
  • Audit historical prediction results and simulations without claiming improvement for every coordinate or realized dataset.

A precise question about better estimates

Suppose X=(X_1,...,X_p) has independent Normal(theta_i,sigma squared) components, where the common positive variance sigma squared is known. We estimate the fixed unknown vector theta. Under total squared-error loss, L(theta,delta)=sum_i(delta_i-theta_i) squared. Risk is R(theta,delta)=E_theta[L(theta,delta(X))], an average over repeated datasets from the stipulated sampling distribution.

The estimator delta_0(X)=X has risk p*sigma squared: each coordinate contributes sigma squared. This is an expectation, not the squared error on every realized dataset. A different loss, such as error in the largest coordinate or the cost of selecting a poor school, defines a different decision problem. Keep the distribution and loss attached to every claim of superiority.[1]

A fixed mean vector and known common noise variance define a sampling distribution. Each new dataset produces estimates and a total squared loss. Risk averages that loss over datasets. An improvement in expected total loss does not imply improvement for every dataset or coordinate.
A fixed mean vector and known common noise variance define a sampling distribution. Each new dataset produces estimates and a total squared loss. Risk averages that loss over datasets. An improvement in expected total loss does not imply improvement for every dataset or coordinate.

The fixed-target James-Stein rule

Choose a fixed target vector a before observing X. Let S=sum_i(X_i-a_i) squared. For p>=3, the James-Stein rule is delta_JS = a + [1-(p-2)*sigma squared/S]*(X-a), with an arbitrary definition at S=0, an event of probability zero under the continuous model. A common example takes a=0. Under the stated independent normal model, known common variance, and unweighted total squared-error loss, its risk is smaller than that of X for every fixed theta.[1]

The quantifier is important: for every theta, average over the possible data. It does not say that for every dataset, the realized loss is smaller. It also does not promise smaller risk for each individual coordinate. The target can be scientifically implausible and the total-risk theorem still hold under its mathematical assumptions, but that does not make the resulting analysis appropriate for every scientific purpose.

Why the risk can decrease

For target zero, write delta=X+g(X), with g(X)=-c*X/S and c=(p-2)*sigma squared. Expanding squared error gives p*sigma squared + E||g|| squared + 2E[(X-theta) dot g]. The normal integration-by-parts identity converts the last term to 2*sigma squared*E[div g]. Here ||g|| squared=c squared/S and div g=-c*(p-2)/S.

Substitution gives R(theta,delta_JS)=p*sigma squared-(p-2) squared*sigma^4*E_theta(1/S). For p>2 the expectation is finite and positive, so the subtraction is positive. This derivation uses the normal identity and integrability conditions, not a claim that the realized data tell us theta exactly. A translated fixed target follows by replacing X with X-a.[1]

At theta=a, S/sigma squared follows a chi-square distribution with p degrees of freedom, whose inverse expectation is 1/(p-2). The raw James-Stein rule therefore has risk 2*sigma squared there, compared with p*sigma squared for X. This is one exact benchmark for a simulation.

Positive-part shrinkage avoids reversing the direction

If S is smaller than (p-2)*sigma squared, the raw multiplier is negative. The estimate then crosses the target. The positive-part rule replaces the multiplier by max(0,1-(p-2)*sigma squared/S). It has lower total squared-error risk than the raw James-Stein rule under the same assumptions. At S=0 set the estimate equal to the target. This risk ordering remains an expected-loss statement.[1]

For p=3, sigma=1, a=0, and the constructed observation X=(0.2,0,0), S=0.04. The raw multiplier is 1-1/0.04=-24, giving (-4.8,0,0). The positive-part multiplier is zero, giving (0,0,0). This arithmetic explains the positive-part modification; observing one improvement is not its proof.

An estimated grand mean costs a dimension

Suppose we shrink toward Xbar, estimated from these same observations. The grand-mean rule is delta_i = Xbar + [1-(p-3)*sigma squared/S_c]*(X_i-Xbar), where S_c=sum_i(X_i-Xbar) squared. The positive-part version again truncates the multiplier below at zero. This is not obtained by inserting a data-dependent a into the fixed-target formula while keeping p-2.[1][2]

An orthogonal transformation separates the unshrunk mean direction from p-1 residual directions. Applying the fixed-target theorem to that residual vector uses (p-1)-2=p-3 and requires p-1>=3, hence p>=4 for a nontrivial strict improvement. At p=3, this particular grand-mean multiplier is one and the rule equals X. The familiar threshold of three coordinates belongs to the fixed-target rule, not this estimated-target rule.

For X=(2,0,0,0), p=4 and known unit noise, fixed-zero James-Stein gives (1,0,0,0), whereas estimated-grand-mean shrinkage gives (1.5,1/6,1/6,1/6). The dimension adjustment is p-2 for a fixed target and p-3 for an estimated grand mean. Strict improvement for the latter requires at least four coordinates.
For X=(2,0,0,0), p=4 and known unit noise, fixed-zero James-Stein gives (1,0,0,0), whereas estimated-grand-mean shrinkage gives (1.5,1/6,1/6,1/6). The dimension adjustment is p-2 for a fixed target and p-3 for an estimated grand mean. Strict improvement for the latter requires at least four coordinates.

Worked example: expected gain does not guarantee realized gain

Take p=4, known sigma=1, and the constructed observation X=(2,0,0,0). Its grand mean is 0.5 and S_c=3. The multiplier is 1-1/3=2/3, giving estimates (1.5,1/6,1/6,1/6). If the actual fixed mean vector happened to be (2,0,0,0), X would have zero loss on this realization, while shrinkage would have loss (0.5) squared+3(1/6) squared=1/3.

This example does not contradict the theorem. The theorem compares expectations over all datasets at that theta. Nor can a simulation prove a uniform theorem by trying finitely many theta values. It can check an implementation against known cases and reveal what repeated-sampling performance looks like.

See aggregate gain and individual harm together

The interactive model generates independent unit-variance normal observations with a fixed mean vector. You choose dimension, the common baseline, one coordinate's additional signal, a fixed-zero or estimated-grand-mean target, run length, and seed. It reports raw-estimate, raw James-Stein, and positive-part losses, plus per-coordinate results. The same data are used by all three rules, allowing a paired comparison.

For p=6, theta=(3,0,0,0,0,0), grand-mean shrinkage, 2000 replications, and seed 410, the average total losses are 5.978079 for X, 5.013689 for raw James-Stein, and 4.895223 for its positive part. Yet the first coordinate's average loss rises from 1.027510 for X to 1.578024 for the positive part. Across these replications the positive part has smaller realized total loss about 80.65 percent of the time, not every time.

The paired positive-part-minus-X difference is -1.082856 with estimated Monte Carlo standard error 0.037333. For independent replications, compute that standard error from the sample standard deviation of the paired loss differences divided by square root replication count. An approximate normal interval addresses uncertainty in this simulation average, not posterior uncertainty about theta and not a proof of dominance. Try a new seed and increase the replication count before interpreting small differences.

A reproducible 2000-replication unit-normal experiment at theta=(3,0,0,0,0,0), seed 410, compares grand-mean shrinkage. Positive-part average total loss is 4.895223 versus 5.978079 for raw observations, but first-coordinate loss increases from 1.027510 to 1.578024. The positive part wins 80.65 percent of realizations, not all.
A reproducible 2000-replication unit-normal experiment at theta=(3,0,0,0,0,0), seed 410, compares grand-mean shrinkage. Positive-part average total loss is 4.895223 versus 5.978079 for raw observations, but first-coordinate loss increases from 1.027510 to 1.578024. The positive part wins 80.65 percent of realizations, not all.

Connect the rule to empirical Bayes

In a normal hierarchy, theta_i|mu,tau ~ Normal(mu,tau squared) and X_i|theta_i ~ Normal(theta_i,sigma squared). With mu and tau fixed, the Bayes posterior mean is mu+c(X_i-mu), where c=tau squared/(sigma squared+tau squared). Empirical Bayes estimates hyperparameters or a shrinkage factor from the data and inserts those estimates into a Bayes rule. Full Bayes assigns hyperpriors and integrates their posterior uncertainty.[1][2]

Under this hierarchical sampling model, S_c/(sigma squared+tau squared) has a chi-square distribution with p-1 degrees of freedom. For p>3, E[1/chi-square_(p-1)]=1/(p-3), so (p-3)*sigma squared/S_c is unbiased for the weight sigma squared/(sigma squared+tau squared) on the group mean. Substituting it motivates the grand-mean rule. The expectation here averages under the marginal random-effects model. The frequentist risk theorem instead holds at each fixed theta under its stated normal observation model.

This empirical Bayes explanation and the frequentist theorem answer related but different questions. Estimating hyperparameters by marginal likelihood is another empirical Bayes strategy and need not give this exact formula. A positive-part estimate is useful for point prediction, but a confidence or credible interval needs a separate justified method. Attaching a conditional Bayes interval while ignoring estimated hyperparameter uncertainty does not automatically produce a calibrated interval.

The historical baseball comparison

Efron and Morris reported 18 players' first 45 at-bats in 1970 and their later observed batting averages. The original paper used a variance-stabilizing transformation, approximately sqrt(45)*arcsin(2y-1), before applying grand-mean shrinkage. The binomial-to-normal step is an approximation, not an exact application of the Gaussian theorem.[1]

For a transparent raw-rate teaching comparison, use exact initial fractions hits/45 and the three-decimal later averages printed in the paper's Table 1. Set the common approximate variance to Xbar(1-Xbar)/45. This is a newly computed approximation, not a claim to reproduce the paper's transformed estimates. The table identifies Williams as Chicago, American League; it does not substitute the different Williams entry found in a later software dataset.

All 18 published cases and a specified raw-rate calculation

PlayerHits / 45Later average, publishedOur shrunken rate
Clemente18/450.3460.293914
F. Robinson17/450.2980.289210
F. Howard16/450.2760.284507
Johnstone15/450.2220.279804
Berry14/450.2730.275100
Spencer14/450.2700.275100
Kessinger13/450.2630.270397
L. Alvarado12/450.2100.265693
Santo11/450.2690.260990
Swoboda11/450.2300.260990
Unser10/450.2640.256287
Williams (Chi, AL)10/450.2560.256287
Scott10/450.3030.256287
Petrocelli10/450.2640.256287
E. Rodriguez10/450.2260.256287
Campaneris9/450.2850.251583
Munson8/450.3160.246880
Alvis7/450.2000.242176
All 18 Table 1 cases from Efron and Morris (1975) are used. Exact initial hits/45 and published three-decimal later averages give raw-rate squared discrepancies 0.07531695 and 0.02130691 under the stated approximate-variance shrinkage. Swoboda and E. Rodriguez get worse. Later observed rates are noisy outcomes, not known abilities. This differs from the original paper's transformed analysis.
All 18 Table 1 cases from Efron and Morris (1975) are used. Exact initial hits/45 and published three-decimal later averages give raw-rate squared discrepancies 0.07531695 and 0.02130691 under the stated approximate-variance shrinkage. Swoboda and E. Rodriguez get worse. Later observed rates are noisy outcomes, not known abilities. This differs from the original paper's transformed analysis.

Interpret the raw-rate comparison

The initial grand mean is 215/810=0.265432099. The approximate variance is 0.00433284222 and S_c=0.08244170096. Thus c=1-15(0.00433284222)/0.08244170096=0.211653417. Compare each estimate with the published rounded later average. Total squared discrepancies are 0.075316951 for the raw rates and 0.021306915 for these shrunken rates. Swoboda and E. Rodriguez have larger discrepancies after shrinking. These numbers depend on the specified raw-rate calculation and rounding.

The original paper's transformed analysis reported total squared discrepancies 17.56 and 5.01 on its transformed scale. Do not compare those magnitudes directly with our raw-proportion losses. They use a different transformation and scale. The paper also discusses exceptional players and methods that limit excessive movement for individual coordinates.[1]

Historical outcomes are not known true abilities

The later averages are themselves noisy observations over unequal numbers of at-bats. Predicting those observations differs from observing the latent probabilities without error. Under an additional stable-ability, conditionally independent binomial model, expected squared prediction loss for a later observed rate equals estimation risk for the latent probability plus the later rate's sampling variance. That last term is common across prediction rules if the observation process is the same, but it remains variable in an actual realized season.

Playing conditions and ability can change over time, and a historical cohort need not be representative of future players. The exact normal known-variance theorem does not automatically transfer to these binomial data with estimated, unequal variances. Choosing a subgroup after inspecting its later performance also biases an evaluation. Define the population, target, prediction time, loss, and information allowed before comparing methods.[1][2]

Choose grouping and loss deliberately

A shared measurement scale is not a sufficient reason to pool unrelated effects. Prior information can suggest multiple groups, group-level predictors, or a more flexible distribution. If one coordinate has unusually high practical importance, an unweighted total loss may conceal a costly failure. Unequal variances, correlated observations, weighted losses, and data-chosen targets require a suitable extension or a new risk analysis; do not reuse the simplest formula unchanged.

For a prediction study, choose tuning methods using training data, evaluate on genuinely held-out outcomes, and describe uncertainty in the comparison. If you need inference about individual parameters or simultaneous coverage, evaluate the intervals and joint statements separately from point-estimation risk. A good prediction score does not by itself validate causal claims or a probability model.

Common misconceptions

  • Uniformly lower risk means lower expected total loss at every theta, not lower loss for every dataset.
  • A total-risk improvement can coexist with worse individual-coordinate risk.
  • Fixed-target shrinkage needs at least three coordinates; the displayed estimated-grand-mean rule needs at least four for a nontrivial gain.
  • A historical future average is an observation, not the exact true parameter.
  • Empirical Bayes estimation and full Bayesian integration handle hyperparameters differently.

Retrieve before checking

Without reading the formulas, state the observation distribution, the known quantity, the target, and the loss required by the theorem. Reconstruct why p-3 appears when the grand mean is estimated. On a later day, explain the four-coordinate counterexample and the baseball comparison to someone who thinks better risk means every prediction improves.

Putting it together

Remember: A shrinkage guarantee is inseparable from its sampling model, loss, target, and expectation. Use the theorem precisely, and evaluate the separate scientific question your estimates will support.

Sources

  1. Efron, B., and Morris, C. (1975). Data Analysis Using Stein's Estimator and its Generalizations. JASA, 70(350), 311-319. DOI: 10.1080/01621459.1975.10479864. Published-paper copy hosted at UC Merced. Read source.
  2. Efron, B. (2010). The Future of Indirect Evidence. Statistical Science, 25(2), 145-157. DOI: 10.1214/09-STS308. Author-deposited electronic reprint. Read source.

Original calculations and diagrams in this lesson use the stated data, models, and settings. Historical tables are identified separately from constructed examples. Numerical agreement checks arithmetic; it does not establish that a model describes a new population.

Key terms
Risk
Expected loss over repeated datasets from a specified sampling distribution at a fixed parameter.
James-Stein estimator
A data-dependent shrinkage rule that improves total squared-error risk under specified normal-means assumptions.
Positive-part rule
A shrinkage rule that replaces a negative retention multiplier by zero.
Empirical Bayes
Estimating prior hyperparameters or a Bayes-rule component from the data before using it for inference.
Grand-mean shrinkage
Moving coordinates toward their estimated common average, with dimension adjustment for estimating that target.
Paired Monte Carlo standard error
The sample SD of method-by-method loss differences divided by square root independent replication count.

Ridge, Lasso, and Horseshoe: Priors, Risk, and Reproducible Estimates

  • Derive a fixed linear shrinkage rule's bias, variance, and risk under a normal-means model.
  • Connect ridge and lasso objectives to Gaussian and Laplace priors with explicit scaling, distinguishing posterior modes from distributions.
  • Calculate a horseshoe posterior mean by integrating local-scale uncertainty and interpret continuous shrinkage without exact inclusion probabilities.
  • Compare methods reproducibly, specify global and slab scales, and separate model fitting from held-out evaluation.

Start with a controlled normal-means problem

Observe Y_j|beta_j ~ Normal(beta_j,1), independently. The known observation standard deviation is one. We will compare estimates of beta under explicit tuning choices, with squared error as one possible loss. This simple model also arises in Gaussian regression with orthonormal columns X transpose X=I and known unit error variance, after reducing the data to the least-squares coefficient estimates. It does not represent every regression design.

In the constructed examples, the true vector is supplied so that realized error can be calculated. In a real dataset, true coefficients are unknown. The purpose is to understand how a method behaves, not to choose the setting that happens to be closest to an answer unavailable in practice.

Derive bias, variance, and risk before comparing methods

For one observation Y~Normal(beta,sigma squared), consider delta=cY with fixed 0<=c<=1. Its expectation is c*beta, its bias is -(1-c)*beta, and its variance is c squared*sigma squared. Therefore R(beta,cY)=(1-c) squared*beta squared+c squared*sigma squared. The unshrunk estimator Y has risk sigma squared.

For 0<=c<1, linear shrinkage has lower risk exactly when beta squared < sigma squared*(1+c)/(1-c). At equality the risks match; at c=1 the rule is Y everywhere. With sigma=1 and c=0.5, shrinkage improves risk when |beta|<sqrt(3). At beta=0 the risk is 0.25, while at beta=3 it is 2.5, larger than the unshrunk risk 1. This is an expected-loss calculation. A particular dataset can order the methods differently.

If beta were known, the risk-minimizing constant would be c=beta squared/(beta squared+sigma squared). It depends on the unknown parameter and is called an oracle comparison, not an available estimation procedure. This explains why adapting the amount of shrinkage can help. It does not prove that an estimated tuning rule always matches the oracle.

With unit noise and fixed retention one half, risk equals one quarter beta squared plus one quarter. It is below the unshrunk risk one only for absolute beta below square root three. Risk is 0.25 at beta zero and 2.5 at beta three. The graph concerns true beta, not a realized observation.
With unit noise and fixed retention one half, risk equals one quarter beta squared plus one quarter. It is below the unshrunk risk one only for absolute beta below square root three. Risk is 0.25 at beta zero and 2.5 at beta three. The graph concerns true beta, not a realized observation.

Ridge corresponds to a Gaussian prior

In the unit-noise normal-means model, use independent beta_j~Normal(0,t squared), with fixed t>0. The posterior is Normal(cY_j,c), where c=t squared/(1+t squared). Its mean and mode coincide because this conditional posterior is normal. Maximizing it is equivalent to minimizing 0.5*sum(Y_j-beta_j) squared + 0.5*lambda_R*sum(beta_j squared), with lambda_R=1/t squared and c=1/(1+lambda_R).[1]

For a general Gaussian regression with known variance sigma squared, writing the objective as 0.5*||y-X beta|| squared + 0.5*lambda_R*||beta|| squared corresponds to prior covariance (sigma squared/lambda_R)I. For lambda_R>0, the mode is (X transpose X+lambda_R I)^(-1)X transpose y. In an eigenbasis, directions with eigenvalue d have relative shrinkage d/(d+lambda_R) when the corresponding least-squares direction exists. Thus a single multiplier for every coefficient is special to the orthonormal case.

Scaling predictors changes what equal prior scales or equal penalties mean. Decide whether and how to standardize, treat the intercept separately when appropriate, and record the convention. A hyperprior on t requires integration and generally produces a non-normal marginal posterior; the fixed-t mean-mode equality need not survive.

Lasso is a mode, not a point mass in the posterior

With unit noise and independent Laplace priors having density (lambda_L/2)exp(-lambda_L*|beta_j|), the negative log posterior, apart from constants, is 0.5*sum(Y_j-beta_j) squared + lambda_L*sum|beta_j|. For orthonormal normal means its mode is soft thresholding: sign(Y_j)*max(|Y_j|-lambda_L,0). Thus lambda_L=1 sends observations with |Y_j|<=1 to an exact zero mode.[1][2]

The one-half in the squared-error term matters. If an author instead writes unscaled squared error plus lambda times the absolute-value penalty, the threshold is lambda/2. Different software may also divide its objective by sample size. Compare the whole objective before identifying penalty values or prior scales.

The Laplace posterior is continuous and generally asymmetric when Y is nonzero. Its mean is generally different from its mode; at Y=0 symmetry makes the mean exactly zero. A continuous posterior assigns probability zero to the single point beta=0 even if its mode is zero. A credible interval can include or exclude zero depending on the data and prior. There is no rule that every such interval must straddle zero.[2]

The horseshoe separates global and local scales

A unit-noise horseshoe model uses beta_j|lambda_j,tau ~ Normal(0,tau squared*lambda_j squared), with independent lambda_j~HalfCauchy(1). The positive global scale tau controls overall shrinkage; each local lambda_j can allow an individual coefficient to escape it. A full hierarchical analysis also specifies a prior for tau. In the numerical explorer we instead fix tau deliberately so students can isolate its effect.[3][4]

Conditional on lambda_j and tau, define kappa_j=1/(1+tau squared*lambda_j squared). The posterior mean is (1-kappa_j)Y_j and its variance is 1-kappa_j. After integrating the local scale, the mean becomes E(beta_j|Y_j,tau)=[1-E(kappa_j|Y_j,tau)]Y_j. Replacing the random kappa by an arbitrary convenient value would not compute this marginal mean.

At tau=1, the prior for kappa is Beta(1/2,1/2). Its density rises without bound near zero and one, but it places no probability mass at either endpoint. The half-Cauchy density for lambda is finite at zero; the marginal horseshoe coefficient density is unbounded there. These are three different distributions, so describing all of them as the same spike is misleading. A continuous horseshoe posterior has no exact inclusion probability P(beta_j=0) greater than zero.[3]

Compute a reproducible horseshoe mean

For fixed tau and unit noise, the posterior density of kappa, up to normalization, is exp(-Y squared*kappa/2)/[sqrt(1-kappa)*(1+(tau squared-1)*kappa)] on 0<kappa<1. Put u=sqrt(1-kappa). The endpoint singularity cancels with the change-of-variable Jacobian. Define w(u)=exp[-Y squared*(1-u squared)/2]/[tau squared+(1-tau squared)*u squared] on 0<=u<=1.

Compute I_r=integral u^r*w(u)du for r=0,2,4. Then the posterior mean is Y*I_2/I_0. Total variance gives Var(beta|Y,tau)=I_2/I_0+Y squared*[I_4/I_0-(I_2/I_0) squared]. Constants cancel from these ratios. Independent adaptive quadrature supplies the lesson's reference values; the browser uses composite Simpson integration checked against them. The result is a deterministic numerical integral, not a claimed MCMC output.

At Y=3.2 and tau=0.2, the actual marginal posterior mean is 1.84618327. It is not approximately 3.15. At Y=-1.4 the mean is -0.20894361. The large local-scale tails permit weaker shrinkage of strong signals, but a moderately large observation can still shrink substantially when the global scale is small.

Response curves show ridge retention one half, lasso threshold one, and the numerically integrated horseshoe mean at fixed tau=0.2. At Y=3.2 the horseshoe mean is 1.84618327. Lasso alone has a flat zero segment here. The identity line is an unshrunk reference, not the known true coefficient.
Response curves show ridge retention one half, lasso threshold one, and the numerically integrated horseshoe mean at fixed tau=0.2. At Y=3.2 the horseshoe mean is 1.84618327. Lasso alone has a flat zero segment here. The identity line is an unshrunk reference, not the known true coefficient.

Worked example: compare four specified rules

Construct beta=(3,0,0,0,0,0,0,0,0,0) and observed Y=(3.2,-0.4,0.6,1.1,-0.9,0.3,-1.4,0.7,-0.2,0.5). These are stipulated values, not a random dataset selected to demonstrate a universal ranking. Compare the unshrunk Y, ridge with c=0.5, lasso with threshold 1, and the marginal horseshoe mean with fixed tau=0.2. Use all ten coordinates.

Computed estimates for the constructed vector

jTrue betaObserved YRidge c=.5Lasso threshold 1Horseshoe tau=.2
133.21.60002.20001.846183
20-0.4-0.20000.0000-0.044054
300.60.30000.00000.068230
401.10.55000.10000.144047
50-0.9-0.45000.0000-0.110173
600.30.15000.00000.032677
70-1.4-0.7000-0.4000-0.208944
800.70.35000.00000.081295
90-0.2-0.10000.0000-0.021613
1000.50.25000.00000.055863
A stipulated sparse ten-coordinate example gives total squared errors 5.41 for raw observations, 3.3025 for ridge c=.5, 0.81 for lasso threshold 1, and 1.42569836 for integrated horseshoe means at tau=.2. Lasso has the lowest error here. Changing signal, noise, or tuning can change the ordering.
A stipulated sparse ten-coordinate example gives total squared errors 5.41 for raw observations, 3.3025 for ridge c=.5, 0.81 for lasso threshold 1, and 1.42569836 for integrated horseshoe means at tau=.2. Lasso has the lowest error here. Changing signal, noise, or tuning can change the ordering.

Interpret the constructed comparison

The respective total squared errors are 5.41, 3.3025, 0.81, and 1.42569836. Lasso wins for these particular values and settings. It makes seven of the nine zero-signal coordinates exactly zero and retains small nonzero estimates for the observations 1.1 and -1.4. The horseshoe gives continuous estimates close to zero for many coordinates, while still shrinking the first coefficient substantially.

This comparison does not establish that lasso is generally best for sparse signals, or that ridge is always best for dense signals. Change the truth pattern, noise realization, tuning, and evaluation loss, and the ordering can change. The explorer changes a known teaching truth while keeping the listed error offsets fixed. That controlled comparison isolates the effect of a different signal pattern; it is not a repeated-sampling risk experiment.

Regularize the largest effects when the problem needs it

The regularized horseshoe introduces a slab scale c_s>0 and replaces lambda_j squared by lambda_tilde_j squared=c_s squared*lambda_j squared/(c_s squared+tau squared*lambda_j squared). Its conditional coefficient variance is tau squared*lambda_tilde_j squared. For fixed finite c_s, this variance is bounded above by c_s squared and approaches that bound as lambda_j grows. As c_s grows without bound, the ordinary horseshoe is recovered.[4]

The variance cap does not bound the coefficient itself. A normal distribution still has support on the entire real line. If c_s is also assigned a prior, describe that additional uncertainty and its tail behavior. A finite slab can be valuable when the likelihood weakly identifies very large coefficients, such as in separated logistic regression. This is a reason to examine regularization, not permission to ignore a poor likelihood or sampling diagnostics.

With global tau=.2 and fixed slab SD=2, the ordinary horseshoe conditional prior variance grows with lambda squared, while the regularized variance approaches four. The limiting Normal(0,4) has probability outside [-2,2]; a variance cap is not a hard coefficient bound.
With global tau=.2 and fixed slab SD=2, the ordinary horseshoe conditional prior variance grows with lambda squared, while the regularized variance approaches four. The limiting Normal(0,4) has probability outside [-2,2]; a variance cap is not a hard coefficient bound.

Calibrate the global scale in the actual units

Under an approximately uncorrelated standardized Gaussian-regression design with X transpose X approximately nI, a useful reference scale is tau_0=[p_0/(D-p_0)]*sigma/sqrt(n), where D is the number of penalized predictors and 0<p_0<D expresses a prior guess about effective signal count. For D=100, p_0=10, n=400, and sigma=2, tau_0=1/90=0.01111111. This guides a prior scale; it is not a rule that exactly ten coefficients become nonzero.[5]

This regression scaling is different from the explorer's unit-noise normal-means coordinates, where no sample-size factor was introduced. Strongly correlated predictors, unknown noise, different predictor scaling, or a non-Gaussian likelihood require a suitable adaptation. The global prior and slab prior encode different beliefs: approximate sparsity and plausible magnitude for the larger effects.

Tuning, prediction, and uncertainty need separate checks

Cross-validation chooses settings by held-out predictive performance. Empirical Bayes commonly chooses hyperparameters by marginal likelihood. Full Bayes places priors on those quantities and integrates them. These procedures are not interchangeable definitions, and they can choose different amounts of shrinkage.[2][4][5]

When evaluating prediction, fit preprocessing and tuning within each training split, then evaluate the held-out observations. Preserve a final test set when it is part of the study design, and avoid selecting a method by looking at that set repeatedly. For time-dependent or grouped data, the split must respect the prediction task. Report the loss, comparison uncertainty, and baseline, rather than only which method has the smallest displayed number.

For Bayesian inference, check computation, prior predictive implications, sensitivity, and posterior predictive behavior. If the task is selecting a compact variable set, define a selection rule and assess it separately from continuous coefficient estimation. A point-mass spike-and-slab prior can express exact-zero probabilities, while continuous priors require a different decision summary. No penalty or prior automatically resolves confounding, collinearity, missing variables, or causal interpretation.

Common misconceptions

  • Lower risk under some parameter values does not imply lower realized error on every dataset.
  • A zero lasso mode is not a positive posterior probability of an exact zero under a continuous Laplace prior.
  • A horseshoe mean requires integrating the local scale; an attractive guessed value is not a computed result.
  • A regularized-horseshoe variance cap is not a hard bound on beta.
  • Penalty values and prior scales can only be compared after checking normalization, noise scale, and predictor units.

Retrieve before checking

Reconstruct the bias-variance identity and the threshold |beta|<sqrt(3) for c=0.5 and unit noise. Derive soft thresholding by differentiating on beta>0 and beta<0 and checking the corner at zero. On a later day, explain why integrating kappa differs from fixing it, then reproduce one row of the constructed-vector table.

What to remember

The point: Shrinkage methods encode different assumptions about signal size and sparsity, and their estimates must be calculated under explicit settings. Separate expected risk, realized error, predictive evaluation, and posterior uncertainty whenever interpreting a comparison.

Sources

  1. Tibshirani, R. (1996). Regression Shrinkage and Selection via the Lasso. JRSS Series B, 58(1), 267-288. Published-paper copy hosted at Duke University. Read source.
  2. Park, T., and Casella, G. (2008). The Bayesian Lasso. JASA, 103(482), 681-686. DOI: 10.1198/016214508000000337. Published-paper copy hosted at UC Berkeley. Read source.
  3. Carvalho, C. M., Polson, N. G., and Scott, J. G. (2009). Handling Sparsity via the Horseshoe. Proceedings of AISTATS, PMLR, 5, 73-80. Read source.
  4. Piironen, J., and Vehtari, A. (2017). Sparsity information and regularization in the horseshoe and other shrinkage priors. Electronic Journal of Statistics, 11(2), 5018-5051. DOI: 10.1214/17-EJS1337SI. Inspected author manuscript, arXiv:1707.01694v1. Read source.
  5. Piironen, J., and Vehtari, A. (2017). On the Hyperprior Choice for the Global Shrinkage Parameter in the Horseshoe Prior. PMLR, 54, 905-913. Read source.

Original calculations and diagrams in this lesson use the stated data, models, and settings. Historical tables are identified separately from constructed examples. Numerical agreement checks arithmetic; it does not establish that a model describes a new population.

Key terms
Ridge regression
Squared-error fitting with a squared-coefficient penalty, corresponding to a Gaussian prior under stated scaling.
Soft thresholding
The map sign(y)*max(|y|-lambda,0), the lasso mode for the stated orthonormal unit-noise objective.
Global-local shrinkage
A hierarchy with a shared scale and individual local scales that permit different amounts of shrinkage.
Horseshoe prior
A continuous normal scale-mixture prior with half-Cauchy local scales and a specified global scale or hyperprior.
Regularized horseshoe
A horseshoe extension with a slab scale limiting the conditional prior variance of large local-scale coefficients.
Oracle comparison
An idealized rule using unknown true parameters, useful as a benchmark but unavailable to the analyst.

Posterior Predictive Checks: Replication, Discrepancies, and Model Revision

  • Construct a posterior predictive replication that preserves the sampling design and propagates parameter uncertainty.
  • Calculate and interpret mean and minimum checks under an explicitly specified normal model.
  • Diagnose count-data discrepancies without confusing overdispersion, parameter uncertainty, and structural zeros.
  • Document model revision, simulation precision, and the limits of data-dependent checks.

A good average can conceal a poor model

Newcomb's 66 light measurements provide a compact example of why checking one summary is insufficient. We use every value in the Bayesian Data Analysis authors' data file. The file identifies the units as deviations from 24,800 nanoseconds and attributes the observations to Stigler (1977). Their sum is 1730, mean 26.212121, sample standard deviation 10.745325, and minimum -44. The next-lowest measurement is -2. These observations are retained without declaring either one a recording error.[1]

Imagine a model that reproduces the average accurately but rarely generates a measurement as small as -44. Its estimate of location can look reasonable while its description of the tails is poor. Begin with two distinct questions: which features of the data matter for the intended use, and what replicated observations would this model generate? A model check targets a feature under stated assumptions. It does not assign a probability that the entire model is true.[2]

All 66 Newcomb measurements from the BDA authors are displayed in supplied order and in a histogram. Mean 26.212121, minimum -44, and next minimum -2. Neither low measurement is declared erroneous.
All 66 Newcomb measurements from the BDA authors are displayed in supplied order and in a histogram. Mean 26.212121, minimum -44, and next minimum -2. Neither low measurement is declared erroneous.

Specify the model before checking it

For a transparent teaching calculation, assume independent y_i|mu ~ Normal(mu,121) for i=1,...,66, with mu~Normal(25,400). Here the second normal argument is variance. The observation standard deviation is fixed at 11 and the prior standard deviation is 20. These are explicit teaching choices, not known historical instrument specifications. We do not substitute the observed sample standard deviation and then describe it as known.

Conjugacy gives V=1/(1/400+66/121)=1.824968893 and m=V(25/400+1730/121)=26.20659100. Thus mu|y~Normal(m,V). The posterior standard deviation of mu is sqrt(V), about 1.351. This describes uncertainty in the shared mean. It is different from the standard deviation 11 of an individual observation and from the spread of a replicated sample mean.

Replicate the experiment, including shared uncertainty

The posterior predictive distribution is p(y_rep|y)=integral p(y_rep|mu)p(mu|y) dmu. For each independent replication, draw one mu from its posterior, then generate 66 conditionally independent observations with that same mu and standard deviation 11. Repeat the entire procedure. Drawing a fresh mu separately for each observation creates a different joint predictive model. Fixing mu at its posterior mean discards uncertainty.[2][3]

Preserve relevant features of the observation process: group membership, exposure durations, censoring, sampling locations, and missingness mechanisms. A new patient from an existing clinic and a new clinic are different prediction targets. If variance is unknown, assign it a model, fit its joint posterior with the mean, and draw it as part of each replication. The known-variance calculations here cannot simply be relabeled as an unknown-variance analysis.

Derive the replicated mean distribution

Conditional on mu, the replicated mean has distribution Normal(mu,121/66). Integrating the posterior of mu gives mean_rep|y~Normal(m,121/66+V), whose standard deviation is 1.912668875. The variance is the sum of new sampling variation and posterior uncertainty in the mean. Using sqrt(V) alone would describe a posterior parameter draw, not a newly replicated average.

Define the upper-tail check explicitly: p_mean=P(mean_rep>=26.212121|y). It is 0.498846517. In the flat-prior limit for mu with known variance, m equals the observed mean and V=121/66, so this particular upper-tail probability is exactly 0.5 for every dataset. That is a property of this model and this statistic. It is not a theorem that every mean check under every prior or constrained model is uninformative.

The posterior mean-parameter density has SD sqrt(1.824968893); the replicated sample mean has SD 1.912668875 after adding new sampling variance 121/66. Its upper-tail probability at the observed mean is 0.498846517.
The posterior mean-parameter density has SD sqrt(1.824968893); the replicated sample mean has SD 1.912668875 after adding new sampling variance 121/66. Its upper-tail probability at the observed mean is 0.498846517.

Check a different feature: the minimum

A very small minimum suggests checking the lower tail. Define p_min=P(min(y_rep)<=-44|y). Conditional on mu, the chance that all 66 observations exceed t is [1-Phi((t-mu)/11)]^66, where Phi is the standard normal cumulative distribution function. Therefore

p_min = E_mu|y[1 - {1-Phi((-44-mu)/11)}^66]

Numerical integration gives p_min=7.8412069 times 10^-9 in the stated proper-prior, fixed-noise model. This calculation averages over uncertainty in mu. It is different from inserting a single estimated mean into the bracket. The result says that this model assigns an extremely small predictive probability to a minimum at least this low. It does not establish a physical impossibility, identify which observation is wrong, or tell us the probability that a competing model is true.

The integrated predictive density of the minimum is compared with the observed -44. The lower-tail probability is 7.8412069e-9 under the specified model. The curve averages conditional minimum densities with 80-node Gaussian quadrature; the reference tail probability uses independent adaptive integration.
The integrated predictive density of the minimum is compared with the observed -44. The lower-tail probability is 7.8412069e-9 under the specified model. The curve averages conditional minimum densities with 80-node Gaussian quadrature; the reference tail probability uses independent adaptive integration.

Compare the two checks

The mean check and minimum check address different aspects of the same predictive distribution. Report the model, statistic, tail direction, observed value, and reference distribution together. For a discrepancy D(y,mu) that depends on parameters, compare D(y_rep,mu) with D(y,mu) at the same posterior draw of mu. Otherwise the two sides need not represent the intended check.[2]

Mean and minimum: numerical results

FeatureObserved valueTail directionPosterior predictive probability
Sample mean26.212121Replicated mean at least observed0.498846517
Sample minimum-44Replicated minimum at most observed7.8412069 x 10^-9

Zero simulation hits are not zero probability

The interactive model simulates independent posterior predictive datasets with a recorded seed. With 2000 replications, it will usually produce no minimum as low as -44. Zero divided by 2000 is a simulation estimate, not proof that the event has probability zero. For zero successes in B independent Bernoulli trials, a one-sided exact 95 percent upper confidence bound for the unknown simulation-event probability is 1-0.05^(1/B). At B=2000 this is about 0.001497.

That bound is far too coarse to resolve a probability near 10^-8. The analytic conditional probability followed by one-dimensional integration is more informative here. For a nonzero event frequency, Monte Carlo standard error is approximately sqrt(p_hat(1-p_hat)/B) when replications are independent. Correlated MCMC-based replications require an appropriate dependence adjustment. Increasing draws improves simulation precision; it does not repair a poorly chosen data model.

A count-data check with all categories visible

Consider a separate constructed example: 100 equally exposed machines have event counts with the frequencies below. There are 150 total events, mean 1.5, and sample variance 3.020202. These totals are internally consistent. A Poisson model with a common known rate 1.5 has expected zero fraction exp(-1.5), about 0.22313, whereas 45 machines are observed with zero events.

For the last column, use a common unknown rate lambda~Gamma(shape=2,rate=1), followed by 100 independent Poisson(lambda) counts. The posterior is Gamma(152,101). Each new count has a negative-binomial marginal predictive distribution, and the expected number of zeros among 100 new machines is 100*(101/102)^152. The categories include 7 or more, so the expected frequencies sum to 100 rather than silently dropping the tail.

Observed frequencies 45,13,15,11,9,4,3,0 are compared with expected counts from fixed Poisson(1.5) and a Gamma(152,101 rate) posterior predictive model. All categories include 7 or more. Expected frequencies are not predictive intervals. Extra zeros alone do not identify their mechanism.
Observed frequencies 45,13,15,11,9,4,3,0 are compared with expected counts from fixed Poisson(1.5) and a Gamma(152,101 rate) posterior predictive model. All categories include 7 or more. Expected frequencies are not predictive intervals. Extra zeros alone do not identify their mechanism.

Machine counts: observed and expected

CountObserved machinesExpected: fixed Poisson 1.5Expected: Gamma-Poisson prediction
04522.31322.368
11333.47033.332
21525.10224.999
31112.55112.581
494.7074.780
541.4121.462
630.3530.375
7 or more00.0930.103

Separate uncertainty from heterogeneity

Integrating the common rate creates marginal dependence between new counts because they share lambda. Consequently, the number of zero machines is not generally binomial with probability obtained by averaging exp(-lambda). Its expectation is still 100 E[exp(-lambda)|y]. To obtain a predictive distribution for that number, draw one common lambda per replicated dataset, then all machine counts.

Uncertainty about one common rate is different from real variation in rates across machines. A hierarchical count model can describe heterogeneous rates. A zero-inflated model instead adds a separate mechanism that generates structural zeros. Exposure differences, omitted groups, dependence, data errors, or an unsuitable count distribution can also create a discrepancy. Neither a sample variance exceeding its mean nor many zeros uniquely diagnoses a zero-inflation mechanism. Even under a true Poisson model, sample variance and sample mean will fluctuate.[3]

Interpret checks and revise transparently

Posterior predictive tail probabilities reuse observations in both fitting and checking and are not generally uniform under repeated sampling. They should not automatically be treated as classical p-values with a universal five-percent rejection rule. The degree of concentration toward 0.5 depends on the model and discrepancy. A satisfactory check establishes only that the examined feature was not clearly surprising under this comparison.[2][3]

Choose scientifically relevant checks, including subgroup patterns and extremes, before examining their results when practical. Exploratory checks remain useful, but record which were chosen after seeing the data. Repeatedly revising a model to improve the same displays can overfit those displays. Use held-out prediction or newly collected observations for an additional assessment of generalization. More flexible tails, group effects, or exposure models are proposals to evaluate, not automatic corrections.[4]

Common misconceptions

  • A posterior parameter draw is not a replicated observation or sample average.
  • Zero simulated hits do not establish zero predictive probability.
  • A satisfactory mean check does not verify tail behavior.
  • A count discrepancy does not uniquely identify a structural-zero mechanism.

Retrieve before checking

Close the equations and explain why a predictive sample mean has two variance contributions. Reconstruct the direction of the minimum check. Then explain why independently redrawing mu for every replicated observation changes the experiment. On the next study day, reproduce the count total and mean from the frequency table. Several days later, design a discrepancy for a model that fits an overall mean while missing a subgroup pattern. Compare your answer with the sampling design before looking at the worked feedback.

What to carry forward

Key idea: A predictive check compares a clearly defined observed feature with replicas from a fully specified model. Propagate uncertainty, preserve shared parameters, show the direction of the comparison, and distinguish a model discrepancy from a diagnosis of its cause. A good average does not establish good tails, and a tiny simulated frequency requires a precision check.

Calculations, teaching datasets explicitly marked constructed, and diagrams are original to this lesson. Reference calculations use the stated distributions and settings. Numerical verification establishes agreement for those settings, not the adequacy of a model for an unexamined application.

Sources

  1. Gelman and collaborators. Bayesian Data Analysis author dataset: Simon Newcomb light measurements, attributed there to Stigler (1977). All 66 values inspected, November 13, 2026. Read source.
  2. Gelman, A., Meng, X.-L., and Stern, H. (1996). Posterior predictive assessment of model fitness via realized discrepancies (with discussion). Statistica Sinica, 6, 733-807. Sections 2 and 4. Read source.
  3. Stan User Guide, version 2.40. Posterior and Prior Predictive Checks. Accessed November 13, 2026. Read source.
  4. Gelman, A., Vehtari, A., McElreath, R., and collaborators (2026). Bayesian Workflow. CRC Press. Author electronic edition corrected August 19, 2026; sections 5.9, 7.3, 8.2, 9.4-9.6, 14.1, and 15.4. Read source.
Key terms
Posterior predictive distribution
Distribution of replicated or future observations after integrating uncertain model parameters over their posterior.
Discrepancy
A chosen feature or function used to compare observations with model-generated replicas; it may depend on parameters.
Posterior predictive tail probability
Conditional probability of a clearly specified replicated discrepancy being at least as extreme in the chosen direction as the observed one.
Conditional independence
Independence after conditioning on specified quantities; integrating a shared uncertain parameter can induce marginal dependence.
Monte Carlo standard error
Uncertainty in a simulation estimate due to a finite number of draws, with dependence accounted for when applicable.
Overdispersion
Variation larger than a reference model describes; its interpretation depends on the observation design and comparison.
Structural zero
A zero produced by a distinct process that cannot generate a positive count, as specified in a model.
Exploratory model check
A diagnostic selected or adapted after seeing data, useful for revision when its role is reported transparently.

Module 6: Model Comparison and a Complete Bayesian Analysis

Compare properly specified models using marginal evidence and held-out predictions, inspect uncertainty and computational reliability, and complete a reproducible analysis with explicit losses, sensitivity, and stopping-rule evaluation.

Model Comparison: Bayes Factors, Exact LOO, and Predictive Uncertainty

  • Compute a Bayes factor from proper prior predictive probabilities and convert it to posterior model odds.
  • Reproduce exact leave-one-out and WAIC calculations for two fully specified normal models.
  • Separate predictive-score uncertainty, importance-sampling reliability, and model adequacy.
  • Choose a validation unit and interpret predictive stacking without treating its weights as model probabilities.

State which comparison you need

A Bayes factor compares the prior predictive support that two specified models assign to the observed data. Leave-one-out cross-validation, abbreviated LOO, evaluates predictions for observations withheld during fitting. A posterior predictive check looks for a discrepancy within a fitted model. These questions are related, but their numerical answers are not interchangeable. A candidate can predict better than another candidate and still omit an important scientific mechanism.[1][2]

We will use two separate constructed examples. Seven events among 23 binary observations illustrate model evidence and prior sensitivity. Four continuous observations illustrate prediction, WAIC, and comparison uncertainty. Neither example is presented as a reconstruction of an aerospace accident, clinical trial, or other historical study. All data and prior settings needed to reproduce the answers are supplied.

Integrate the likelihood rather than maximize it

For the binary example, assume conditionally independent Bernoulli observations with common event probability theta. Under H0, theta=0.1. Under H1, theta~Beta(a,b), with positive a and b chosen as part of the model. For an observed sequence containing k=7 events and 16 nonevents, its marginal probabilities are

m0 = 0.1^7 * 0.9^16 = 1.853020189 x 10^-8
m1 = B(a+7,b+16) / B(a,b)
BF01 = m0 / m1

The beta function is B(a,b)=integral_0^1 theta^(a-1)(1-theta)^(b-1) dtheta. If the data are recorded as the unordered count rather than the sequence, multiply both marginal probabilities by choose(23,7). This common factor cancels in BF01. The likelihood at theta=7/23 is a maximized likelihood, not the alternative model's integrated evidence. The distinction is central to Bayes factors.[1]

Prior predictive count probabilities under H0 and two proper beta alternatives are normalized over counts zero through 23. The observed count is seven. These plotted count probabilities differ from sequence probabilities by a common binomial coefficient.
Prior predictive count probabilities under H0 and two proper beta alternatives are normalized over counts zero through 23. The observed count is seven. These plotted count probabilities differ from sequence probabilities by a common binomial coefficient.

Expose sensitivity to the alternative prior

The Beta(1,99) alternative concentrates near a much smaller event rate than the data suggest. It can perform poorly relative to H0 even though the observed fraction 7/23 is well above 0.1. Beta(3,7) puts more prior mass near 0.3 and gives a different comparison. These are different models, not competing numerical approximations to one model. Prior predictive count plots make their implications visible before the evidence is interpreted.

Beta(0.5,0.5), the Bernoulli Jeffreys prior, is proper and has more mass near zero and one than the uniform Beta(1,1) prior. Calling either choice free of assumptions would conceal its predictions. A hypothetical Beta(7,16) prior gives BF01=0.036262308, but selecting those parameters because the same data contained 7 and 16 outcomes would reuse the data. A prespecified sensitivity scenario is useful; presenting a data-tuned prior as independent prior evidence is misleading.[1]

Three proper alternative priors lead to Bayes factors BF01 1441.821599,0.109027409,0.047437493 for the same seven events in 23 observations. The prior-density plot clips the Beta(1,99) peak above 13 and labels this explicitly; the Bayes-factor axis is logarithmic.
Three proper alternative priors lead to Bayes factors BF01 1441.821599,0.109027409,0.047437493 for the same seven events in 23 observations. The prior-density plot clips the Beta(1,99) peak above 13 and labels this explicitly; the Bayes-factor axis is logarithmic.

Marginal evidence under five priors

H1 priorm1 for the sequenceBF01P(H0|y), equal model priors
Beta(1,99)1.285194e-111441.8215990.999307
Beta(2,18)8.522247e-80.2174330.178600
Beta(0.5,0.5)1.195792e-70.1549620.134170
Beta(1,1)1.699591e-70.1090270.098309
Beta(3,7)3.906235e-70.0474370.045289

Keep parameter priors and model odds separate

Posterior odds H0:H1 equal BF01 times prior odds H0:H1. With prior model probability p0, P(H0|y)=BF01*p0/[BF01*p0+(1-p0)]. Under Beta(1,1), equal model priors give P(H0|y)=0.098309030. Changing p0 changes this posterior probability without changing the Bayes factor. Changing a or b changes the model's marginal likelihood and can change the Bayes factor itself.

These probabilities are conditional on the candidate set and its specifications. They do not establish that one of the models accurately describes every aspect of reality. Standard marginal likelihoods also require properly normalized parameter priors. An arbitrary multiplicative constant in an improper prior can contaminate the comparison; specialized constructions need their own justification. Large sample size is not a blanket license to ignore prior sensitivity, especially in weakly identified or high-dimensional settings.[1]

Build a prediction example that can be refit by hand

Now take y=(-1,0,1,5). Model A uses independent y_i|mu~Normal(mu,1), and model B uses independent y_i|mu~Normal(mu,4). Both assign mu~Normal(0,4). All second arguments are variances: A has observation SD 1, B has SD 2, and both have prior SD 2. These fixed noise settings are teaching comparisons, not estimates selected by optimizing these four observations.

For observation SD sigma and prior SD s0, a training set of n_t values gives V_t=1/(1/s0 squared+n_t/sigma squared) and m_t=V_t*sum(y_train)/sigma squared. A new observation has predictive distribution Normal(m_t,sigma squared+V_t). In each LOO fold, exclude the held-out value from both the training count and the training sum. Then evaluate its log density under that fold's predictive distribution.

Inspect each exact LOO contribution

When 5 is held out, the remaining observations sum to zero. Both training posterior means are zero. A's predictive variance is 1+1/3.25=1.307692308, whereas B's is 4+1=5. The resulting log predictive densities are -10.611894 and -4.223657. Model B loses less log score on that held-out extreme. At y=1, model A instead has the higher predictive density. Comparing contributions reveals what drives the total.

Exact LOO log densities for constructed y=(-1,0,1,5). When five is held out, both training means are zero; predictive variances are 17/13 and 5. B improves the log score by 6.388237 on this observation, while A is better for y=1.
Exact LOO log densities for constructed y=(-1,0,1,5). When five is held out, both training means are zero; predictive variances are 17/13 and 5. B improves the log score by 6.388237 on this observation, while A is better for y=1.

Exact leave-one-out fold calculations

Held-out yA training posterior meanA log predictive densityB training posterior meanB log predictive densityDifference B-A
-11.846154-4.1503561.500000-2.3486571.801698
01.538462-1.9580481.250000-1.8799070.078140
11.230769-1.0734331.000000-1.723657-0.650225
50.000000-10.6118940.000000-4.2236576.388237

Calculate WAIC and distinguish it from exact LOO

The full-data posterior for a model is Normal(m,V). Its log pointwise predictive density is lppd_i=log NormalDensity(y_i;m,sigma squared+V). Define p_WAIC,i=Var_mu|y[log p(y_i|mu)]. For this conjugate normal model, direct normal-moment calculation gives

p_WAIC,i = V squared/(2*sigma^4) + V*(y_i-m)^2/sigma^4
elpd_WAIC = sum_i(lppd_i - p_WAIC,i)

Higher expected-log-predictive-density estimates, abbreviated elpd, are better on the log-score scale. Some software instead reports WAIC=-2*elpd_WAIC and LOOIC=-2*elpd_LOO, for which lower is better. Always label the scale. WAIC approximates out-of-sample performance using the full posterior; it is not generally identical to exact LOO in a finite dataset.[2]

The source paper reports that individual log-likelihood variance terms exceeding 0.4 can signal unreliable WAIC approximation. Both models exceed that diagnostic value here. It is a warning based on the method's behavior, not an automatic proof that the scientific model is false. Since exact refitting is easy in this example, use it directly and inspect the difference rather than substituting WAIC for a failing approximation.[2]

WAIC and LOO totals

ModelExact elpd_LOOelpd_WAICLargest p_WAIC,i
A: sigma=1-17.793730-17.5041033.467535
B: sigma=2-10.175880-10.1304860.820000

Quantify comparison uncertainty without overstating four observations

Let d_i be the paired difference between B's and A's LOO log predictive contributions. The total difference is sum(d_i)=7.617850112 in favor of B. The commonly used approximate standard error is sqrt(n*s_d squared), using the sample variance of the paired differences with divisor n-1. Here n=4 and this standard error is 6.322095733. Pairing matters because both models predict the same held-out observations.

This uncertainty reflects variation across observations, not numerical integration error. Four observations are far too few to assume that the estimate and its standard error define a well-calibrated normal confidence interval. Cross-validation terms also share training data. Report the pointwise contributions, sample size, intended prediction target, and limitations. A computed advantage on this dataset does not establish a universal winner or a probability that B is true.[2]

Exact LOO totals -17.793730 and -10.175880 differ from WAIC elpd totals -17.504103 and -10.130486. Paired B-minus-A contributions sum to 7.617850 with approximate SE 6.322096. Four observations and shared training data limit interpretation.
Exact LOO totals -17.793730 and -10.175880 differ from WAIC elpd totals -17.504103 and -10.130486. Paired B-minus-A contributions sum to 7.617850 with approximate SE 6.322096. Four observations and shared training data limit interpretation.

Diagnose approximate LOO before using its scores

For larger models, Pareto smoothed importance sampling, or PSIS, can approximate LOO using full-posterior draws. Raw case-deletion importance ratios are proportional to 1/p(y_i|theta). Influential observations can make these ratios unstable because the full and leave-one-out posteriors differ substantially. The estimated Pareto tail-shape parameter k is a diagnostic of the approximation, not a posterior probability that an observation is wrong.[3]

The current loo documentation uses the reliability threshold min(1-1/log10(S),0.7), where S is the nominal number of posterior draws; low effective sample size can make that threshold optimistic. At S=1000 it is 2/3. A separately hypothetical k estimate of 0.81 exceeds it. Refit problematic folds, use a suitable alternative importance method, or use an appropriate K-fold scheme, then reassess the comparison. Merely reporting an elpd standard error does not repair unreliable computation.[4]

The theoretical raw-weight variance boundary k=0.5 is distinct from the practical reliability threshold. An estimated k above 0.7 is not the definition of infinite variance, and an estimated tail shape has uncertainty. Our four-observation example uses exact analytic refits and does not manufacture a PSIS k value. An accurate computation can still reveal inadequate models or limited predictive evidence.

Match validation to deployment and combine carefully

Holding out individual rows answers a different question from predicting a new group or the future. For a new clinic, hold out the relevant clinic information; for forecasting, respect time ordering. Learn preprocessing, tuning, and fitted prior choices using training data within each split when those steps are part of the prediction procedure. Otherwise information from the held-out outcomes can leak into fitting. Bayesian predictive evaluation still depends on the priors used for the training posterior.[2][6]

Predictive stacking chooses nonnegative weights summing to one to maximize sum_i log[sum_j w_j p_j(y_i|y_-i)]. It combines densities before taking the logarithm. In our two-model example, the optimum is the boundary weight w_B=1, not an improved interior mixture. Stacking weights describe a predictive combination and are not posterior probabilities of model truth. Optimizing the observed cross-validation objective does not guarantee a better score on future data, particularly after extensive model search.[5]

Common misconceptions

  • A Bayes factor is not a posterior model probability without prior model odds.
  • An integrated likelihood is not a likelihood maximized over parameters.
  • A reliable calculation does not remove predictive-score uncertainty.
  • Stacking weights are not model-truth probabilities.

Retrieve before checking

From memory, distinguish a marginal likelihood, a held-out predictive density, and a posterior predictive tail probability. Derive the posterior odds formula from Bayes's rule. The next day, reconstruct the fold that holds out 5 without using full-data posterior quantities. Later, explain why a high Pareto k, a large paired standard error, and an implausible predictive plot require different responses. Interleave this with the earlier loss-function lesson: the model with best log score need not minimize every operational loss.

Putting it together

Remember: Compare explicit models for an explicit purpose. Show prior sensitivity for evidence, use genuinely held-out predictions for predictive assessment, inspect computational diagnostics, and report uncertainty about score differences. A model ranking is conditional on the candidate set, validation design, data, and scoring rule.

Calculations, teaching datasets explicitly marked constructed, and diagrams are original to this lesson. Reference calculations use the stated distributions and settings. Numerical verification establishes agreement for those settings, not the adequacy of a model for an unexamined application.

Sources

  1. Kass, R. E., and Raftery, A. E. (1995). Bayes Factors. Journal of the American Statistical Association, 90(430), 773-795. Sections 3-5. DOI: 10.1080/01621459.1995.10476572. Read source.
  2. Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27, 1413-1432. Inspected author manuscript arXiv:1507.04544v5. DOI: 10.1007/s11222-016-9696-4. Read source.
  3. Vehtari, A., Simpson, D., Gelman, A., Yao, Y., and Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72), 1-58. Read source.
  4. loo developers. Diagnostics for Pareto smoothed importance sampling. Package documentation version 2.10.1, accessed November 13, 2026. Read source.
  5. Yao, Y., Vehtari, A., Simpson, D., and Gelman, A. (2018). Using Stacking to Average Bayesian Predictive Distributions (with Discussion). Bayesian Analysis, 13(3), 917-1003. DOI: 10.1214/17-BA1091. Author-hosted published paper. Read source.
  6. Gelman, A., Vehtari, A., McElreath, R., and collaborators (2026). Bayesian Workflow. CRC Press. Author electronic edition corrected August 19, 2026; sections 5.9, 7.3, 8.2, 9.4-9.6, 14.1, and 15.4. Read source.
Key terms
Marginal likelihood
Probability or density of the observed data under a model, integrating its likelihood over a normalized parameter prior.
Bayes factor
Ratio of two model marginal likelihoods, multiplying prior model odds to obtain posterior model odds.
Leave-one-out cross-validation
Evaluation of each observation using a predictive distribution fitted without that observation.
elpd
Expected log pointwise predictive density; cross-validation supplies an estimate for a specified prediction target.
WAIC
A full-posterior approximation to predictive performance using pointwise log predictive density and posterior log-likelihood variance.
Pareto k diagnostic
An estimated importance-weight tail-shape measure used to assess the reliability of PSIS approximation.
Paired score difference
Difference between two models' predictive scores for the same held-out observation or unit.
Predictive stacking
Choice of mixture weights for predictive densities by optimizing a validation scoring objective, without interpreting those weights as model-truth probabilities.

Bayesian Workflow: A Reproducible Analysis and Decision

  • Produce a complete analysis that connects the question, data collection, model, posterior prediction, and decision.
  • Calculate prior sensitivity, beta-binomial prediction, and posterior expected losses in a reproducible capstone.
  • Distinguish posterior updating, prior-averaged calibration, and fixed-parameter repeated-sampling error under stopping rules.
  • Write an auditable report with numerical checks, limitations, a validation plan, and a justified action.

Finish with an analysis another person can reproduce

A Bayesian calculation is one part of an analysis. Its usefulness also depends on the question, observations, measurement process, assumptions, computational accuracy, and consequences of action. This final lesson puts those pieces together in a constructed quality-monitoring example. It supplies an offline route so that a complete capstone does not depend on finding a private dataset or installing specialist software.[1]

Suppose 20 independent checks under a stable process contain two events. Let theta be the probability of an event on one check. The target is the underlying process rate, and the operational concern is whether theta exceeds q=0.1. This is an illustrative threshold, not a regulatory requirement. Before calculating, identify the units, define an event, confirm that all 20 checks were recorded, and ask whether independence and a common rate are defensible.

Write a generative model and inspect its implications

Use X_i|theta~Bernoulli(theta), conditionally independently, and theta~Beta(a,b). The default prior is Beta(1,1); sensitivity scenarios are Beta(1,9) and Beta(2,18). These are specified teaching models. The last two share prior mean 0.1 but differ in concentration. The sum a+b controls concentration in this family; it should not automatically be described as a literal number of historical observations.

For a prior predictive check, draw theta from the prior and then a complete 20-check dataset. Under Beta(1,1), each total count from zero through 20 has probability 1/21. That is a strong predictive implication, not an absence of assumptions. Ask whether totals near 20 are remotely plausible for the intended process. Use defensible prior information and record when a scenario was chosen. Do not select a prior solely because it yields a desired decision.[1]

Update and keep the estimand visible

With k=2 and n=20, the posterior is Beta(a+2,b+18). Under the default prior it is Beta(3,19), with posterior mean 3/22=0.136363636. Its equal-tailed 95 percent credible interval is approximately [0.030489,0.303774]. Conditional on this model and these observations, the posterior assigns 0.95 probability to that interval. This statement is not a guarantee of 95 percent coverage at every fixed true theta under repeated sampling.

The posterior tail probability pi=P(theta>0.1|y) is 0.648408824. This concerns an unobserved process parameter. It is different from the probability that the next check has an event, which equals E(theta|y)=0.136363636. Always label the random quantity. Conjugacy gives an analytic posterior here, so MCMC convergence checks are unnecessary for this calculation; arithmetic and implementation checks still matter.

Predict a future batch while retaining uncertainty

For ten future checks from the same stable process, let K_new be their total. Integrating theta gives a beta-binomial distribution with n_new=10, alpha=3, beta=19. Its probability mass is choose(10,j)*B(3+j,19+10-j)/B(3,19). The expected total is 10*3/22=1.363636364, and

P(K_new >= 1 | y) = 1 - B(3,29)/B(3,19) = 0.704115684
Var(K_new|y) = 10*mu*(1-mu)*(22+10)/(22+1) = 1.638519583

Here mu=3/22. A binomial distribution with fixed probability 3/22 has the same expected count but a smaller variance, about 1.177686. Sharing an uncertain theta makes future indicators marginally dependent. The exact beta-binomial probability of no events is about 0.295884, whereas the plug-in binomial probability is about 0.230839. Adding parameter uncertainty need not increase every tail probability; it changes the full distribution.

The beta-binomial predictive distribution and fixed-posterior-mean binomial have the same expected count but different variances. Integrating uncertainty yields probability 0.704116 of at least one event, versus 0.769161 for the plug-in model; adding uncertainty does not increase every tail probability.
The beta-binomial predictive distribution and fixed-posterior-mean binomial have the same expected count but different variances. Integrating uncertainty yields probability 0.704116 of at least one event, versus 0.769161 for the plug-in model; adding uncertainty does not increase every tail probability.

Let the loss function determine the action

Consider two actions, investigate and continue, and two parameter states, theta>q and theta<=q. For this deliberately simplified decision, set loss zero for investigating when theta>q or continuing when theta<=q. A false investigation costs C_A, and a missed excessive rate costs C_M. The posterior risks are R(investigate)=C_A*(1-pi) and R(continue)=C_M*pi. Investigate when pi>C_A/(C_A+C_M); at equality either action minimizes this loss.[2]

With C_A=19 and C_M=1, the threshold is 0.95. At the default posterior, risks are 6.680232335 and 0.648408824, so continuing minimizes the specified posterior expected loss. This counterintuitive cost ratio is chosen to examine a 95 percent threshold. It is not advice that false alarms are generally more costly than missed quality problems. If C_A=C_M=1, the threshold is 0.5 and the default action changes to investigate. Neither threshold is mandated by Bayes's theorem.

Posterior expected losses 19(1-pi) and pi cross at 0.95. With pi=0.648409, continuing has lower specified loss. The illustrative cost ratio is a teaching choice, not a recommended quality policy; equal error costs instead give a 0.5 threshold.
Posterior expected losses 19(1-pi) and pi cross at 0.95. With pi=0.648409, continuing has lower specified loss. The illustrative cost ratio is a teaching choice, not a recommended quality policy; equal error costs instead give a 0.5 threshold.

Report sensitivity instead of hiding it

At the 0.95 threshold, all three scenarios choose continue. With equal error costs, Beta(1,1) instead chooses investigate while the other two choose continue. The data and loss do not uniquely choose a prior. Explain why each prior is plausible or deliberately hypothetical, and distinguish conclusions that persist across scenarios from those that depend on them. More observations may reduce some uncertainty, but they do not automatically resolve biased sampling or an unstable process.

Priors Beta(1,1),Beta(1,9),Beta(2,18) update to Beta(3,19),Beta(3,27),Beta(4,36). Posterior probabilities theta>0.1 are 0.648409,0.434960,0.443719. Plots show the range 0 to 0.7; numeric probabilities use the full support 0 to 1.
Priors Beta(1,1),Beta(1,9),Beta(2,18) update to Beta(3,19),Beta(3,27),Beta(4,36). Posterior probabilities theta>0.1 are 0.648409,0.434960,0.443719. Plots show the range 0 to 0.7; numeric probabilities use the full support 0 to 1.

Posterior sensitivity: numerical results

PriorPosteriorPosterior meanP(theta > 0.1 | y)P(at least one of next 10)
Beta(1,1)Beta(3,19)0.1363640.6484090.704116
Beta(1,9)Beta(3,27)0.1000000.4349600.600175
Beta(2,18)Beta(4,36)0.1000000.4437190.611797

Check model adequacy and computational calibration separately

For actual monitoring, inspect event order, subgroup patterns, varying exposures, repeated checks on the same unit, and changes in equipment. The count two out of twenty alone cannot reveal all those features. If the data show clustering or time trends, the independent common-rate model may be inadequate. A posterior predictive check should reproduce the relevant observation structure. A held-out comparison should match the future decisions the model will support.[1]

Simulation-based calibration, or SBC, answers a different question: does a computational inference procedure recover the posterior implied by its own model? Draw parameters from the prior, simulate datasets, fit each, and examine ranks or coverage using appropriate independent posterior draws and handling of ties. Uniform ranks are expected under correct simulation and inference for continuous parameters. Passing these checks does not prove that the model describes the real process, and a finite diagnostic can miss defects.[3]

State what optional stopping does and does not change

If all observations up to stopping are retained and the stopping rule is a function of the observed history with no additional theta-dependent mechanism, the stopping indicator contributes a factor constant in theta for that observed path. It cancels in the posterior normalization. The beta update for the observed k and n remains valid under that ignorable sampling rule. Informative selection, missing outcomes, or reporting only favorable studies requires a fuller observation model.

Posterior updating for an observed path is different from the repeated-sampling behavior of an entire decision procedure. Calibration averaged over parameters drawn from a prior is also different from error control at every fixed parameter value. The optional-stopping literature carefully distinguishes these goals and conditions; it does not supply a universal guarantee for every prior and posterior threshold.[4]

Compute a repeated-sampling operating characteristic

Fix the actual process rate at theta=0.1, use the Beta(1,1) analysis prior, and investigate whenever P(theta>0.1|data)>0.95. Compare one look after n=20 with looks after n=5,10,15,20, stopping at the first investigation. At the boundary theta=0.1, investigation is a false alarm under our strict excessive-rate definition.

Exact summation over all possible Bernoulli paths gives a probability 0.137771176 of any trigger at the four planned looks. One look at n=20 gives 0.043174495. The first-trigger probabilities in the table are mutually exclusive, so they can be added. Simply adding unconditional binomial tail probabilities at the four looks would double-count paths that crossed earlier. The interactive model uses a probability recursion, not a Monte Carlo estimate.

With Beta(1,1), q=0.1, and posterior trigger probability greater than 0.95, exact first-trigger probabilities at n=5,10,15,20 are 0.081460,0.031778,0.015750,0.008784. At fixed theta=0.1 their sum is 0.137771, compared with 0.043174 for one look at n=20. This is one specified procedure.
With Beta(1,1), q=0.1, and posterior trigger probability greater than 0.95, exact first-trigger probabilities at n=5,10,15,20 are 0.081460,0.031778,0.015750,0.008784. At fixed theta=0.1 their sum is 0.137771, compared with 0.043174 for one look at n=20. This is one specified procedure.

First-trigger probabilities

Look nSmallest cumulative count that triggersProbability of first trigger at this look
520.081460
1030.031778
1540.015750
2050.008784

Interpret the calibration result at its actual scope

The repeated-look false-alarm probability is about 13.78 percent at this fixed theta, although each decision uses a 95 percent posterior threshold. This is a concrete counterexample to an automatic five-percent interpretation. It does not prove that all Bayesian sequential procedures have this behavior. Different priors, losses, maximum sample sizes, and stopping rules have different operating characteristics; some specially designed procedures provide error guarantees.

The lab reports the boundary calculation at theta=q. It does not claim to have evaluated every possible misspecification or every parameter value. If a fixed false-alarm target or power target is required, evaluate and design the full procedure for that requirement. Prespecify the rule, retain the observation path, and report changes. Choosing a new threshold after seeing the favorable path changes the procedure whose performance needs assessment.

Write an honest report with a decision trail

Report the scientific or operational target, data origin and exclusions, likelihood, parameter meanings and units, priors with rationale, computation, predictive checks, sensitivity, and chosen action under an explicit loss. Include enough data and formulas to recreate each displayed number. Store the observation order if sequential decisions matter. Record software versions and seeds where simulation is used; a seed alone does not specify a stochastic analysis.[1]

Numerical precision is not scientific certainty. Explain effects and consequences in their units, and distinguish parameter uncertainty, future observation variation, Monte Carlo error, model inadequacy, and sampling bias. The ASA's six principles warn against interpreting a p-value as a hypothesis probability or reducing decisions to one significance cutoff. The same reporting discipline argues against treating any single posterior probability, Bayes factor, or cross-validation score as a substitute for context.[5]

Complete the capstone and assess it

Prepare a two-page analysis memo and a calculation appendix using this example or a documented nonsensitive dataset with an appropriate model. Include the four parts in the rubric below. For the supplied example, report all three prior scenarios, both cost settings (19:1 and 1:1), the ten-check prediction, and the exact stopping comparison. Propose at least one realistic observation-process failure and a check or redesign that addresses it.

Use the rubric to locate a weakness, revise it, and recompute affected results. A correct number without its conditioning model earns incomplete credit. A polished narrative without reproducible calculations also earns incomplete credit. If using new data, document permission and provenance and avoid exposing personal information; choosing the supplied constructed data satisfies the assignment completely.

Capstone scoring rubric

CriterionPointsEvidence required
Question and model25Define event, target, observation process, likelihood, prior, and assumptions.
Reproducible calculations30Correct posterior, prediction, losses, and stopping probabilities with formulas and inputs.
Checking and sensitivity25Interpret all three priors; separate computation checks from data-model checks; propose suitable validation.
Decision and communication20State the action under each loss, uncertainty, limits, and what would change the recommendation.

Common misconceptions

  • A parameter-tail probability differs from a future-batch event probability.
  • A posterior threshold does not automatically control fixed-parameter false alarms.
  • Passing a computational calibration check does not establish real-world model adequacy.
  • Changing a loss function can change the action without changing the posterior.

Retrieve before checking

Without notes, distinguish the posterior probability of an excessive parameter from the probability of at least one future event. Derive the action threshold from the two risks. The next day, explain why one-lambda-per-batch prediction induces dependence. Several days later, reconstruct the first-trigger recursion and identify which probability is conditioned on the observed data and which averages over new datasets. Revisit an earlier lesson's inference under a different loss to practice transfer.

What to remember

The point: A complete Bayesian analysis makes its assumptions, calculations, predictions, and consequences inspectable. Updating, model checking, computational calibration, and repeated-sampling performance answer distinct questions. Connect them deliberately, and make the final decision traceable to the evidence and the stated loss.

Calculations, teaching datasets explicitly marked constructed, and diagrams are original to this lesson. Reference calculations use the stated distributions and settings. Numerical verification establishes agreement for those settings, not the adequacy of a model for an unexamined application.

Sources

  1. Gelman, A., Vehtari, A., McElreath, R., and collaborators (2026). Bayesian Workflow. CRC Press. Author electronic edition corrected August 19, 2026; sections 5.9, 7.3, 8.2, 9.4-9.6, 14.1, and 15.4. Read source.
  2. Chen, Y.-C. (2026). STAT 581, Lecture 1: Decision theory. University of Washington course notes. Posterior expected loss and Bayes rules. Read source.
  3. Stan User Guide, version 2.40. Simulation-Based Calibration Checking. Accessed November 13, 2026. Read source.
  4. Hendriksen, A., de Heide, R., and Grunwald, P. (2021). Optional Stopping with Bayes Factors: A Categorization and Extension of Folklore Results, with an Application to Invariant Situations. Bayesian Analysis, 16(3), 961-989. Sections 2-3. DOI: 10.1214/20-BA1234. Read source.
  5. American Statistical Association (March 7, 2016). Official release of the Statement on Statistical Significance and P-Values, including its six principles. This source is the three-page release, not the separate journal article. Read source.
Key terms
Generative model
A specification of how parameters and observations are distributed, enabling simulated datasets and explicit assumptions.
Beta-binomial prediction
Distribution of a future binomial total after integrating a common event probability over a beta distribution.
Posterior expected loss
Loss for an action averaged over the parameter posterior; comparing these quantities defines a Bayes action.
Ignorable stopping rule
A stopping mechanism whose likelihood factor for the retained observed path adds no parameter-dependent information beyond that modeled path.
Operating characteristic
A repeated-sampling property of a complete procedure, such as trigger probability at a fixed parameter value.
First-trigger probability
Probability that a sequential rule first crosses its decision boundary at a particular look, excluding earlier crossings.
Simulation-based calibration
A computational check using parameters and data drawn from the model to assess whether an inference procedure reproduces the implied posterior calibration.
Sensitivity analysis
Comparison of conclusions under explicitly varied assumptions, priors, or losses while identifying which changes matter.

Open the interactive version with quizzes and progress →