Partial pooling on a bottle-filling line

Deriving a hierarchical model, sampling a non-conjugate posterior, and predicting the output of a new machine.

Statistics
Bayesian inference
R

The assignment compared deviations from a 500 mL filling target across seven machines. With samples ranging from five to fifty bottles, the individual machine means were not equally precise.

I used a hierarchical normal model to connect the machine means through a shared population mean. A Laplace prior made the population-level posterior non-conjugate, so I derived an acceptance–rejection sampler rather than relying on a named posterior distribution. From those samples, I estimated machine-specific means and constructed a predictive distribution for a bottle from a new machine.

Unequal amounts of evidence

The dataset contained 153 observations across seven machines. The measurements are deviations, in millilitres, from a 500 mL target:

Machine Observations Sample mean (mL) Sample standard deviation (mL)
1 5 0.441 2.188
2 8 2.100 1.514
3 12 2.050 1.919
4 18 −1.094 1.998
5 25 −0.275 1.772
6 35 0.354 1.811
7 50 −0.783 1.884

The first four machines supplied 43 observations, approximately 28% of the data. The other three supplied approximately 72%. The imbalance matters: the sample mean for machine 1 is based on only a tenth as many observations as the mean for machine 7.

Observed filling deviations by machine, showing differences in location and spread.
Figure 1: Observed filling deviations by machine, showing differences in location and spread.

Machine 1 had the largest sample standard deviation, but it also had the smallest sample. I treated that combination cautiously. The hierarchical model addresses the unequal precision of the means by allowing information to be shared across machines.

The hierarchical model

Let \(Y_{ij}\) denote observation \(i\) from machine \(j\), and let \(\theta_j\) be that machine’s underlying mean. The model in my report is

\[ Y_{ij}\mid\theta_j\overset{\mathrm{ind}}{\sim} N(\theta_j,\sigma^2), \qquad \theta_j\mid\mu\overset{\mathrm{iid}}{\sim} N(\mu,\tau^2). \]

The within-machine variance is \(\sigma^2\); the variance of machine means around the common mean \(\mu\) is \(\tau^2\). The investigation treats these variances as known, with

\[ \sigma^2=4,\qquad\tau^2=2.25. \]

For the population mean I used a Laplace prior centred on zero:

\[ p(\mu)=\frac{c}{2}\exp(-c|\mu|), \qquad c=0.25. \]

The model uses the same within-machine variance for all seven machines.

Integrating out a machine mean

For machine \(j\), the conditional distribution of its sample mean is

\[ \bar{Y}_j\mid\theta_j\sim N\left(\theta_j,\frac{\sigma^2}{n_j}\right). \]

To derive the likelihood for \(\mu\), I integrated over \(\theta_j\):

\[ p(\bar{y}_j\mid\mu)= \int_{-\infty}^{\infty} p(\bar{y}_j\mid\theta_j)p(\theta_j\mid\mu) \,d\theta_j. \]

The exponent in the integrand is

\[ -\frac12\left[ \frac{n_j}{\sigma^2}(\bar{y}_j-\theta_j)^2+ \frac{1}{\tau^2}(\theta_j-\mu)^2 \right]. \]

Writing

\[ A_j=\frac{n_j}{\sigma^2}+\frac{1}{\tau^2}, \qquad B_j=\frac{n_j\bar{y}_j}{\sigma^2}+\frac{\mu}{\tau^2}, \]

allows the terms involving \(\theta_j\) to be completed into a square:

\[ -\frac{A_j}{2}\left(\theta_j-\frac{B_j}{A_j}\right)^2 +\frac{B_j^2}{2A_j} -\frac{n_j\bar{y}_j^2}{2\sigma^2} -\frac{\mu^2}{2\tau^2}. \]

The first term supplies a normal integral. Simplifying the remaining terms gives

\[ \boxed{\bar{Y}_j\mid\mu\sim N(\mu,V_j)}, \qquad V_j=\tau^2+\frac{\sigma^2}{n_j}. \]

This expression carries the sample-size imbalance into the population-level calculation: a machine with fewer observations has a larger sampling contribution to \(V_j\).

The posterior for the shared mean

Combining the marginal likelihoods with the Laplace prior gives

\[ p(\mu\mid\bar{\mathbf y})\propto \exp\left\{-\frac12\sum_{j=1}^{7} \frac{(\bar{y}_j-\mu)^2}{V_j}-c|\mu|\right\}. \]

Define

\[ v=\left(\sum_{j=1}^{7}\frac{1}{V_j}\right)^{-1}, \qquad m=v\sum_{j=1}^{7}\frac{\bar{y}_j}{V_j}. \]

Completing the square in \(\mu\) produces the useful factorisation

\[ p(\mu\mid\bar{\mathbf y})\propto \underbrace{\exp\left[-\frac{(\mu-m)^2}{2v}\right]}_{ \text{normal kernel}} \underbrace{\exp(-c|\mu|)}_{\text{Laplace-prior factor}}. \]

The normal kernel suggests a proposal distribution directly. The extra factor is bounded above by one, which makes acceptance–rejection sampling particularly simple.

An acceptance–rejection sampler

I proposed candidates from \(N(m,v)\). For each candidate \(\mu^\ast\), I generated an independent \(U\sim\mathrm{Uniform}(0,1)\) and accepted when

\[ U\leq\exp(-c|\mu^\ast|). \]

The proposal-to-target envelope follows from the completed-square expression: after the normal kernel cancels, the remaining factor is \(\exp(-c|\mu|)\), whose maximum occurs at zero. I therefore did not need the posterior’s normalising constant to implement the acceptance test.

ar = function(samples = 5000) {
  sigma_squared = 4
  tau_squared = 2.25
  c = 0.25
  ybar_array = table_summary$mean
  V_j_array = tau_squared + sigma_squared /
    table_summary$num_bottles_per_machine
  v = sum(1 / V_j_array)^-1
  m = sum(ybar_array / V_j_array) / sum(1 / V_j_array)

  mu_array = numeric(0)
  accepted_value_count = 0
  generated_value_count = 0
  while (length(mu_array) < samples) {
    generated_value_count = generated_value_count + 1
    uniform = runif(1, 0, 1)
    candidate = rnorm(1, m, sqrt(v))
    if (uniform <= exp(-c * abs(candidate))) {
      mu_array = c(mu_array, candidate)
      accepted_value_count = accepted_value_count + 1
    }
  }
  return(list(draws = mu_array,
              empirical_acceptance_rate =
                accepted_value_count / generated_value_count))
}

set.seed(888)
draws = ar(samples = 5000)$draws

I retained 5,000 posterior draws from this sampler.

What the population-level draws showed

Histogram of the 5,000 retained posterior draws for the shared mean.
Figure 2: Histogram of the 5,000 retained posterior draws for the shared mean.
Posterior summary Reported value
Mean of \(\mu\) (mL) 0.3144728
Variance of \(\mu\) (mL²) 0.3302718
2.5% quantile (mL) −0.8168016
97.5% quantile (mL) 1.4725756
\(P(\mu>0\mid\text{data})\) 0.7138
\(P(|\mu|<0.5\mid\text{data})\) 0.56

The posterior placed more probability above zero than below it, suggesting a tendency towards a positive average deviation under the model. The 95% interval nevertheless covered both negative and positive values. My interpretation was therefore a positive tendency with substantial uncertainty, rather than decisive evidence that the population mean lay above zero.

The probability inside \((-0.5,0.5)\) answers a different question from the sign probability: approximately 56% of the retained draws lay within that central band.

Recovering individual machine means

Conditional on \(\mu\), each machine mean has a normal posterior. Multiplying its normal likelihood and normal prior gives the same quadratic structure used earlier:

\[ p(\theta_j\mid\bar{y}_j,\mu) \propto\exp\left\{-\frac12\left[ \frac{n_j}{\sigma^2}(\theta_j-\bar{y}_j)^2+ \frac{1}{\tau^2}(\theta_j-\mu)^2\right]\right\}. \]

Consequently,

\[ \theta_j\mid\bar{y}_j,\mu\sim N\left(\frac{B_j}{A_j},\frac{1}{A_j}\right). \]

Rewriting the conditional mean exposes the partial pooling:

\[ E(\theta_j\mid\bar{y}_j,\mu)= \frac{n_j\tau^2}{n_j\tau^2+\sigma^2}\bar{y}_j+ \frac{\sigma^2}{n_j\tau^2+\sigma^2}\mu. \]

The two weights sum to one. As \(n_j\) increases, the machine’s own mean receives more weight. When \(n_j\) is smaller, the common mean receives more weight.

For each retained draw of \(\mu\), the report generated a corresponding draw of each \(\theta_j\) from this conditional distribution. The source implementation was:

mu_draws = draws
sample_array = matrix(0, nrow = length(draws),
                      ncol = max(table_summary$Machine_number))
sigma_squared = 4
tau_squared = 2.25
set.seed(888)
for (j in 1:max(table_summary$Machine_number)) {
  n_j = table_summary$num_bottles_per_machine[j]
  y_bar_j = table_summary$mean[j]
  variance_value = 1 / ((n_j / sigma_squared) + (1 / tau_squared))
  for (i in 1:length(draws)) {
    expected_value =
      ((n_j * tau_squared) / (n_j * tau_squared + sigma_squared)) * y_bar_j +
      (sigma_squared / (n_j * tau_squared + sigma_squared)) * mu_draws[i]
    sample_array[i, j] = rnorm(1, mean = expected_value,
                               sd = sqrt(variance_value))
  }
}
posterior_machine_means = colMeans(sample_array)

Averaging those draws gave:

Machine Sample mean (mL) Posterior mean of \(\theta_j\) (mL)
1 0.441 0.4162034
2 2.100 1.7712521
3 2.050 1.8397312
4 −1.094 −0.9739342
5 −0.275 −0.2296794
6 0.354 0.3508196
7 −0.783 −0.7384935
Observed machine means and posterior machine-mean estimates. The shifts towards the shared population level illustrate partial pooling.
Figure 3: Observed machine means and posterior machine-mean estimates. The shifts towards the shared population level illustrate partial pooling.

Shrinkage is about both weight and distance. Machine 1 has very little data, but its observed mean was already close to the population-level estimate, so its absolute movement was small. Machines 2 and 3 began further away and moved more visibly towards the common level. Machine 7 retained more of its own mean because its estimate was supported by fifty observations.

Predicting a bottle from a new machine

Prediction introduces a new machine mean, not merely another measurement from one of the seven observed machines:

\[ \theta_{\mathrm{new}}\mid\mu\sim N(\mu,\tau^2), \qquad Y_{\mathrm{new}}\mid\theta_{\mathrm{new}} \sim N(\theta_{\mathrm{new}},\sigma^2). \]

I integrated out \(\theta_{\mathrm{new}}\):

\[ p(y_{\mathrm{new}}\mid\mu)=\int p(y_{\mathrm{new}}\mid\theta_{\mathrm{new}}) p(\theta_{\mathrm{new}}\mid\mu) \,d\theta_{\mathrm{new}}. \]

For this integral the completed-square quantities become

\[ A=\frac{1}{\sigma^2}+\frac{1}{\tau^2}, \qquad B=\frac{y_{\mathrm{new}}}{\sigma^2}+\frac{\mu}{\tau^2}. \]

Completing the square and integrating the normal kernel leaves

\[ p(y_{\mathrm{new}}\mid\mu)= \frac{1}{\sqrt{2\pi(\sigma^2+\tau^2)}} \exp\left[-\frac{(y_{\mathrm{new}}-\mu)^2} {2(\sigma^2+\tau^2)}\right]. \]

Thus

\[ Y_{\mathrm{new}}\mid\mu\sim N(\mu,\sigma^2+\tau^2). \]

The full posterior predictive distribution then averages over the posterior uncertainty in \(\mu\):

\[ p(y_{\mathrm{new}}\mid\text{data})= \int p(y_{\mathrm{new}}\mid\mu) p(\mu\mid\text{data})\,d\mu. \]

The simulation mirrors that integral: take a posterior draw of \(\mu\), then draw a new observation from its conditional predictive distribution.

mu_draws = draws
sigma_squared = 4
tau_squared = 2.25
set.seed(888)
sample_array = numeric(0)
for (i in 1:length(draws)) {
  sampled_value = rnorm(1, mean = mu_draws[i],
                        sd = sqrt(sigma_squared + tau_squared))
  sample_array = c(sample_array, sampled_value)
}
mean(sample_array)

Here sigma_squared = 4 and tau_squared = 2.25, as in the model above. The sample mean of the simulated predictive draws was 0.3421268 mL.

Posterior predictive distribution for a bottle from a new machine.
Figure 4: Posterior predictive distribution for a bottle from a new machine.

Comparing with an empirical-Bayes prediction

I compared the posterior predictive density with an empirical-Bayes predictive density.

Empirical-Bayes predictive distribution for a bottle from a new machine.
Figure 5: Empirical-Bayes predictive distribution for a bottle from a new machine.
Posterior predictive and empirical-Bayes predictive densities for a bottle from a new machine.
Figure 6: Posterior predictive and empirical-Bayes predictive densities for a bottle from a new machine.

The report described the distributions as similar, with the posterior predictive distribution slightly wider and flatter. Its explanation was that the fully Bayesian calculation carries uncertainty in \(\mu\) through to prediction, whereas the empirical-Bayes comparison uses a fixed estimate.

What I learned from the hierarchy

The hierarchy provided a precise way to share evidence without making every machine identical. It also separated three sources of variation that are easy to blur together: variation within a machine, variation between machine means and uncertainty about the population mean.

The completed-square calculations were useful computationally as well as analytically. They produced the marginal likelihood, supplied a practical proposal for a non-conjugate posterior, yielded the conditional machine distributions and led to the predictive sampler.

Under this model, smaller samples place more weight on the shared mean, whose uncertainty carries through to predictions for a new machine.

Originally completed as part of STA3048S · Statistical Modelling and Bayesian Analysis, University of Cape Town, 2026.