import pymc as pm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import arviz as az
rng = np.random.default_rng(6420)
4. Hald*#
Adapted from Unit 9: Hald.odc.
A dataset on Portland cement originally due to Woods, Steinour and Starke (1932), and which has since then been widely analysed is now referred as Hald data cf. e.g., Hald (1952, pp. 635†652),
These data come from an experimental investigation of the heat evolved during the setting and hardening of Portland cements of varied composition and the dependence of this heat on the percentages of four compounds in the clinkers from which the cement was produced.
As observed by Woods, Steinour and Starke (1932, p. 1207):
This property is of interest in the construction of massive works such as dams, in which the great thicknesses severely hinder the outflow of the heat. The consequent rise in temperature while the cement is hardening may result in contractions and cracking when the eventual cooling to the surrounding temperature takes place.
The four compounds considered by Woods, Steinour and Starke (1932) are tricalcium aluminate: 3CaO-Al2O3, tricalcium silicate: 3CaO-SiO2, tetracalcium aluminoferrite: 4CaO-Al2O3-Fe2O3, and beta-dicalcium silicate: 2CaO-SiO2, which we will denote by x1, x2, x3, and x4, respectively. The heat evolved after 180 days of curing, which we will denote by y, is measured in calories per gram of cement.
REFS: Hald, Anders (1952). Statistical Theory with Engineering Applications. Wiley, New York.
Woods, H., Steinour, H. H., and Starke, H. R. (1932). Effect of composition of Portland cement on heat evolved during hardening. Industrial and Engineering Chemistry, 24, 1207†1214.
data = pd.read_csv("../data/hald_data.csv")
y = data["y"].to_numpy()
X = data.drop("y", axis=1).to_numpy()
model_names = ["0124", "0123", "0134", "01234", "012", "014", "0234"]
Y = np.tile(y[:, None], (1, len(model_names)))
coords = {
"obs": np.arange(len(y)),
"model": model_names,
}
This was a pain to type out. Would be nice to find a cleaner method.
Model 1 shows how to use the Laud-Ibrahim criteria (Laud and Ibrahim, 1995) to choose between models. The L metric is based on a comparison between the original target variable and the posterior predictive distribution. In the BUGS example, the Y.new contains the results of the Posterior Predictive Check (PPC). As the variable name indicates, it’s just a set of new Y values generated from the posterior. The L metric is a measure of distance between the original y values and the PPC. The lower L is, the better.
Note
The BUGS example has 8 models, but I only have 7 here. That’s because models 6 and 8 were identical, so I just dropped model 8.
x1 = X[:, 0]
x2 = X[:, 1]
x3 = X[:, 2]
x4 = X[:, 3]
with pm.Model(coords=coords) as m:
a = pm.Normal("a", 0, tau=0.00001, shape=4)
b = pm.Normal("b", 0, tau=0.00001, shape=4)
c = pm.Normal("c", 0, tau=0.00001, shape=4)
d = pm.Normal("d", 0, tau=0.00001, shape=5)
e = pm.Normal("e", 0, tau=0.00001, shape=3)
f = pm.Normal("f", 0, tau=0.00001, shape=3)
g = pm.Normal("g", 0, tau=0.00001, shape=4)
tau = pm.Gamma("tau", 12.5, 62.5, dims="model")
# fmt: off
_mu = [
a[0] + a[1] * x1 + a[2] * x2 + a[3] * x4, # 0124 (0 is intercept)
b[0] + b[1] * x1 + b[2] * x2 + b[3] * x3, # 0123
c[0] + c[1] * x1 + c[2] * x3 + c[3] * x4, # 0134
d[0] + d[1] * x1 + d[2] * x2 + d[3] * x3 + d[4] * x4, # 01234
e[0] + e[1] * x1 + e[2] * x2, # 012
f[0] + f[1] * x1 + f[2] * x4, # 014
g[0] + g[1] * x2 + g[2] * x3 + g[3] * x4, #0234
]
# fmt: on
mu = pm.Deterministic(
"mu", pm.math.stack(_mu, axis=1), dims=("obs", "model")
)
pm.Normal("likelihood", mu=mu, tau=tau, observed=Y, dims=("obs", "model"))
trace = pm.sample(5000, target_accept=0.95, random_seed=rng)
pm.sample_posterior_predictive(
trace, extend_inferencedata=True, random_seed=rng
)
post_pred = trace.posterior_predictive["likelihood"]
post_pred_means = post_pred.mean(dim=("chain", "draw"))
post_pred_vars = post_pred.var(dim=("chain", "draw"))
# variance version (from previous page notes)
L2 = ((post_pred_means - Y) ** 2 + post_pred_vars).sum(dim="obs")
L = np.sqrt(L2).to_numpy()
# BUGS lecture version (not sure why they did it differently)
# L_bugs = np.sqrt(
# ((post_pred - Y) ** 2).sum(dim="obs")
# + post_pred.std(dim="obs", ddof=1) ** 2
# )
# L = L_bugs.mean(dim=("chain", "draw"))
L_df = pd.DataFrame(
{
"model": model_names,
"L": L,
}
)
L_df
| model | L | |
|---|---|---|
| 0 | 0124 | 11.828645 |
| 1 | 0123 | 11.814316 |
| 2 | 0134 | 12.009691 |
| 3 | 01234 | 12.187086 |
| 4 | 012 | 12.101945 |
| 5 | 014 | 13.063982 |
| 6 | 0234 | 13.390507 |
Posterior predictive checks#
Just going to introduce a quick example here.
az.plot_ppc_dist() compares the observed data distribution with simulated distributions.
az.plot_ppc_tstat() compares specific statistics between the posterior predictive and the observed value. For example, you might check the standard deviation or mean to see how close your model is to the data.
az.plot_ppc_interval() shows how well individual data points are predicted by the model.
az.plot_ppc_dist(
trace, var_names="likelihood", coords={"model": ["0124"]}
).show()
az.plot_ppc_dist(
trace, var_names="likelihood", coords={"model": ["0234"]}
).show()
So in the above two plots comparing the worst and best model by Laud-Ibrahim, it’s pretty clear that the models aren’t different enough for this kind of visual inspection to help us. In that case, it might be better to try using PSIS LOO-CV.
Below is the Bayesian t-stat plot mentioned above, which isn’t much more helpful for model comparion in this case.
az.plot_ppc_tstat(
trace, var_names="likelihood", coords={"model": ["0124"]}, t_stat="std"
).show()
az.plot_ppc_tstat(
trace, var_names="likelihood", coords={"model": ["0234"]}, t_stat="std"
).show()
The interval plot is interesting but still a little difficult to distinguish visually for this particular model. We’ll come back to PPCs again later in Unit 9.
az.plot_ppc_interval(
trace, var_names="likelihood", coords={"model": "0124"}
).show()
az.plot_ppc_interval(
trace, var_names="likelihood", coords={"model": "0234"}
).show()
%load_ext watermark
%watermark -n -u -v -iv -p pytensor
Last updated: Tue, 10 Nov 2026
Python implementation: CPython
Python version : 3.14.7
IPython version : 9.16.1
pytensor: 3.3.0
arviz : 1.3.0
matplotlib: 3.11.1
numpy : 2.4.6
pandas : 3.0.5
pymc : 6.3.2