1  Bayesian Inference: Optimisation and Sampling

The historic development of statistics is a turbulent affair, marked by profound success but also fraught with controversies and bitter disputes. Arguments ranged across philosophical and technical details about the meaning of probability statements and their provenance. In parallel, probability as an applied science progressed in a series of fits and starts, ranging over topics in political science, insurance, and medicine. Gigerenzer et al. (1989) call this series of conquests the Empire of Chance. Statistical inference is a discipline born from gambling problems that now encompasses territory across the natural and social sciences.

The venom in the methodological debates stems from the real and practical importance of statistical inference. Medical decisions and political policies, lives and livelihoods all rest on statistical evidence. Any protocol that determines how evidence should be weighed risks highlighting improper use. Improper use risks blood and treasure.

The costliest of these methodological disputes centre on a distinction between cause and association, between mechanism and prediction. Subtler disputes about the proper meaning of probability or asymptotic trends are bloodless in comparison. Get the causal distinction wrong, and nothing downstream repairs it. This chapter buys insurance against that risk early, giving us a statistical workflow careful enough to sustain the causal claims the rest of the book will ask it to support.

Important🗺 Chapter overview
  • What We’ll Cover
    • Data generating processes and the regression model
    • Parameter estimation by optimisation and by sampling
    • The Bayesian statistical workflow: priors, likelihoods, posteriors, and predictions
    • The distinction between statistical associations and causal claims
  • Learning Objectives
    • Understand how optimisation and sampling work with the same likelihood, and where the frequentist–Bayesian question actually enters
    • Specify and interpret prior distributions, likelihoods, and posterior distributions
    • Implement Bayesian regression models in Python using Bambi and PyMC
    • Recognise the limits of statistical models for causal inference
  • Prerequisites
    • Core Knowledge: Basic understanding of probability, statistics, and linear regression.
    • Technical Setup: Familiarity with Python and libraries such as pandas, matplotlib, statsmodels, Bambi, and PyMC.
  • Difficulty: Foundational. Assumes basic regression and Python; introduces the Bayesian workflow (priors, likelihoods, posteriors, predictions) and probabilistic programming with Bambi and PyMC. Briefly touches on exchangeability / de Finetti.

1.1 Statistical scaffolding

To navigate these stakes, and to build a reliable foundation for the causal models we will develop later, our focus here will be on a contemporary workflow for Bayesian inference.

Our focus is a familiar regression modelling problem. We’ll fit one model three ways: (1) as an optimisation problem with statsmodels, (2) as a sampling problem with Bambi, and then (3) the same problem expressed more vividly in PyMC. The sequence escalates in two directions at once: each step widens the space of models we can express, and each step widens how much of that space we can explore.

In applied work we define the quantity of interest, state the modelling assumptions, then choose an estimation approach. Let’s set the scene.

1.2 Study time and exam scores

We’ll work with a simple, simulated dataset: hours studied (\(X\)), baseline ability (\(A\)), and exam score (\(Y\)). We’ll assess how exam scores improve with increased studying, while we’re able to control for differences in ability across students. This is a real policy question in the educational sciences, but we keep the model deliberately simple. We’ll also make our lives easier and allow that we can measure ability accurately.

We treat ability as an exogenous variable and not something we can experimentally manipulate, while hours studied is a plausible intervention target. With this example we want to establish a workflow. We’ll see later that a robust workflow is the right way to establish compelling statistical claims.

Code
from bayesian_causal_infer.plotting import book_show
import arviz as az
from bayesian_causal_infer.plotting import style_library_figure
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc as pm
import pymc.dims as pmd
import seaborn as sns
import statsmodels.formula.api as smf
import xarray as xr

SEED = sum(map(ord, "bayesian-regression"))
rng = np.random.default_rng(SEED)
sample_kwargs = {"nuts_sampler": "nutpie", "random_seed": SEED}
bambi_sample_kwargs = {"inference_method": "nutpie", "random_seed": SEED}

from bayesian_causal_infer.plotting import (
    apply_book_style,
    book_daft_pgm,
    book_content_height,
    book_figsize,
    display_book_daft,
)

apply_book_style()
plt.rcParams.update({"figure.constrained_layout.use": True})

The simulation code below generates a dataset from known parameters, so we can later check how well our estimation approaches recover the true data generating process.

def simulate_study_data(
    N: int, rng: np.random.Generator, beta: dict, hours_mean=4, hours_sd=2, score_sd=4
):
    """Simulate a study-time dataset for N students.
    """
    df = pd.DataFrame(index=range(N))
    df = df.assign(
        ability=rng.normal(0, 1, N),
        hours=np.clip(rng.normal(hours_mean, hours_sd, N), 0, None),
        score=lambda d: (
            beta["intercept"]
            + beta["hours"] * d["hours"]
            + beta["ability"] * d["ability"]
            + rng.normal(0, score_sd, N)
        ),
    )
    return df

beta = {"intercept": 50, "hours": 3.0, "ability": 4.0}
df = simulate_study_data(500, rng, beta)

Two idioms in this code are worth flagging. First, we draw ability from a standard Normal distribution and hours from a Normal distribution with mean 4 and standard deviation 2. Both independent variables can be transformed to the same \(N(0, 1)\) standardised scale, so the sampling procedure is a reasonable proxy. The score outcome does depend on the already-created hours and ability columns, so it is passed to the lambda d: ... function interface. Second, np.clip(..., 0, None) clamps every value in the array to a minimum of zero. This is a simple way to prevent negative study hours without writing an explicit loop. Statistically, this imposes a floor constraint: values that would have fallen below zero are set to the boundary. Analogous constraints apply in the real world too; some variables are functions of others, some are independent, others are clipped at different levels. In real data, a similar pattern (left-censoring) arises when an observation mechanism truncates values. Such circumstances require careful modelling. The worldly mechanisms of truncation and mismeasurement might be more opaque than the code above, but they are no less real.

Let’s visualise the relationships to get a sense of the data before we dive into modelling (Figure 1.1).

Figure 1.1: Our simulated dataset for this chapter shows exam scores increasing linearly with the number of hours studied. There is also a linear effect of innate ability.

The cloud of points appears to trace out a linear relationship, rising up and to the right. There are obvious differences in achievement across the scale of ability. This suggests a multiple linear regression approach to parse and describe this data:

\[ Y = \beta_0 + \beta_1 X + \beta_2 A + \epsilon, \tag{1.1}\]

where \(\epsilon\) is a normally distributed error term.

As a refresher, what this says is: 1) we expect exam scores to increase linearly with hours studied and ability, and 2) there is some random noise (\(\epsilon\)) around that expectation. It is common in probabilistic programming to write the model in probabilistic notation:

\[ \begin{aligned} \mu &= \beta_0 + \beta_1 X + \beta_2 A \\ Y &\sim \text{Normal}(\mu, \sigma) \end{aligned} \tag{1.2}\]

This is equivalent to Equation 1.1, but it is more explicit in stating the model’s expectation (\(\mu\)) and the likelihood for \(Y\). The \(\sim\) symbol means “is distributed as,” so the second line says that \(Y\) is normally distributed with mean \(\mu\) and standard deviation \(\sigma\). Here, \(\sigma\) captures the variability in exam scores not explained by the predictors.

This is a subtle but important shift in how we think about the model. Where \(\epsilon\) is often treated as a nuisance term, the probabilistic notation foregrounds the generative reading: \(Y\) is a draw from a distribution, and the spread of that distribution is also a parameter to be characterised like any other. Let’s spell out what each of these parameters mean:

  • \(\beta_0\): The intercept, or expected exam score when hours studied and ability are both zero.
  • \(\beta_1\): The expected change in exam score for a one-hour increase in study time, holding ability constant.
  • \(\beta_2\): The expected change in exam score for a one-unit increase in ability, holding study time constant.
  • \(\sigma\): The standard deviation of the error term, representing the variability in exam scores not explained by the model.

To make the structure explicit, we can draw a simple computational graph (Figure 1.2). It shows the two predictors feeding into the outcome, with coefficients on the arrows.

Figure 1.2: This diagram is a computational/statistical graph: it encodes how the model combines predictors to generate outcomes. In later chapters, we introduce causal graphs (DAGs) and explain how their interpretation differs, even when they can look visually similar.

As it stands, this is a process mapping of the relationships between the variables in the model. Even a “simple” regression model is to be thought of as a generative process. Our focus (the estimand) is whether hours studied improves exam scores. We are imposing structure on that process by saying the outcome results from a linear combination of the predictors. The question this chapter answers is what the data can tell us about the parameters in that data generating process. We’ll first characterise the parameters as a single best-fitting point and then as a distribution over the plausible ones. Whether \(\beta_{1}\) actually measures the effect of studying more is a different question, and the following chapters take it up.

1.3 What are we estimating?

Now we’ve got our model specified (Equation 1.2), we need to estimate the parameters (\(\beta_0\), \(\beta_1\), \(\beta_2\), and \(\sigma\)) from the data.

We’ve narrowly outlined the model as a problem about parameters and how they are weighted and combined to generate the observed data. The parameters characterise a relationship, and there are many different ways the relationships could have been realised in the world. Statistical inference is the process of learning about the probable realisations of the parameters. The parameters serve as proxies for the real world relationships. For example, if the parameter estimate for hours studied is positive then we would expect an improvement in exam scores due to increased hours of study. The parameter is statistically identifiable if we can uniquely characterise the relationship from the distribution of the data.

The mapping between statistical quantity and real-world relationship is always imperfect. However, the proxy-relationship of our regression estimate is informed by observed data through statistical inference.1 Once we posit a suitable mapping, then we can use an estimation strategy to derive insight into the probable values of the focal parameter \(\beta_{1}\). We will work through two methods: (1) Optimisation searches the parameter space for the single best-fitting point, and (2) Sampling draws from that space repeatedly, tracing out a distribution rather than converging on a point. Both are built upon the likelihood structure of the model.

These are computational strategies, not creeds. There is a separate (more contentious) question of what a frequentist or a Bayesian is entitled to say about the resulting numbers, but we’ll defer that to after we’ve made the computational strategies concrete. We’re comparing the methods, not to criticise one or other philosophy of inference, but to highlight the focal objects of Bayesian inference and elaborate how the prior, posterior and posterior predictive distributions are mapped to a concrete modeling question.

1.4 Estimation by optimisation

The likelihood computation gives us a score for every candidate-setting of the parameters, gauging how well that setting accounts for the data we observed. Optimisation walks the score uphill and returns the point where it peaks. What comes back is one number per parameter, together with a standard error read off the curvature of the surface around that peak.

1.4.1 The likelihood surface

The hill-climbing routine is often called maximum likelihood estimation (MLE), and for the standard Gaussian likelihood linear regression model, maximising the likelihood yields the same coefficient estimates as the ordinary least squares (OLS) analytical solution. This is one of the properties that makes linear regression so useful.

The next code block implements some helper functions to compute the log-likelihood surface for our regression model over the parameter space of \(\beta_1\) and \(\beta_2\). The intercept is profiled out: at each candidate slope pair we give it whatever value fits best, so every point on the surface represents the best the model can do at those slopes. This allows us to visualise how the likelihood varies with different parameter values across the grid, but in practice most optimisation packages use closed-form linear algebra solutions to find the MLE estimates of the parameters.

# Treat beta_1, beta_2 as free. The intercept is profiled out: at each candidate
# slope pair we give it its best-fitting value, so the surface shows the best the
# model can do there. Sigma is held fixed, which rescales the surface without
# moving its peak.
sigma_fix = 4.0
n_obs = len(df)

Y = df["score"].values
X = df["hours"].values
A = df["ability"].values


# Best-fitting intercept for a candidate (b1, b2) is the mean residual:
#   β₀(β) = mean(Y_i − β₁·X_i − β₂·A_i)
def profiled_intercept(b1, b2):
    return np.mean(Y - b1 * X - b2 * A)


# For a candidate (b1, b2), the residuals map directly onto the regression equation:
#   ε_i(β) = Y_i − β₀(β) − β₁·X_i − β₂·A_i
def residuals(b1, b2):
    return Y - profiled_intercept(b1, b2) - b1 * X - b2 * A


# Sum of squared residuals: S(β) = Σ_i ξ_i(β)²
def S(b1, b2):
    return np.sum(residuals(b1, b2) ** 2)


# Gaussian log-likelihood: ℓ(β, σ) = −n/2·log(2π) − n/2·log(σ²) − S(β)/(2σ²)
def log_lik(b1, b2):
    return (
        -n_obs / 2 * np.log(2 * np.pi)
        - n_obs / 2 * np.log(sigma_fix**2)
        - S(b1, b2) / (2 * sigma_fix**2)
    )

The next visualisation Figure 1.3 plots the parameter space on the 2D plane. In this well-behaved regression problem the maximum value of the parameter space just is the point estimate of the parameters that maximises the likelihood. The star marks the maximum likelihood estimate, while the cross marks the true data-generating values. The optimisation routine gives back the best-fitting parameters for this sample data.

Figure 1.3: The Gaussian log-likelihood surface over \(\beta_{\text{hours}}\) and \(\beta_{\text{ability}}\), with the intercept profiled out and the noise scale held fixed. The star marks the maximum likelihood estimate, the peak of the surface. The cross marks the true data-generating values.

The maximum likelihood inference strategy works by finding the parameter values that maximise the likelihood (or probability density) of the observed data under the model. Under the linear model specification we search for parameters that predict \(Y\) (as well as possible) given the observed \(X\) and \(A\). The search for optimal fit is conditional on the model specification.

\[ \begin{aligned} \varepsilon_i(\beta) &= Y_i - (\beta_0 + \beta_1 X_i + \beta_2 A_i), \\[6pt] S(\beta) &= \sum_{i=1}^n \varepsilon_i(\beta)^2, \\[10pt] (\hat{\beta}, \hat{\sigma}^2) &= \arg\max_{\beta \in \mathbb{R}^3,\; \sigma^2 > 0} \left\{ -\frac{n}{2}\log(2\pi) -\frac{n}{2}\log(\sigma^2) -\frac{1}{2\sigma^2} S(\beta) \right\}. \end{aligned} \]

The displayed equation is the full Gaussian log-likelihood. We maximise it jointly over \(\beta\) and \(\sigma^2\). But notice that \(S(\beta)\) enters with a negative sign and is the only term that depends on \(\beta\). So for the regression coefficients, maximising the log-likelihood is equivalent to minimising the sum of squared errors \(S(\beta)\). That is the OLS criterion. The variance estimate \(\hat{\sigma}^2\) requires the remaining terms, but the coefficients fall out of the simpler optimisation problem. The behaviour of the estimator across repeated samples is easy to state: under regularity conditions, the MLE is consistent and asymptotically normal. This means that as we hypothetically grow our classroom to more and more students (\(N \to \infty\)) and re-estimate our parameters each time, two things happen: (a) the sampling distribution of those estimates converges toward a perfectly symmetric Gaussian curve, and (b) its variance shrinks, focusing our estimates tighter and tighter around the true data-generating values. These are guarantees about the procedure under hypothetical repetition rather than about the single estimate in hand.

1.4.2 Estimation with the statsmodels package

We now fit a regression model. Under the hood the algorithm will minimise the error of the predictions to derive the parameter estimates. We fit the linear model described in Equation 1.2 via the statsmodels library, because the package offers the convenient Wilkinson formula interface to specify the model.

ols_result = smf.ols("score ~ 1 + hours + ability", data=df).fit()

The formula string "score ~ 1 + hours + ability" specifies the mean structure of the model. The left-hand side (score) is the outcome variable, and the right-hand side specifies the predictors. 1 indicates that we want to include an intercept term in the model. hours and ability are the main effects we want to include.

Note📖 Wilkinson-Rogers notation (formula syntax)

Wilkinson-Rogers notation (Wilkinson and Rogers 1973) is a compact way to describe the mean structure of a linear model, where each term specifies which predictors and interactions are included. The table below summarises the most common notation patterns:

Notation Meaning Example expansion
1 Include an intercept y ~ 1
0 or -1 Remove the intercept y ~ 0 + x
x Include main effect of x y ~ 1 + x
x1 + x2 Add main effects y ~ 1 + x1 + x2
x1:x2 Include interaction only y ~ 1 + x1:x2
x1*x2 Main effects plus interaction y ~ 1 + x1 + x2 + x1:x2
C(x) Categorical variable (dummy-coded) y ~ 1 + C(grade) expands grade into \(k-1\) indicator variables, one per level after a reference category

The compact syntax scales well. A three-way interaction like x1*x2*x3 expands to seven terms without being written out by hand: three main effects, three two-way interactions, and one three-way interaction. Categorical variables multiply this further: a model with a continuous predictor fully interacted with a \(k\)-level factor, x * C(group), simultaneously fits \(k\) separate slopes. This combinatorial expressiveness means you can describe a wide range of linear mean structures in a single readable line.

This same syntax extends to generalized linear models (GLMs): logistic regression for binary outcomes, Poisson for counts, and others. Simply by pairing the formula with a different likelihood family and link function, we can model a range of different outcome types. Each pairing of formula with likelihood family is a different composition of building blocks: the same predictive structure with different distributional assumptions about the outcome.

This code fits the model and returns an object containing the results, which we report below.

ols_result.summary().tables[1]
Table 1.1: Summary statistics from the OLS regression.
coef std err t P>|t| [0.025 0.975]
Intercept 49.5377 0.407 121.594 0.000 48.737 50.338
hours 3.1652 0.090 35.178 0.000 2.988 3.342
ability 4.1082 0.187 21.955 0.000 3.741 4.476

Examining the regression coefficients in Table 1.1 we could say the following:

  • baseline exam score (the intercept) with zero hours studied and ability equal to zero is around 50 points.
  • for every one unit increase in innate ability score (let’s not worry about what this measurement would mean), exam scores increase by about 4 points, holding hours studied constant.
  • for every additional hour studied, exam scores increase by about 3 points, holding ability constant

And we can visualise this by plotting the expected exam score across different levels of ability in Figure 1.4.

Figure 1.4: We overlay the expected exam score lines from the OLS regression model across different ability levels. Each line shows how exam scores are expected to increase with hours studied for a given ability level.

The lines trace out the modelled approximation to the relationship between hours studied and exam scores, while varying different levels of ability. From the estimate of the slope \(\beta_{1}\) of the lines we can summarise the relationship. The positive slope indicates that more hours of study is associated with higher exam scores. Although, you might reasonably wonder whether the real-world relationship is so linear and consistent across all levels of ability.

The OLS output in Table 1.1 also reports confidence intervals and p-values, the standard frequentist measures of uncertainty. A 95% confidence interval means: if we repeated the study many times, 95% of such intervals would contain the true parameter. A p-value measures how surprising the data would be under the null hypothesis of no effect. Both measures are properties of the procedure under repetition.

1.5 Estimation by sampling

The second strategy does not climb the likelihood surface. It explores it. Rather than returning the single highest point, we draw repeatedly from the parameter space and retain draws in proportion to how well they account for the data. What comes back is not a point but a cloud.

Sampling is a more expansive operation, costing more in compute time than a comparable optimisation of a closed form solution. The mechanics oblige us to say what we are sampling from: a distribution over the parameter space, supplied in advance. That distribution is the Bayesian prior. The prior places a weighting on the search space. We treat the data as fixed (we have observed it) and the parameters as random variables with probability distributions. The Bayesian learning algorithm samples across the space of parameters \(\beta_{0}, \beta_{1}, \beta_{2}, \sigma.\) The space of parameters is constrained by how we set up the model. We start with prior beliefs about the parameters, then update these beliefs using the observed data to obtain posterior distributions. Uncertainty is naturally quantified through the posterior distributions because the process literally explores and characterises plausible realisations of the parameters conditioned on the data, our priors and the model structure.

In the most concise but abstract form, the Bayesian learning process can be expressed with Bayes’ theorem:

\[\overbrace{p(\theta \mid \text{data})}^{\text{posterior}} \;\propto\; \overbrace{p(\text{data} \mid \theta)}^{\text{likelihood}} \; \overbrace{p(\theta)}^{\text{prior}} \]

Written out in full this proportionality becomes an equality once we restore the normalising constant in the denominator:

\[ \underbrace{p(\theta \mid \text{data})}_{\text{posterior}} \;=\; \frac{\overbrace{p(\text{data} \mid \theta)}^{\text{likelihood}}\,\overbrace{p(\theta)}^{\text{prior}}}{\underbrace{p(\text{data})}_{\text{marginal likelihood}}} \]

The restored denominator is the marginal likelihood \(p(\text{data}) = \int p(\text{data} \mid \theta)\,p(\theta)\,d\theta\), the probability of the data averaged over the prior. Each term now has a distinct job: the prior \(p(\theta)\) states what we are willing to entertain about the parameters before seeing the data; the likelihood \(p(\text{data} \mid \theta)\) measures how well any particular parameter setting explains what we observed; and their product, renormalised, is the posterior \(p(\theta \mid \text{data})\), our updated belief. For the task of learning \(\theta\) the marginal likelihood is a constant we can ignore, which is why the proportional form suffices. But it is not merely bookkeeping. The marginal likelihood scores how well the model as a whole predicts the data and it is the basis for Bayesian model comparison. It reappears in explicit form when we assemble the implied covariance of a structural equation model in Chapter 7.

For our regression model, we can concretely write down the equation’s parameters:

\[ \begin{aligned} \vec{\beta} &= (\beta_0, \beta_1, \beta_2)^\top, \\[6pt] \mathbf{X} &= (1, X, A), \\[6pt] p(\vec{\beta}, \sigma \mid \mathbf{Y}, \mathbf{X}) &\propto p(\mathbf{Y} \mid \mathbf{X}, \vec{\beta}, \sigma) \, p(\vec{\beta}) \, p(\sigma). \end{aligned} \]

The sampler visits parameter values in proportion to prior times likelihood, so the draws it keeps trace out the posterior. The process gives us access to the fully sampled posterior distribution. Implicit in this formulation is that there is a structural relationship between \(\mathbf{Y}, \mathbf{X},\vec{\beta}, \sigma\). As in the optimisation goal, there is an assumed mapping between the predictors, the parameters and the data, but in the Bayesian setting we learn of plausible mappings.

\[ \mathbf{Y} = f(\mathbf{X}, \vec{\beta}, \sigma)\]

There is some functional relationship between the predictors and the outcome and we sample across instantiations of that functional form. Both optimisation and sampling are trying to learn about the parameters that characterise this relationship. But the specification of the structural relationship is under-specified in both abstract formulations of MLE and Bayesian Updating.

Some of the primary benefits of the Bayesian formulation include making the structural relationship more explicit, but also:

  • Structural Flexibility: The parameter space and priors can be configured to be as complex or hierarchical as needed to more accurately match the true data-generating process.
  • Natural Error Propagation: Uncertainty at any stage of the model propagates through the likelihood to the posterior.
  • Information Integration: The freedom to establish constraints via priors allows us to formally incorporate historical data, physical constraints, or expert knowledge directly into the model.

We highlight briefly some benefits of the sampling approach here only to advertise the aspects of Bayesian inference we will lean on throughout the book. The sampling view pushes us to think about generative flow from our structured parameters through the functional form of the model to the resulting outcome. This generative focus is key. The prior to posterior move is justified by a similar generative view. Given exchangeability and de Finetti’s representation theorem, we can decompose each model into a prior to posterior sampling routine.2

Tip🔍 Exchangeability and the Bayesian warrant

The structure \(\mathbf{Y} = f(\mathbf{X}, \vec{\beta}, \sigma)\) treats the parameters as the unknown and the observations as the known. The focus is on learning about the parameters given the data. But this division is motivated by appeal to de Finetti’s representation theorem. Suppose we have reason to treat individual observations as exchangeable. That is, we know nothing special about any particular student that isn’t already captured by the covariates. Then there is an implied representation of the data in which the observations are generated independently, conditional on the latent parameters and each student’s own covariates.

\[p(y_1, \ldots, y_n \mid x_1, \ldots, x_n) = \int \prod_{i=1}^{n} p(y_i \mid x_i, \theta) \, \mathrm{d}F(\theta)\]

where \(F\) is a distribution over the latent parameter \(\theta\), shared across students, while each \(y_i\) is drawn conditional on both \(\theta\) and its own covariates \(x_i\). Formally the exchangeability premise states that the joint distribution of the observations is unchanged by reordering the observations, once each observation carries its covariates with it. It is a symmetry assumption. De Finetti’s representation theorem shows that any such exchangeable sequence can be written as conditionally independent draws from a common distribution parametrised by some latent \(\theta\).3 That latent \(\theta\) is exactly our \((\vec{\beta}, \sigma)\): fixed across students, while \(x_i\) varies from student to student. The theorem is what turns the intuition of “neutral, general-purpose learning” into a mathematical warrant for the prior-likelihood-posterior structure. Just when we can adopt the exchangeability premise, we can treat the parameters as random variables and the observations as fixed, and use Bayes’ theorem to update our beliefs about the parameters in light of the observed data.

Exchangeability is rarely all-or-nothing. We seldom treat every observation as exchangeable with every other, but we can often treat it as holding within groups: students within a school, or choices within a person. This conditional exchangeability leads very naturally to hierarchical models, where each group draws its own parameters from a shared population distribution, and groups with sparse data borrow strength from the rest.

1.5.1 Bayesian regression in Bambi

At the level of model specification, the code for Bambi is very similar to statsmodels. This speaks to the ubiquity and general usefulness of regression relationships. What changes is what the estimator demands and returns: smf.ols returned a point, bmb.Model(...).fit() returns draws from the posterior. The Bambi model also asks for our prior specification.

Bambi will automatically translate the formula and priors into a PyMC model under the hood, and then we can use MCMC (Markov Chain Monte Carlo) sampling to estimate the posterior distributions of the parameters.

bmb_model = bmb.Model(
    "score ~ hours + ability",
    data=df,
    priors={
        "Intercept": bmb.Prior("Normal", mu=50, sigma=10),
        "hours": bmb.Prior("Normal", mu=0, sigma=5),
        "ability": bmb.Prior("Normal", mu=0, sigma=5),
        "sigma": bmb.Prior("HalfNormal", sigma=5),
    },
)
bmb_idata = bmb_model.fit(
    **{
        **bambi_sample_kwargs,
        "draws": 5000,
        "tune": 2000,
        "random_seed": SEED,
    }
)

We see the intercept is set as drawing from a normal distribution characterised with a mean of 50, and a standard deviation of 10. This maps well to (a) a decent baseline for exam scores and (b) the linear intercept on the line plots above. The beta coefficients for hours and ability are set to be normally distributed with a mean of 0 and a standard deviation of 5. This null-effect prior is a common choice for regression coefficients, as it allows for a wide range of plausible values while still being centered at zero. In this way we can use priors to encode transparent commitments about the data generating relationship. A few of those commitments are structural constraints: the HalfNormal on sigma gives a negative standard deviation no mass at all, because that is not a quantity the model can admit. Other commitments are softer. The Normal(0, 5) does not forbid wild swings in effect, but the shape of the prior assigns them low mass in the distribution and leaves the data to argue against them. Priors are a way to encode our domain knowledge and common sense into the model, and they also help to regularise the estimation process, especially in cases where the data may be sparse or noisy.

This API is simple and clean. We provide a dataframe and a formula string to build a model, then call fit() to estimate the parameters using MCMC. The major difference is the addition of specifying priors which count as commitments about the data generating process. Before fitting anything, we can look at what those priors alone imply. This step has no counterpart on the optimisation route: there is nothing to plot before a solver runs, because the search has no state until it starts. Under sampling, the parameter space is characterised before the data arrives, and we can inspect its features.

Figure 1.5: Priors over parameters

Each prior panel in Figure 1.5 is wide and centred on no effect deliberately. We have committed to very little beyond making absurdities improbable. Conditioning on the data will do the rest of the work. The plot Figure 1.6 shows the posterior distributions for the hours and ability coefficients, with reference lines indicating the true parameter values.

Figure 1.6: This plot shows the true coefficient values for hours and ability (black plus symbols), and the posterior distributions over the parameter estimates. The circles represent the posterior means and the error bars represent the 94% highest density credible interval.

We can see that our parameter estimation has done pretty well. The posterior means are slightly offset from the true parameters and this will be just because we are dealing with a finite sample size. But we can see that the level of deviation is low relative to the credible interval. The true coefficient values lie well inside the credible intervals.

Warning⚙️ Credible intervals vs confidence intervals

A 95% Bayesian credible interval says: given the data and model, there is a 95% probability the parameter lies in this range. In this way Bayesian analysis is “just counting”. You count the proportion of samples from the posterior in each range. The proportion gives you the probability statement. In contrast, a 95% frequentist confidence interval says: if we repeated the experiment many times, 95% of such intervals would contain the true value. The credible interval makes a direct probability statement about the parameter; the confidence interval makes a statement about the long-run properties of the procedure. The Bayesian credible interval is a direct probability statement about which parameter values are plausible when accounting for the data using a coherent update rule. The frequentist confidence interval is an indirect statement about realisability under a repeated process. Both are attempts to quantify uncertainty and in practice the numerical values are often similar (especially with weakly informative priors) but the interpretation differs. It’s the difference in interpretation which fuels the Statistics wars.4

1.5.2 Bayesian regression in PyMC

Bambi is a powerful and expressive package. By focusing on formula notation and linear modelling, it is possible to specify a broad range of models using a concise and clear API. However, behind the scenes Bambi builds a model in a general purpose probabilistic programming language (PPL) called PyMC.

We’re going to come across many examples in this book where we have to go beyond simple linear modelling that can be described by the formula syntax. So we will embrace full probabilistic programming using PyMC. Let’s dive in and understand how we can use PyMC to build the same model that we have just seen in Bambi. The PyMC version of the model (Equation 1.2) looks identical in its mean structure, but we explicitly place priors on the parameters and quantify uncertainty via the posterior as in Bambi. In code Equation 1.2 is adapted to become:

\[ \begin{aligned} \beta_0 &\sim \text{Normal}(50, 10) \\ \beta_1 &\sim \text{Normal}(0, 5) \\ \beta_2 &\sim \text{Normal}(0, 5) \\ \sigma &\sim \text{HalfNormal}(5) \\ \mu &= \beta_0 + \beta_1 X + \beta_2 A \\ Y &\sim \text{Normal}(\mu, \sigma) \end{aligned} \tag{1.3}\]

These are the distributional building blocks from which we compose our regression model. Notice that the model expectation and likelihood terms are unchanged. All we have done is to specify priors for each of the parameters individually.

with pm.Model(coords={"student": df.index.to_numpy()}) as model:
    # Data containers
    x = pmd.Data("hours", df["hours"], dims="student")
    a = pmd.Data("ability", df["ability"], dims="student")
    y = pmd.Data("score", df["score"], dims="student")
    # priors over parameters
    intercept = pmd.Normal("intercept", mu=50, sigma=10)
    b_hours = pmd.Normal("b_hours", mu=0, sigma=5)
    b_ability = pmd.Normal("b_ability", mu=0, sigma=5)
    sigma = pmd.HalfNormal("sigma", 5)
    # the linear model
    _mu = pmd.Deterministic("mu", intercept + b_hours * x + b_ability * a)
    # the likelihood term
    pmd.Normal("score_obs", mu=_mu, sigma=sigma, observed=y)

The functional form of the mapping between the predictors and the outcome is the same as before, but here made more explicit in the code. The flexibility offered by PPLs like PyMC is that we can specify any functional relationship we like, not just linear.

\[ \mathbf{Y} = f(\mathbf{X}, \vec{\beta}, \sigma)\]

This flexibility is crucial for understanding how to structure richer causal models and how to interpret interventions on these data generating systems. The freedom to swap and constrain the interactions of different distributional components is incredibly powerful.

There is no doubt that this is much more verbose than the Bambi or OLS versions. However, if you look back and forth between Equation 1.3 and the PyMC code, you can see the one-to-one correspondence between the mathematical notation and the code structure. There are only a few additions: First, we specify data containers using pm.Data, which allows us to easily swap in new data later (useful for g-computation, the intervention-estimation recipe we introduce in Chapter 2). Second, we use pm.Deterministic to create a named variable for the linear predictor \(\mu\), which is useful for later reference. Third, the likelihood term is defined using the observed data with the observed=y argument. Finally, the data are named along the student axis. With pymc.dims, that name participates in tensor operations, so the linear predictor inherits the student dimension and the likelihood does not need a repeated dims declaration.

Each line of this specification is a building block: a distributional choice (Normal, HalfNormal), a structural relationship (the linear predictor), or a deterministic transformation. The model is their composition.

Behind the scenes, PyMC is building a computational graph that represents every probabilistic and deterministic relationship in the model. This graph is used for efficient gradient computation during sampling. We can also inspect it directly by calling model.to_graphviz().

Figure 1.7: The Computational Graph representing the flow of influence resulting in the Outcome

We can see in Figure 1.7 the computational graph for the PyMC model.5 This graph represents the relationships between variables in the model and is used for efficient computation during sampling and inference. Shaded nodes represent observed data. Square nodes represent deterministic variables. Circular nodes represent random variables. Rounded boxes represent data containers. The large box which encompasses many of the nodes is called a plate, and it indicates that the nodes inside it are replicated for each observation in the dataset. In our case all the nodes in the plate are replicated for each of the 500 students in our dataset. The observed values of Student scores are downstream effects of their weighted ability, population norms and hours studied. The functional expression which takes these inputs is fed forward into our likelihood term and calibrated against the data.

This is a good moment to appreciate the difference in expressive capacity between a PPL and a formula-based syntax. Wilkinson notation describes the mean structure of a model. It says which predictors and interactions enter a linear combination. PyMC, by contrast, lets you specify any number of likelihoods, priors, and any deterministic relationships between variables: hierarchical structures, non-linear predictors, custom distributions, latent variables or Gaussian processes. The Wilkinson syntax is a restricted but highly convenient sublanguage; the PPL is the full language underneath it. The language gives us expressive freedom and flexibility to articulate complex modelling structures we will see throughout the book.

1.5.3 Sampling the posterior with MCMC

We can begin parameter estimation (using MCMC sampling) with the following code.

with model:
    idata = pm.sample(
        **{
            **sample_kwargs,
            "draws": 5000,
            "tune": 2000,
        }
    )

Markov chain Monte Carlo (MCMC) is the workhorse algorithm for Bayesian inference. Rather than solving for the posterior analytically, MCMC constructs a random walk through the parameter space. At each step, proposed parameter values are accepted or rejected based on how well they explain the data, weighted by the priors. Over many steps, the visited values form a representative sample from the posterior distribution. By default PyMC uses the No-U-Turn Sampler (NUTS), a gradient-based sampler that explores high-dimensional posteriors efficiently.

# The 2.0-inch trace floor collapses under constrained layout once the
# suptitle is added. 3.6 inches keeps the title off the top row.
trace_height = 3.6
pc = az.plot_trace_dist(
    idata,
    var_names=["b_hours", "b_ability"],
    figure_kwargs={"figsize": book_figsize(height=trace_height)},
)
fig = pc.get_viz("figure")
from matplotlib.ticker import MaxNLocator

for axis in fig.axes:
    axis.xaxis.set_major_locator(MaxNLocator(nbins=4, prune="both"))
    axis.yaxis.set_major_locator(MaxNLocator(nbins=4, prune="both"))

fig.suptitle("Posterior trace plots for the hours and ability coefficients")
style_library_figure(fig, height=trace_height)
book_show(fig)

Standard diagnostics (\(\hat{R}\), effective sample size, and trace plots) help verify that the chains have converged and mixed well. Here we can see that the MCMC chains overlap, caterpillar-like, exploring regions of the parameter space, which is a good sign of convergence. This is the analogue of checking that an optimiser has settled on a stable solution rather than stalling on a ridge. Both strategies traverse the same parameter space; the sampler keeps a record of where it has been, while the optimiser retains only its current best guess.

The trace plot is a visual check. The numerical gates are \(\hat{R}\), which compares the spread within each chain to the spread between chains, and the bulk and tail effective sample sizes, which count how many independent draws the correlated chains are worth. Table 1.2 reports the worst value of each across every parameter in the model.

Table 1.2: Worst-case convergence diagnostics across all parameters of the PyMC model.
max r_hat min ess_bulk min ess_tail
all parameters 1.00 6886 8500

No parameter has an \(\hat{R}\) above 1.00, and the smallest bulk effective sample size is 6,886 from 20,000 draws. The chains agree with each other, so we can read the posterior.

Figure 1.8: Posterior distributions for the PyMC model parameters. The vertical lines indicate reference values for the hours and ability coefficients, which correspond to the true data-generating values used in the simulation.

Figure 1.8 shows very similar posterior distributions to the Bambi model (see Figure 1.6). This is expected because both models are fitting the same statistical relationship, and we matched the priors across Bambi and PyMC.

1.6 Two strategies, one surface

We now have both estimates in hand, and we can put them on the same axes (Figure 1.9). The log-likelihood surface is a nice way to illustrate what we get from each estimator, showing the variability in potential parameterisations.

Figure 1.9: The same log-likelihood surface, before and after the data.

The left panel shows where sampling starts: draws from the priors, spread across the surface with no regard for where the likelihood peaks. The right panel shows where it ends. Conditioned on the data, the cloud has contracted onto the peak, into a region too small to see at the left panel’s scale, where the star sits. Sampling returns this cloud of draws, which we can also summarise by its mean (circle). The star and the circle coincide: this is a common feature with wide priors and well-behaved data generating processes. In thornier problems, gaps between the point estimates reflect differences in the way the estimators leverage information.

What matters is the breadth of the cloud of points. The spread of the cloud is a characterisation of uncertainty that responds and shifts when we change an assumption and re-run the posterior sampling. Like a cloud of swallows reacting to an airhorn, scattering and then coalescing, the posterior distribution shifts as we update our priors or incorporate new data. The ability to intervene and perturb these distributions will be crucial to understanding the data generating mechanisms and establishing legitimate causal interpretations of statistical models.

Tip🔍 Where the frequentist–Bayesian question actually sits

Optimisation and sampling are computational strategies. Traditionally, the frequentist–Bayesian distinction is about which guarantees you are entitled to claim. We crudely gloss the differences in focus below.

On the frequentist account the object of study is the procedure. An estimator is a function of the data, and its properties (e.g unbiasedness, minimum variance, coverage, controlled error rates) are statements about how it would behave across hypothetical repetitions of the study under identical conditions. Probability attaches to the procedure, not to the parameter. Confidence intervals, p-values and hypothesis tests are all designed around these operating characteristics: a procedure is trustworthy not because it says the right thing about the dataset in front of you, but because it would say the right thing often enough if applied over and over.

On the Bayesian account the object of study is the posterior. Probability attaches to the parameter, conditional on the data, the model and the prior, and the organising warrant is coherence rather than long-run error control. This does not exempt a Bayesian model from the other kind of scrutiny: posteriors can be, and routinely are, checked for calibration and coverage.

In this chapter optimisation happened to deliver a frequentist reading because MLE strategies are designed to have good long run properties, while MCMC sampling gets a Bayesian one. But nothing about the mechanics of MCMC requires it. The discipline of contemporary Bayesian workflows can be seen to yield Bayesian models with good frequentist properties. The place where the distinction has real practical bite for us is in the reading of credible intervals, which is the subject of the callout above. For a broader discussion of the philosophical differences between inference frameworks, see, for example, (Dienes 2008; Jaynes and Bretthorst 2003; Mayo 2018).

1.7 The pattern with PyMC

With the model specified and fitted, we can now map the core probabilistic operations: prior sampling, conditioning and prediction, to their PyMC counterparts.

1.7.1 1) Start with the joint model

The model object we built above is a joint probability model over unknown parameters and outcomes. In compact notation:

\[ p(\beta_0, \beta_1, \beta_2, \sigma, Y \mid X, A) \]

At this stage, no new data has been attached beyond the model definition itself. We have a structured set of assumptions: priors, likelihood, and deterministic relationships.

# A model definition encodes the joint structure.
with pm.Model() as model:
    ...

1.7.2 2) Sample from the prior predictive distribution

Before conditioning, it is often useful to ask what kind of outcomes the model can generate from priors alone. This is a quick calibration check: are the implied outcomes plausible?

with model:
    prior_pred = pm.sample_prior_predictive(
        draws=500,
        random_seed=SEED,
        compile_kwargs={"mode": "FAST_COMPILE"},
    )
Figure 1.10: Exam scores the model generates from its priors alone, against the observed scores.

Figure 1.10 answers the question. The priors put 94% of simulated scores between 0 and 98, while the observed scores run from 37 to 87. Every score we saw is one the model was prepared to generate, and the prior does not pre-empt the data by concentrating where the scores happen to fall. The check also shows a cost of the unbounded Normal likelihood: 3% of simulated scores are negative, which no exam produces. The bounded-score model in Section 2.1 removes that possibility.

1.7.3 3) Condition on observed data and sample the posterior

Conditioning means updating beliefs using observed values. Here the model is conditioned when score is supplied as the observed value of score_obs; the pm.sample call below then draws from that posterior. In a generative model with an unobserved random variable, pm.observe can instead attach observations to that random variable by name.

After this step, inference targets the posterior distribution:

\[ p(\beta_0, \beta_1, \beta_2, \sigma \mid Y, X, A) \]

In practice, the model is already conditioned by its observed likelihood, so we draw posterior samples from model. In the Bayesian framework, the distinction between a parameter and a data variable is less absolute than it first appears: both are nodes in the same generative graph, each assigned a distribution. What marks something as data is not its nature but our epistemic attitude toward it. We have observed it, and so we condition on it. The same logic will apply in later chapters when we place priors directly on causal path strengths and realised outcomes, treating them as quantities to be inferred from data, not fixed inputs.

1.7.4 4) Make out-of-sample posterior predictions

After fitting, we often want predictions for new covariate values that were not used for model fitting. In PyMC, we can update the pymc.dims data containers and the corresponding named coordinate with pm.set_data(...), then push posterior uncertainty through the likelihood with pm.sample_posterior_predictive(...).


new_students = pd.DataFrame({
    "hours": [1.0, 3.0, 5.0, 7.0],
    "ability": [-1.0, 0.0, 0.5, 1.0],
})

with model:
    pm.set_data({
        "hours": new_students["hours"],
        "ability": new_students["ability"],
    }, coords={"student": new_students.index.to_numpy()})
    pred_oos = pm.sample_posterior_predictive(
        idata,
        var_names=["score_obs"],
        random_seed=SEED,
        compile_kwargs={"mode": "FAST_COMPILE"},
    )

Conceptually, this draws from the posterior predictive distribution: predictive outcomes for new cases, formed by integrating the likelihood over the posterior we have just fitted.

\[ p(\tilde Y_{new} \mid X_{new}, A_{new}, Y, X, A) = \int p(\tilde Y_{new} \mid X_{new}, A_{new}, \vec{\beta}, \sigma)\; p(\vec{\beta}, \sigma \mid Y, X, A)\; d\vec{\beta}\, d\sigma \]

This has the same shape as the marginal likelihood we met earlier: in both, we average the likelihood over a distribution of the parameters. The difference is which distribution. To score the data we already had, we averaged over the prior; to predict data we have not yet seen, we average over the posterior. MCMC makes the integral mechanical: rather than evaluating it in closed form, we push each posterior draw through the likelihood and collect the resulting outcomes, which is exactly what pm.sample_posterior_predictive does.

Figure 1.11: Exam scores the model generates from its posterior, against the observed scores.

Figure 1.11 repeats the check after conditioning. The posterior predictive puts 94% of simulated scores between 46 and 78, inside the observed range of 37 to 87, and the share of negative simulated scores falls to 0.00%. Conditioning has done what the prior left open: the predictions now concentrate where the scores fall.

1.7.5 Quick map: concept to operation

Probabilistic concept What it answers PyMC operation Representative command
Joint model \(p(\beta, Y \mid X, A)\) What relationships are possible before seeing data? model specification with pm.Model() as model: ...
Prior predictive \(p(\tilde Y \mid X, A)\) What data could the model generate from priors alone? prior predictive sampling pm.sample_prior_predictive
Conditioning and sampling \(p(\beta \mid Y, X, A)\) What parameter values are plausible after observing this dataset? sample a model with an observed likelihood pm.sample
Out-of-sample posterior predictive \(p(\tilde Y_{new} \mid X_{new}, A_{new}, Y, X, A)\) What outcomes are plausible for new covariate values after fitting? update named data and coordinates, then sample predictive pm.set_data, then pm.sample_posterior_predictive

This last mechanism is crucial. pm.set_data changes the inputs and labels along the resized student axis, and pm.sample_posterior_predictive pushes the whole posterior through that change, returning a new distribution over outcomes. We perturbed the covariates and watched the outcome distribution move. This move is how we will intervene on a statistical model and impute counterfactuals.

Collectively these operations are best treated as parts of an iterative Bayesian workflow. Rather than a one-shot fit and predict, we want to specify, check implications, fit, diagnose, revise, and then predict6. The prior predictive and posterior sampling are an integral part of model-checking and validation. Visual diagnostics are central to this loop (Gabry et al. 2019), and convergence checks such as rank-normalised \(\hat R\) and effective sample size should be routine gates before interpretation (Vehtari et al. 2021).

1.8 From statistical to causal claims

In this chapter we have implicitly adopted a naive statistical perspective on the modelling process. We described a proxy for the relationship of interest in \(\beta_{1}\) and argued that the linear structure is a reasonable approximation to the true data generating process. We then used the data to learn about the likely values of \(\beta_{1}\) under this model.

In causal inference we need to be more precise. Our estimand (the thing we care about) is the average treatment effect (ATE) of an extra hour of study on exam scores. The models we have fit are prediction engines that can be used to compute this estimand, but they do not automatically give us a causal interpretation. We need to make additional assumptions about the data generating process to interpret these quantities as a causal effect. The conditions for causal identification are not guaranteed just because the model is statistically well-specified and fits the data. To make a causal claim we need to account for risks of confounding, selection bias, and other threats to validity.

For example, you can imagine that students who study more might also differ in other ways that affect their exam scores, such as motivation, access to resources, or prior knowledge. These “omitted variables” threaten the validity of causal conclusions from simple statistical models. If we don’t account for these confounders, the hours-coefficient \(\beta_{1}\) might capture not just the effect of study time but also the influence of these other factors.

Warning⚙️ Necessary but not sufficient

We are not teaching regression for its own sake. We need predictive models so that, once identification assumptions hold, we can compute causal estimands by averaging model-based predictions under hypothetical interventions. We need to understand how to fit models that capture the relationships in the data, but we also need to understand what assumptions are required to interpret those relationships causally. Statistical identification is a necessary but not sufficient condition for causal identification.

1.8.1 What would mandate a causal interpretation?

When can we interpret the hours coefficient causally, as the average treatment effect (ATE) of studying one more hour on exam scores? The cleanest case of causal inference is underwritten by randomisation: random assignment of treatment breaks the link between treatment and all other causes of the outcome, so differences in outcomes can be attributed to the treatment rather than to pre-existing differences. When we have a fitted probabilistic model we can ask how would outcomes change if we intervened on the data generating process and changed the treatment covariate (holding all else fixed) before sampling the posterior predictive distribution. But prediction under counterfactual treatment regimes is not guaranteed to be a reliable guide to future interventions.

In observational studies, we need an “as-if random” story. This means that once we condition on the right covariates, the remaining variation in the treatment behaves like random assignment. In other words: among people who are similar on those covariates, treatment differences are not systematically tied to unmeasured factors that also affect the outcome. For example, if we condition on ability, we are assuming that students with the same ability who study more versus less do not differ in other unmeasured ways (like motivation or support) that also move exam scores. This is a strong assumption, and it can fail if important confounders are missing. We must build our models with appropriate care to avoid this kind of confounding that corrupts the causal claim the model can support. If we do this well then Bayesian statistical inference is a powerful aid to causal inference.

1.9 Conclusion

This chapter established the statistical scaffolding for the rest of the book. Here we fit the same linear model three ways: by optimisation with statsmodels, by sampling with Bambi, and as a full probabilistic specification in PyMC for Bayesian inference with MCMC. The escalation from formula-based to programmatic modelling was deliberate: causal models often require structural flexibility that only a PPL can provide. The flexibility of probabilistic modelling for (a) learning from data and (b) lego-block style expansion gives us the breadth of applications that Gigerenzer calls the Empire of Chance.

The ability to update on data and shift a prior distribution to the posterior is not yet the right to describe that implied shift as a causal effect. We saw that the data alone cannot certify \(\beta_1\) as the effect of an intervention. To bridge that gap, we need identification assumptions that justify interpreting the coefficient as a causal effect: assumptions about what variables to condition on, what might be unmeasured, and whether treatment assignment is effectively random given the conditioning set. To make a statistical model sufficiently robust to support a causal claim, we must know what evidence the claim requires.

Statistical models can be criticised for hidden assumptions, misspecification or misapplication.7 Formalised as a PyMC model our model becomes a transparent executable programme. Richard Hamming observed that the effectiveness of mathematics depends on recognising an analogy between parts of a problem and a mathematical structure, and that the analogy must be both extensive and accurate for the mathematics to predict well (Hamming 2020). A fitted regression is precisely such an analogy: a mathematical consequence relation mapped onto a worldly process. But causal inference demands that the analogy go deeper. It is not enough for the model to describe the data; the model must also faithfully represent what would happen under intervention. The next chapters formalize the “as-if random” logic with DAGs and show how to choose covariates for adjustment strategies that support an intervention interpretation.

Note📚 Further reading
  • James V. Stone’s Bayes’ Rule: A Tutorial Introduction to Bayesian Analysis is the most tutorial and technically direct companion (Stone 2013).
  • Sharon Bertsch McGrayne’s The Theory That Would Not Die and Tom Chivers’s Everything Is Predictable offer accessible historical and narrative accounts of Bayesian ideas and applications (McGrayne 2011; Chivers 2024).
  • Aubrey Clayton’s Bernoulli’s Fallacy gives a more critical account of statistical reasoning and argues for incorporating prior knowledge (Clayton 2021).

  1. See Ashworth et al. (2021) for further discussion of how credibility requires a faithful mapping of statistical proxies to real-world propensities.↩︎

  2. See Jaynes and Bretthorst (2003) for an alternative more detailed discussion of how to motivate the Bayesian approach as a species of logical inference↩︎

  3. The theorem is due to de Finetti (1937); an English translation appears in Kyburg and Smokler’s Studies in Subjective Probability (1964).↩︎

  4. See Mayo (2018) for more discussion.↩︎

  5. In Chapter 3 we’ll discuss the idea of how a theoretical DAG graph underwrites these kinds of computational graph. The computational graph factorises the joint distribution into a Bayesian conditional model. Thinking through possible DAG structures helps us figure out which computational graph we want to execute.↩︎

  6. See both Gelman et al. (2020) and Gelman et al. (2026)↩︎

  7. See Freedman (2009) for a review of misapplied statistical models which obscure implausibility behind inappropriate mathematics.↩︎