from bayesian_causal_infer.plotting import book_showfrom bayesian_causal_infer.plotting import disable_constrained_layoutimport pandas as pdimport numpy as npimport statsmodels.formula.api as smffrom stargazer.stargazer import Stargazerimport arviz as azfrom matplotlib import pyplot as pltimport matplotlib.lines as mlinesimport matplotlib.patches as mpatchesfrom matplotlib.ticker import MaxNLocatorfrom IPython.display import display, Markdownimport warningsimport causalpy as cpimport seaborn as snsimport pymc as pmimport pymc.dims as pmdimport bambi as bmbimport pytensorfrom pathlib import PathSEED =sum(map(ord, "propensity-scores"))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_content_height, book_figsize, forest_axes, style_library_figure,)warnings.filterwarnings("ignore", category=UserWarning)warnings.filterwarnings("ignore", category=RuntimeWarning)warnings.filterwarnings("ignore", category=FutureWarning)pd.options.mode.chained_assignment =None# default='warn'apply_book_style()
Elections, the saying goes, are decided by the people who show up. Which votes get counted and what counts as evidence are analogous problems. In both cases selection criteria are contentious. Decisions about who is sampled, who receives treatment, and what is actually recorded will shape the evidence we later analyze. Once the data are in hand, there is a myriad of other problems the analyst faces too. No insistence that the sample was “representative” will resolve issues of irreducible uncertainty, cohort imbalance, or missing data. Causal inference grapples with both sides of this issue. The most important considerations in causal modelling come down to what counts as evidence and when.
Should statistical inference depend only on observed data, or must it also account explicitly for the mechanisms that produced the observations? When the aim is to estimate a particular effect, how much weight should be placed on design decisions (made before data collection), and how much on patterns discovered after? How much does the provenance of the information matter? Incorporating information about how data were generated can improve estimates dramatically, or it can destabilise them. The more faithfully you try to account for the structure of the data-generating process, the more sensitive your conclusions can become to observations at the margins. This is not a reason to ignore such considerations, but it is a reason to think carefully about how they should enter the analysis.
Important🗺 Chapter overview
What We’ll Cover
Selection risk as the core threat: when the mechanism that determines who receives treatment is systematically related to potential outcomes
Survey sampling as the revealing analogy: how the choice of which units to include (which elephants to weigh) mirrors the selection problem in causal inference
The Horvitz-Thompson estimator, stratification, and the value of auxiliary information for correcting selection-induced bias
Why a pure likelihood approach fails when overlap is poor: a Bayesian imputation model diagnoses the information gap before propensity scores resolve it
Propensity scores as a model of the selection mechanism, and the challenge of extreme weights when selection is severe
Combining regression adjustment with propensity weighting for more robust effect estimates
Learning Objectives
Understand selection into treatment as a threat to causal identification, and how modelling the selection mechanism addresses it
Distinguish design-based from model-based inference and their respective assumptions
Estimate and evaluate propensity scores, including diagnosing extreme weight problems
Assess covariate balance and understand what it means for identification
Combine propensity score methods with regression (as a covariate, as strata, and through trimming) for more robust effect estimates
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.
Exchangeability and de Finetti’s representation theorem from Chapter 1
Difficulty: Intermediate–Advanced. Draws on survey-sampling theory (Horvitz–Thompson, Hájek variance estimators and weighting schemes) and the likelihood-principle debate, and uses a bivariate potential-outcomes model with masked (missing) data.
We will indirectly explore the idea of selection mechanisms in causal inference by starting with a simpler problem: weighing a herd of elephants from a sample. Then we turn to the more complex problem of selection into treatment for a policy intervention. In this way we motivate the importance of sampling design to propensity modelling. We’ll see how a naive model, that ignores the selection mechanism, can be badly biased when the model likelihood accounts for insufficient information. Propensity scores will serve as a diagnostic tool for assessing when the information content of the data supports credible inference.
5.1 Weighing sampled elephants
We begin with a herd of 50 elephants, made up of 25 cows and 25 bulls. For each animal we know its true WEIGHT, but we also possess an auxiliary variable, EYEBALL_ESTIMATE, representing a subjective assessment of each animal’s size. Imagine the circus owner who wants to estimate the total weight of all these elephants. It’s an arduous task to manually weigh 50 elephants, so we must sample the data and infer the total weight. We’ll use different kinds of information to improve our odds of a correct answer: (1) facts of the animals themselves, and (2) facts about how we sample them to distill various estimates of the total weight of the herd.
This is a pedagogical dataset drawn from Brewer’s Combined Survey Sampling Inference which allows us to draw samples from a fully known population, providing a clear basis for comparing the performance of competing inferential frameworks.1 The circus owner comes from a thought experiment by the statistician D. Basu. Faced with fifty elephants and the unappealing task of weighing them all, the owner seeks to estimate their total weight from a sample.
df_basu.head()
CATEGORY
WEIGHT
SELECTION_ID
EYEBALL_ESTIMATE
0
COW
3567
1
1.20
1
COW
3270
4
1.10
2
COW
2971
6
1.00
3
COW
3028
7
1.00
4
COW
2588
10
0.85
Here we can see the true elephants weight and a corresponding eyeball estimate for each of the elephants. But in practice we would only have a sample of the elephants weights and need to make an inference to the total weight. We consider now how to derive estimates for the total weight given a particular sample.
5.2 Design thinking: how to weigh the elephants
When we talk about “design-based” inference, we’re focusing on how a sample is drawn. In this approach the population parameter values themselves are treated as a set of fixed (albeit unknown) constants. The key idea is that if we know the rules by which an elephant could have been selected we can define an estimation routine informed by those rules. The statistical properties of such an estimator e.g. its bias and variance, are determined by averages taken over the set of all possible samples that the design could have generated.
Note📖 Design-unbiased estimation
An estimator is design-unbiased when its expected value, averaged over all samples the design could have generated, equals the true population quantity. The bias and variance of the estimator are properties of the sampling procedure, not of any assumed distribution over the population values. Design-based inference rests on exactly this randomisation in the sampling scheme. This is the warrant for the statistical estimate.
The properties of random sampling schemes are well known and have desirable features like unbiasedness and efficiency. But these guarantees depend on how the sample is drawn.
5.2.1 Simple random sampling without replacement
We begin with the most elementary design: Simple Random Sampling Without Replacement (SRSWOR). This scheme ensures that every possible sample of a given size n has an equal probability of being selected from the population of size N. This means each elephant has the same probability of being included. No animal is favoured or ignored. Let us suppose that this procedure was used to draw the following sample of n=5 elephants.
With the sample in hand, we can now construct an estimate for the population total. Under a simple random sampling (SRS) design, the sample mean is an unbiased estimator of the true population mean.
The most straightforward and logical way to estimate the population total is therefore to scale this sample mean by the known population size, N. This yields the expansion estimator for the total which is a specific instance of the more general Horvitz-Thompson estimator. Implicitly, this HT weighting uses the equal inclusion probabilities that define the SRS procedure. We will see this below, but first consider the expansion estimate:
Our estimator’s properties (like bias and variance) depend on the sampling design, not any assumptions about the distribution of weights. This estimator is design-unbiased. Its properties are derived from the fact that, on average, over all possible simple random samples, the estimate will equal the true population total. The code below first calculates the sample statistics and then applies this formula to produce a point estimate of the total weight for all 50 elephants.
## Total Weight Estimatetotal_weight_est = aggs.loc["mean"]["WEIGHT"] *len(df_basu)total_weight_est
np.float64(214719.99999999997)
Next we want to move from the estimate of the total to estimating sampling variance of the total weight estimator.
5.2.1.1 Estimating variance
This step carries a real cost. In the Bayesian models that occupy the rest of this book, uncertainty is a by-product of inference: once we have a posterior, the variance of any quantity we care about comes essentially for free, by sampling it. Design-based inference has no posterior to draw on. Its uncertainty must be assembled by hand, from the structure of the sampling scheme itself. To do this we first need to manually calculate the estimated contribution of that sampled unit to the total.
For each sampled unit, we compare its implied total contribution against the overall total estimate and square the differences to gauge variances. We then need to combine these individual measures and correct for the usage of the sample Mean to get at the population variance. This quantity is then scaled to the sample size and used to calculate a corrected variance for the total estimate.
Our expected total is too high, but the variance properly accounts for this, as the true value falls well within the uncertainty bounds. The key feature is that equal inclusion probabilities make this estimator design-unbiased. But equal chance is a strong requirement. Maybe some elephants are more docile or compliant than others, and so are more likely to be sampled. Maybe some are more aggressive or elusive, and so are less likely to be sampled. If the inclusion probabilities are unequal, the estimates inherit this fact.
Consider what happens if we allowed sampling with replacement (where the same elephant might be selected twice) the composition of our sample would become less representative of the true population. A sample inflated by repeated individuals is more homogeneous than the herd it purports to describe. The variance estimate would then be too small, generating false confidence that the uncertainty bounds capture the true total when they do not. Who is included, and on what terms, shapes both the point estimate and our sense of its reliability.
5.3 Explosive weights with the Horvitz-Thompson estimator
The Horvitz-Thompson (HT) estimator generalises SRS to any probability sampling design. Each sampled observation is weighted by the inverse of its inclusion probability \(\frac{1}{\pi}\). An elephant with a small chance of selection stands in for many; one with a high chance stands in for few. What matters is not equal chance, but known chance. As long as every \(\pi_{i}\) is positive and known, the estimator is design-unbiased in the sense defined above. The function below encodes this principle. The subtleties lie in the variance, where different sampling designs induce different forms of dependence.
def ht_total_and_variance(y, pi, design="SRS", N=None, strata=None): y = np.asarray(y) pi = np.asarray(pi) y_pi = y / pi ht_total = np.sum(y_pi) n =len(y)if design =="Poisson": ht_var = np.sum((1- pi) * (y / pi) **2)elif design =="SRS": f = n / N s2 = np.var(y, ddof=1) ht_var = N**2* (1- f) * s2 / nelif design =="Hajek":# unstratified by default; pass `strata` as array of labels for stratifiedif strata isNone: c =1- pi B = np.sum(c * y_pi) / np.sum(c) ht_var = n / (n -1) * np.sum(c * (y_pi - B) **2)else: ht_var =0.0for g in np.unique(strata): idx = strata == g n_g = idx.sum() c =1- pi[idx] B = np.sum(c * y_pi[idx]) / np.sum(c) ht_var += n_g / (n_g -1) * np.sum(c * (y_pi[idx] - B) **2)else:raiseValueError("Design not recognized. Use 'SRS', 'Poisson', 'Hajek'.")return ht_total, ht_var
The inclusion probabilities encode selective weighting of evidence. The function implements three variance formulas for the same HT total. Under SRS, the fixed sample size allows a finite-population correction. Under Poisson sampling, each unit is selected independently, so variance decomposes into a sum over individual probabilities. This decomposition is unstable when any \(\pi_{i}\) is small. The Hájek approximation stabilises variance by centring around a weighted mean, trading strict unbiasedness for lower variance. In practice, the stabilisation is usually worth it.
n = sample_df.shape[0]y = sample_df["WEIGHT"].values# Example: equal probability for SRS approximationpi = np.array([n /len(df_basu)] * n)ht_total, ht_var = ht_total_and_variance(y, pi, design="SRS", N=len(df_basu))ht_total, np.sqrt(ht_var)
The equal-probability case reproduces our earlier SRS estimate, confirming that SRS is a special case of HT.
5.3.1 Comparing variance calculations
One of the elegant but treacherous features of the Horvitz–Thompson estimator is how it handles inclusion probabilities that are very small or very large. The mathematics guarantees unbiasedness in the SRS case. Every unit, no matter how rarely sampled, contributes its proper share when weighted by \(1/\pi_i\). But unbiasedness does not mean stability. When \(\pi_i\) is small, the corresponding weight \(1/\pi_i\) is large, and a single observation can dominate the estimate. The variance formulas in the table capture that risk directly: the squared weights amplify noise, leading to wide standard errors.
First let’s examine how the estimators perform under uniform probabilities of inclusion.
Here we compute Horvitz–Thompson totals and variances under three design assumptions (Poisson, Hájek, SRS), then display them alongside their textbook formulas. By holding the data constant and changing only the inclusion probabilities, we see how design assumptions and sampling probabilities interact.
This result, with uniform probabilities, mimics simple random sampling. The totals across designs align closely, and the variances are modest because no single unit is unduly influential. Under equal probabilities the Hájek approximation reproduces the SRS variance exactly. While the Poisson estimator inflates the variance, it does encompass the true value. Let’s see how results change if we have extreme inclusion probabilities.
5.3.2 Exploding the point estimate
Basu’s original parable turns on exactly this scenario: one animal sampled with a vanishingly small chance of selection. Suppose the same five elephants are drawn again, but now with inclusion probabilities of [0.8, 0.1, 0.02, 0.1, 0.1]. One of the bulls, weighing 4,459 in our sample, had only a 2% chance of being included.
The consequence is almost comic. Scaled up by that 2% chance, this one bull alone now outweighs the true weight of the entire herd. So under the adjusted inclusion probabilities, the HT total climbs from around 214,720 under uniform sampling to 366,725 here, an estimate 89% above the truth, driven almost entirely by a single unit’s inverse-probability weight. This is unbiasedness working exactly as advertised and being no comfort at all. The guarantee holds on average, over repeated samples, not for the one sample in front of us.
Extreme probabilities don’t just distort the point estimate; they corrupt our sense of its reliability too. Small \(\pi_{i}\) values inflate weights and variance; large ones anchor the estimate to a few over-represented units. The SRS formula, blind to this imbalance, is confidently wrong, as its standard error does not move even as the point estimate blows up. Poisson and Hájek formulas are wrong too, but honestly so, their standard errors widening to reflect the added uncertainty. The remedy is to bring in more information! Either refine the estimate through stratification (structuring the design) or through auxiliary variables (structuring the model).
5.4 Leveraging stratification and supplementary information
The Horvitz–Thompson estimator is unbiased but often volatile; the Hájek modification is more stable but approximate. When applied to the same data, they can yield noticeably different estimates of the variance in our total. How can we resolve this seeming contrast?
Neither estimator makes use of available supplementary information. If we know more about the population than just the study design, we can exploit that structure to improve efficiency. The ratio estimator is the canonical example. Instead of relying solely on design information to drive inference, we use the known total of an auxiliary variable that tracks with our outcome of interest.
The estimator deploys an auxiliary variable \(X_{i}\), correlated with \(Y_{i}\) and whose population total is known, to stabilize the estimate. The \(i\) index ranges over the entire herd, and the \(s\) index just ranges over the sample of weighed elephants. Applying the formula shrinks our estimate toward the true total.
The ratio of sample totals \((\hat{Y}_s / \hat{X}_s)\) provides a calibrated slope, which we then project onto the known population total of \(X\). In practice, this shrinks the variance dramatically when \(X\) and \(Y\) move together. The Python code above illustrates exactly this: using “eyeball estimates” of animal weights as an auxiliary variable, the ratio estimator refines the population weight total. We leverage the information from the observed eyeball estimates to infer properties of the unobserved total WEIGHT.
5.4.1 Rescue by stratification
Stratification is a complementary idea that also attempts to incorporate other information. Rather than treating the population as one undifferentiated mass, we divide it into groups. Here, we have cows and bull elephants. The following code computes separate ratio estimates for cows and for bulls, then aggregates them. This “stratified ratio” estimator blends the benefits of auxiliary information (through the eyeball estimates) with the variance reduction of stratification.
First we look at the Cows.
n_cows = sample_df[sample_df["CATEGORY"] =="COW"].shape[0]y_hat_cow = sample_df[sample_df["CATEGORY"] =="COW"]["WEIGHT"].sum() / n_cowsx_hat_cow = sample_df[sample_df["CATEGORY"] =="COW"]["EYEBALL_ESTIMATE"].sum() / n_cowsx_cow = df_basu[df_basu["CATEGORY"] =="COW"]["EYEBALL_ESTIMATE"].sum()ratio_cow_est = (y_hat_cow / x_hat_cow) * x_cowprint("Ratio Estimate of Total in the Sample of Cows:", ratio_cow_est)
Ratio Estimate of Total in the Sample of Cows: 76023.41463414635
Next, at the Bulls
n_bulls = sample_df[sample_df["CATEGORY"] !="COW"].shape[0]y_hat_bull = sample_df[sample_df["CATEGORY"] !="COW"]["WEIGHT"].sum() / n_bullsx_hat_bull = sample_df[sample_df["CATEGORY"] !="COW"]["EYEBALL_ESTIMATE"].sum() / n_bullsx_bull = df_basu[df_basu["CATEGORY"] !="COW"]["EYEBALL_ESTIMATE"].sum()ratio_bull_est = (y_hat_bull / x_hat_bull) * x_bullprint("Ratio Estimate of Total in Sample of Bulls:", ratio_bull_est)
Ratio Estimate of Total in Sample of Bulls: 118364.19047619047
Now we combine both estimates, which gives an almost perfect match to true total.
print("Combined Stratified Estimates to give Estimate of Total:", ratio_cow_est + ratio_bull_est,)
Combined Stratified Estimates to give Estimate of Total: 194387.60511033682
These two observations can be combined into an across stratum ratio estimator, but at this point we should just note that ratio estimation can be reinterpreted as a regression without an intercept. Regressing \(Y\) (true weight) on \(X\) (eyeball estimate) forces the fitted line through the origin. If the noise variance grows in proportion to \(X\), the weighted least-squares slope is exactly the ratio adjustment; ordinary least squares gives a close but slightly different slope. Once phrased this way, a broader vista opens up. Why stop at a single auxiliary variable? Why not combine categorical structure (cow vs. bull) with continuous predictors (eyeball estimates)? Why not allow an intercept? The more relevant information we bring to bear, whether from sampling design or auxiliary variables or stratification, the better.
5.5 Model thinking: putting the pieces back together
We can see this progression as a way to specify increasingly sophisticated model-based estimation routines.
Category-only models: WEIGHT ~ C(CATEGORY) treats cows and bulls as distinct subpopulations, akin to stratification.
Auxiliary-only models: WEIGHT ~ EYEBALL_ESTIMATE mirrors the classical ratio estimator.
Combined models: WEIGHT ~ C(CATEGORY) + EYEBALL_ESTIMATE blends the two strategies, much like stratified ratio estimation.
By fitting these regressions to the sample and then predicting over the full population, we obtain alternative estimates of the population total, along with measures of prediction variance. This bridges the design-based and model-based traditions in survey inference: one rooted in inclusion probabilities, the other in statistical modeling. Model thinking is about seeing the story in the generative process that links the variables. By accounting for categorical differences and levels on a continuous score we seek to establish the premise of conditional exchangeability discussed in Chapter 1, which we develop formally below. The variables we seek to include in our model are proffered as an adequate conditional set to license probabilistic conclusions.
Tip🔍 The ratio estimator is a regression model
The Ratio estimate is implicitly a regression model. This can be seen if we compare the structure of the equation.
The two coincide when \(\beta\) is estimated by weighted least squares with variance proportional to \(X\), which gives \(\hat{\beta} = \sum_{s} Y_{s} / \sum_{s} X_{s}\). Ordinary least squares gives \(\hat{\beta} = \sum_{s} X_{s}Y_{s} / \sum_{s} X_{s}^{2}\) instead, which is why the no-intercept regression below lands close to, but not exactly on, the ratio estimate.
This raises a natural question: how much further might we get if we further augment our estimators with extra information?
Below we report a number of simple regression models which aim to compare and assess the variation in the elephant’s weight while controlling for aspects of gender and auxiliary information in the form of the owner’s eyeball estimate of relative weight.
The parameter estimates on each of the covariates tell us something of the influence of these predictors. In a sense the parameter estimates tell us everything we’ve learned from the data. A regression model of this format conditions on the observed data to learn latent parameters \(\beta\). If we assume a normal likelihood then we have:
This formulation seems to ignore all aspects of sampling design. Instead, we’ve imposed a functional relationship between \(X, Y\) and once we’ve learned the expected realisation of the function we’ve arguably accounted for the relevant variances in our outcome. Consequently, we can pull out the predictions for each individual based on our modelling. This allows us to sum the predicted weights to gauge the variance of the total.
Predicted Total
SE of Total
Model
204600
13909.8
WEIGHT ~ 1 + C(CATEGORY)
203080
29182.3
WEIGHT ~ 1 + EYEBALL_ESTIMATE
195493
1182.41
WEIGHT ~ 1 + C(CATEGORY) + EYEBALL_ESTIMATE
204600
13909.8
WEIGHT ~ 0 + C(CATEGORY)
205517
22334.2
WEIGHT ~ 0 + EYEBALL_ESTIMATE
195493
1182.41
WEIGHT ~ 0 + C(CATEGORY) + EYEBALL_ESTIMATE
The category models produce the same population total with and without an intercept, because 0 + C(CATEGORY) only reparameterises the two group means. The fact that regression models with and without intercepts produce the ery similar population totals here illustrates an important point. At the level of design-based inference, intercepts often vanish once predictions are aggregated to population margins. What matters are the auxiliary variables and how they calibrate the sample to the population. In this sense, ratio and regression estimators are not only philosophically close, but they can also be numerically close.
When we have sufficient information to characterise the process via substantive predictors, the role of the intercept shrinks because it has less unexplained variation to absorb. Notice, too, what the model gave us: a variance for the total, computed from the covariance of the fitted coefficients, with none of the hand-construction the design-based route demanded. The modelling approach to inference uses the information available and creates an incentive to find more. Every useful auxiliary variable is both a statistical tool and a claim about the data generating process itself.
5.6 From sampling design to causal design
Now we pivot from sampling design to causal inference. The analogies are precise. Inclusion probabilities become propensity scores and population totals become treatment effects, but the inferential logic is the same. Design information and model information serve different purposes: the first diagnoses who are in the sample and on what terms; the second extracts the signal from what was observed. The question is how they should be combined. The Horvitz-Thompson estimator proved to be brittle when \(\pi_{i}\) was extreme, but is this a real problem? We now turn to modelling the problem more directly.
The instability of the design-based estimation has led some proponents of Bayesian inference to suggest that there is an illegitimacy to inferences made from such ad-hoc design recipes. This culminates in the likelihood principle which states that everything there is to be learned from a particular sample is to be derived from the likelihood. Here we quote a formulation of the likelihood principle from L.J. Savage
“According to Bayes’s Theorem \(p(X | \theta)\)… constitutes the entire evidence of the experiment, that is it tells all that the experiment has to tell. More fully and more precisely, if \(Y\) is the datum of some other experiment, and if it happens that \(p(X | \theta)\) and \((Y | \theta)\) are proportional functions of \(\theta\) (that is constant multiples of each other) then each of the two data \(X\) and \(Y\) have exactly the same thing to say about the value of \(\theta\)” - Savage in The Foundations of Statistics p17
This is a contentious principle, despite claims that it is in fact a theorem. Taken to an extreme the view implies that Horvitz Thompson style estimators are illegitimate. Rather than helping they are deemed to hinder inference in that they corrupt what can be learned from the sample by “arbitrary” weightings. We won’t dwell on the philosophy here, only to highlight that this theoretical dispute has practical consequences when we need to apply our inferential machinery.2 This problem becomes particularly acute in causal inference.
5.7 Causal inference as a design problem
We saw in Chapter 2, how causal inference requires recognising which arrangement of facts warrant causal conclusions. A causal claim is never won from data by formal manipulation alone; it requires that the facts be structured through design, selection, or adjustment so that the observed association cannot plausibly be attributed to anything other than the mechanism of interest.
The Platonic ideal for causal inference is a perfectly random allocation of treatment status in the sample. In this framing causal inference can be seen as a special case of survey design.3 The unbiased allocation of treatment status is an evidentiary demand. We want to ensure that the study population is split as-if arbitrarily into treatment and control groups. Within such a sampling regime we would hope to have even splits across these cohorts mitigating the risk of selection-bias contaminating our inferred treatment effects. With this limiting case in mind, it becomes quite natural to ask about the design attributes of any causal inference study.
We cannot dogmatically insist that there is nothing to be learned except from the likelihood. The likelihood is often subtly misspecified and yields only a crude approximation of the outcome data. The probabilities of inclusion latent in any observed data will serve as a diagnostic sense-check on how close our sample data is to the Platonic ideal. When these inclusion probabilities are estimated they are referred to as propensity scores. Their diagnostic power alone is a sufficient reason for the central role of the propensity score in causal inference (Rosenbaum and Rubin (1983)). Propensity scores have a real evidentiary role we would be foolish to ignore.
5.8 The paradox of the propensity score
And yet, there is a paradox when we consider the role of the propensity scores in Bayesian inferences. Write the propensity score as \(e(X) = p(T \mid X)\) and let \(\theta_Y\) parameterise the outcome model and \(\theta_T\) parameterise the assignment model. The likelihood of the observed treatment and outcome then factorises as
Suppose treatment assignment T is independent of the potential outcomes \(Y(0), Y(1)\) given \(X\) and the two parameter blocks are distinct, in the sense that they are a priori independent, \(p(\theta_Y, \theta_T) = p(\theta_Y)\,p(\theta_T)\). Then the posterior for the outcome parameters \(\theta_Y\) is
The assignment factor does not involve \(\theta_Y\), so it is constant in \(\theta_Y\) and drops out of the normalised posterior. The propensity score “cancels” in exactly this sense: under exchangeability and distinct parameters, inference about the causal effect does not depend on the propensity model at all. The assignment mechanism is, in Rubin’s terms, ignorable(Rosenbaum and Rubin 1983). Estimating the joint distribution pushes us to focus on the likelihood of \(Y\) and to leave aside “extraneous” information about the sampling design.
However, this cancellation rests entirely on its two premises, and that is what obscures why propensity scores remain valuable in practice. Even granting ignorability, the cancellation only helps when the outcome model \(p(Y \mid T, X, \theta_Y)\) is correctly specified and the parameter blocks are genuinely distinct. When our outcome model is misspecified (which is nearly always), or when the two models share structure, the propensity score stops being ancillary and becomes a separate source of information about the assignment mechanism. This risk of misspecification is worst exactly where overlap is poor, in regions of the propensity score distribution with few or no comparable units. There is insufficient data to check whether the outcome model’s functional form still holds. By modeling \(e(X)\) independently, we can check covariate balance, diagnose overlap violations, and, in principle, construct doubly-robust estimators that remain consistent if either the outcome model or the propensity model is correct. The propensity score doesn’t add information beyond a correctly specified likelihood; rather, it helps us identify the correct likelihood to use.
Let’s now move beyond this seeming paradox by working to see how propensity score methods are useful in an applied context.
5.9 Diagnosing imbalance in the LaLonde data
We’ll look at a famous LaLonde (1986) dataset.4 LaLonde studied the effect of a job training program (the National Supported Work Demonstration, NSW) on participants’ earnings. Our variant of the dataset refers to the Current Population Survey (CPS) comparison sample matched to NSW trainees, with covariates and outcomes as above. This CPS sample is much larger and observational (non-randomised), and as such will highlight the role of design considerations for causal inference.
This data set is (in)famous in causal inference literature because in the original study LaLonde was able to impose a truly randomised design and derive a benchmark estimate for the true treatment effect of this programme. There was an expected gain of $1794 resulting from participation in the programme. In our data set the treatment indicator is not randomised, and we’ll see how that impacts our ability to infer plausible treatment effects.
Description
Mean
Std
Variable
treat
Treatment indicator (1 = NSW, 0 = CPS)
0.01
0.11
age
Age in years (at baseline)
33.14
11.04
educ
Years of education
12.01
2.87
black
Indicator (1 = Black, 0 otherwise)
0.08
0.27
hispan
Indicator (1 = Hispanic, 0 otherwise)
0.07
0.26
married
Indicator (1 = Married, 0 otherwise)
0.71
0.46
nodegree
Indicator (1 = No high school degree)
0.30
0.46
re74
Real earnings in 1974 (pre-treatment, in 1978 USD)
13887.72
9622.15
re75
Real earnings in 1975 (pre-treatment, in 1978 USD)
13504.04
9302.83
re78
Real earnings in 1978 (post-treatment, in 1978 USD)
14758.36
9681.12
Let’s inspect how our outcome re78 varies across strata. The code below compares treated and untreated outcomes within each stratum. Stable, consistent differences would suggest the dataset approximates a randomised controlled trial (RCT). The fact that differences vary a lot in LaLonde’s CPS sample demonstrates how far it is from a randomised treatment assignment, and why propensity score methods are applied to reduce this imbalance.
The summary statistics from these strata suggest strongly negative effects.
Mean Values: treat
untreated 11541.28
treated 6981.22
diff -4024.94
dtype: float64
---------------------------------------
Percentage of Strata Missing a Treatment: 0.68
However, the first thing to note is that there are a lot of strata where the causal contrast of interest isn’t even defined i.e. there are strata where one of the treatment groups has no realised values within that stratum. Any model fitted to this data set must impute those missing contrasts from other strata rather than observe them. This is not reflective of fair allocation and can lead to bias. We’ll visualise this next.
Code
def make_strata_plot(df): strata_df = ( df .groupby(["educ", "black", "hispan", "married", "treat"])[["re78"]] .agg(["count", "mean"]) .rename({"age": "count"}, axis=1) ) global_avg = df["re78"].mean() strata_df["global_avg"] = global_avg strata_df["diff"] = strata_df[("re78", "mean")] - strata_df["global_avg"] strata_df.reset_index(inplace=True) strata_df.columns = [" ".join(col).strip() for col in strata_df.columns.values] joined_df = strata_df[strata_df["treat"] ==0].merge( strata_df[strata_df["treat"] ==1], on=["educ","black","hispan","married", ], ) joined_df.sort_values("diff_y", inplace=True)# Func to draw line segmentdef newline(p1, p2, color="black"): ax = plt.gca() l = mlines.Line2D([p1[0], p2[0]], [p1[1], p2[1]], color="black", linestyle="--") ax.add_line(l)return l fig, ax = plt.subplots(figsize=book_figsize(preset="tall")) ax.scatter( joined_df["diff_x"], joined_df.index, color="gold", alpha=0.7, label="Control Sample Size", s=joined_df["re78 count_x"] *2, ) ax.scatter( joined_df["diff_y"], joined_df.index, color="blue", alpha=0.7, label="Treatment Sample Size", s=joined_df["re78 count_y"] *2, )for i, p1, p2 inzip(joined_df.index, joined_df["diff_x"], joined_df["diff_y"]): newline([p1, i], [p2, i]) ax.set_xlabel("Difference from the Global Mean") ax.set_title("Differences from Global Mean \n by Treatment Status and Strata", fontweight="bold", ) ax.axvline(0, color="k") ax.set_ylabel("Strata Index") ax.legend( loc="lower right", markerscale=0.4, frameon=True, edgecolor="black", fancybox=False, framealpha=1, )return fig
Many of the dashed lines connecting the treated and untreated outcomes are long, reflecting sizable within-stratum imbalances. Moreover, the differences do not cluster around a common treatment effect. Instead, some strata show treated individuals earning much more than controls, while others show the opposite, with no clear or consistent pattern emerging. We’re only showing the strata which have a defined contrast, the majority of strata do not have a well-defined causal contrast.
What this visualization demonstrates is just how far the observational dataset is from the limiting condition of random assignment. It highlights both the magnitude and the heterogeneity of imbalance across strata, making visible where treated and control groups are not comparable. The bubble sizes add further context by weighting the importance of each stratum: large imbalances in larger strata are especially concerning because they contribute disproportionately to bias in overall estimates. We have a strata-level diagnostic that underscores why this observational dataset cannot be treated as RCT-like without adjustment. The strata plot suggests the imbalance matters: we cannot hold a fair election by counting only the votes of the wealthy, and we cannot derive a credible treatment effect by drawing comparisons only from a skewed subset of the population. What happens if we ignore the treatment allocation altogether and just try and model the outcome to impute potential outcomes? Can we get away with a purely likelihood based approach?
5.10 Imputation with insufficient information
From a Bayesian perspective, causal inference can be viewed as a problem of missing data. For each individual, only one of the two potential outcomes is ever observed. The remaining outcome is not unobservable in principle, but unobserved in fact. Bayesian inference offers a natural way to reason about such missingness by treating counterfactual outcomes as latent variables and integrating over their posterior uncertainty.
In this section, we take this perspective seriously. We set aside explicit modelling of the treatment assignment mechanism and instead focus entirely on the outcome process. Conditional on observed covariates, we specify a joint model for the potential outcomes under treatment and control. The observed outcome for each individual is treated as a partially observed realization of this joint distribution, while the counterfactual outcome is imputed through posterior sampling.
This approach has several appealing features. It provides a direct route to individual-level treatment effects, allows uncertainty to propagate naturally from the imputation of counterfactuals to population-level estimands, and adheres closely to the likelihood principle: inference proceeds entirely through a model for the observed data. In particular, no design-based weights or propensity scores are introduced at this stage. All information enters through the likelihood and the prior.
Concretely, we model the pair of potential outcomes as a bivariate regression on covariates, allowing for correlation between treated and control outcomes at the individual level. For each unit, the observed outcome occupies one component of this bivariate vector, while the other component is missing and inferred from the model. Posterior draws of these latent outcomes yield samples of individual treatment effects, which can then be aggregated to estimate sample-average or conditional average treatment effects.
This formulation represents a clean, internally coherent Bayesian solution to the causal inference problem. At the same time, it places a heavy burden on the outcome model: wherever treated and control units differ systematically in covariate space, the imputation of counterfactual outcomes necessarily relies on extrapolation. In the next sections, we will see how this burden manifests in practice when overlap is limited. Additionally, we’ll see how information about the assignment mechanism can help diagnose and mitigate these failures without abandoning the Bayesian framework.
The design matrix and coefficients use named unit and predictor axes, so the regression contracts over predictor by name. We use a masked multivariate likelihood to handle the missing potential outcomes.
The function above partitions our outcome space into the observed and unobserved (missing) values. We mask the missing values because we want to sample them from the posterior of our next model. We are attempting to learn the potential outcome for each individual.
The Lewandowski-Kurowicka-Joe (LKJ) prior on the correlation between \(Y(1)\) and \(Y(0)\) is noteworthy because it is a cross-world assumption: it says how a unit’s outcome under treatment co-varies with its outcome under control, and no unit ever reveals both. No data can inform it, so the posterior leaves it where the prior put it. The CATE does not depend on it because the marginal potential outcomes are data-informed, but the individual effects, and the spread of the sample average built from them, do depend on the unidentified LKJ prior. It is a concrete, transparent instance of the cross-world commitments we return to in Chapter 9. We’ve implemented the LKJ settings to be weakly informative, but the prior is still a commitment. The model is not fully identified by the data, and that prior is doing work.
Our current focus on this model is about what happens when applied to the LaLonde data. The diagnostics of Bayesian inference imply that we have had a really difficult time sampling the data for the LaLonde case. But even more precisely, the model struggles sampling the outcome space for the treatment group.
This suggests a reading that the causal inference problem for the LaLonde data set is practically ill-advised. There is simply not enough information available about plausible realisations of the treatment outcomes for us to impute values to the counterfactuals we want to assess across the whole population. The sampler’s failure is diagnostic: it reveals that the likelihood contains insufficient information to support the extrapolations this approach demands. This is the g-computation engine of Chapter 2, imputing the missing potential outcomes from a model of their joint distribution, and here it runs out of comparable units to learn from. The propensity score would have warned us of this problem before we attempted inference. This is reflected in the trace plot above, but also our imputed treatment estimates. We’ll unpack why this potential-outcomes model of the LaLonde case fails in the next section; for now, notice that the diagnostic signal itself is informative.
The distribution of imputed outcomes confirms the diagnostic signal from the trace plot: the model cannot separate the treatment and control outcome distributions when overlap is this poor. The expected values under treatment are driven by extrapolation rather than empirical support.
5.11 Imputation with sufficient information
We now turn to a simulated example in which treatment assignment is stochastic, but we have plenty of observed values under both treatment regimes and the true treatment effect is known. The data-generating process ensures that both potential outcomes are well-supported by observed data, even though only one outcome is realised for each individual, just as in the observational setting.
Applying the same Bayesian imputation model in this setting leads to a very different inferential experience. The sampler mixes well, effective sample sizes are healthy, and posterior uncertainty is well-behaved. The model has no difficulty imputing the missing counterfactual outcomes and recovering the underlying treatment effect from the data.
rng_imputation = np.random.default_rng(SEED)df1 = pd.DataFrame({"x1": rng_imputation.normal(0, 1, N),"x2": rng_imputation.normal(0, 1, N),"x3": rng_imputation.normal(0, 1, N),})TREATMENT_EFFECT =2df1["treat"] = rng_imputation.binomial(1, inv_logit(0.5* df1["x1"] + df1["x2"] + df1["x3"]))df1["re78"] = (1+ TREATMENT_EFFECT * df1["treat"]+ df1["x1"]+0.2* df1["x2"]+-3* df1["x3"]+ rng_imputation.normal(0, 1, N))# Standardising the covariates (not treat, not re78) keeps the NUTS geometryX = (df1[["x1", "x2", "x3"]] - df1[["x1", "x2", "x3"]].mean()) / df1[ ["x1", "x2", "x3"]].std()T = df1["treat"]# fitted means back to re78's original units using df1["re78"].std().Y = (df1["re78"] - df1["re78"].mean()) / df1["re78"].std()y_masked = create_y_matrix(Y, T)model_imputed, idata_imputed = make_imputation_model( X, y_masked, target_accept=0.99,)
When we have high information content about the realisations of the outcome variable on each arm of the treatment, the same model has no problem learning to impute the counterfactual values. With imputation, we can derive a non-parametric estimate of the treatment effect. Here we are using the Bayesian model to impute the potential outcomes for each individual.
Figure 5.1: Posterior of the imputation model: the sample average treatment effect (SATE) and the two outcome intercepts.
We can see that we have accurately recovered the treatment effect. This is also reflected in the expected values of the outcome for each treatment group.
What changed between the two cases was not the model, but the availability of information. The same estimation routine, applied to data with genuine overlap, recovers the treatment effect cleanly. Applied to data without it, the sampler exposes the problem: there is simply not enough empirical support for the counterfactual imputations the model requires. The bottleneck was never the sophistication of the estimation; it was the information content of the data.
The lesson this contrast teaches is also a practical one. Before reaching for any adjustment strategy, ask whether the data contain the comparisons needed to support the inference. In the LaLonde case, the answer seems clear. Our counterfactual contrast is only weakly informed by data. What we need is a way to diagnose the information problem before attempting inference: to see, directly, which individuals have realistic counterfactual comparators and which do not. That is precisely what the propensity score provides.
5.12 Estimating and inspecting propensity scores
We can quantify the differences between the observed sample and an RCT-like condition if we first estimate the propensity of treatment. When we talk about estimating propensity scores, we are really asking: given what we know about someone’s baseline characteristics, how likely is it that they would be selected into the treatment group? This probability of treatment assignment, conditional on observed covariates, is the propensity score \(e(X)\). If the data truly came from an RCT, treatment would be assigned independently of these characteristics \(X\), and the estimated propensity would be essentially constant across individuals. In observational data, however, treatment assignment often depends strongly on covariates, and this dependence is precisely what creates imbalance and the need for adjustment. In a DAG format, we can represent the causal structure of the data following Steiner et al. (2017) (Figure 5.2):
Figure 5.2: Propensity score DAGs, following Steiner et al. (2017).
Conditioning on the propensity score aims to cleave the influence of the covariates \(X\) on the treatment assignment. Normally conditioning on a collider \(e(X)\)5 introduces a spurious dependence that obscures causal inference. Here by the definition of the propensity score, we’re isolating and controlling for the (assumed) deterministic influence of \(X\) on \(T\). We absorb the influence of observed covariates into the population propensity score, which then serves as a balancing score. By conditioning on \(e(X)\), we can achieve balance in the distribution of covariates between treated and control groups, thus mitigating or offsetting the confounding bias. Within levels of the propensity score, we argue that the treatment assignment is “as if” random, allowing for well-defined causal contrasts.6
Logistic regression is the most common starting point for estimating propensity scores. We fit a binary regression model where the dependent variable is the treatment indicator (treat = 1 for program participants, 0 otherwise), and the predictors are the observed baseline covariates that could influence selection into treatment. The logistic link is a natural choice because it constrains the predicted probabilities to the [0, 1] range and provides interpretable odds ratios for how each covariate relates to treatment assignment. For example, in the LaLonde data, being unmarried or lacking a high school degree increases the likelihood of being in the training program, while age and education levels also play a role. The logistic regression captures these patterns in a flexible but parsimonious way. In CausalPy this logistic regression model is estimated within the InversePropensityWeighting class.
formulas = ["treat ~ 1 + age + black + married + hispan + nodegree + re74 + re75 + u74 + u75","treat ~ 1 + age + black + married + hispan + nodegree","treat ~ 1 + age + black + married + hispan + nodegree + u75",]def fit_prop_model(formula, sampler_kwargs): result1 = cp.InversePropensityWeighting( df_reg, formula=formula, outcome_variable="re78", weighting_scheme="robust", model=cp.pymc_models.PropensityScore(sample_kwargs=sampler_kwargs), ).fit()return result1result0 = fit_prop_model(formulas[0], sampler_kwargs)result1 = fit_prop_model(formulas[1], sampler_kwargs)result2 = fit_prop_model(formulas[2], sampler_kwargs)
A logistic regression for propensity scores is a means to reweight the data. The point is to estimate, as credibly as we can, the probability that each individual is treated given their observed characteristics. These probabilities, the propensity scores, are intended to be used for balancing weights, but first we want to see how these weights might change under different model specifications.
The code above takes three alternative specifications of the treatment assignment model, ranging from a rich version including pre-treatment earnings and unemployment indicators, to a stripped-down version with only demographic and educational variables, and a middle ground in between. This variety can matter: with observational data, model dependence is real. Small changes in the set of covariates can shift estimated treatment effects substantially, particularly in the LaLonde data, where (as we’ll see) some people have extreme values of the propensity score (very close to 0). Let’s see how the different models attempt to place weight on the different parameters.
Figure 5.3: Propensity score coefficients under the three specifications.
A regression model, even one tucked away inside a weighting scheme, deserves to be inspected. The forest plot in Figure 5.3 displays the estimated coefficients from the three logistic propensity score models we fit earlier. Each dot is a posterior mean, each line an interval of uncertainty. By lining them up side by side, we can see how robust or fragile the story of treatment assignment is.
In the LaLonde data, the model suggests that e.g. being Black or without a high school degree increases the likelihood of entering the training program. But what matters for our purposes is not just whether these effects are positive or negative, but whether the different model specifications (rich, sparse, or intermediate) produce consistent signals. If the sign of a coefficient flips or the interval widens dramatically depending on what covariates are included, that is a warning: the propensity scores, and with them the reweighting exercise, are being driven by modelling choices rather than stable features of the data.
This plot, then, is a diagnostic step. It tells us whether the balancing mechanism we plan to rely on is built on shaky ground. In empirical practice, taking such a look is essential; it prevents us from treating propensity score weights as black-box corrections and reminds us they are as fragile, or as sturdy, as the regression that generated them.
5.12.1 Checking propensity score balance
Code
def make_plot(idata, axs, subset_idx):# Extract posterior samples of propensity scores p_post = az.extract(idata)["p"].values # shape: (n_obs, n_samples)# Compute posterior mean for each individual p_mean = p_post.mean(axis=1)# Separate treated and control units treated_idx = df_reg["treat"] ==1 control_idx = df_reg["treat"] ==0# --- Plot 1: Density plot of posterior mean propensity scores --- sns.kdeplot( p_mean[treated_idx], label="Treated", fill=True, alpha=0.4, color="gold", ax=axs[0] ) axs[0].axvline(np.quantile(p_mean[treated_idx], 0.75), label="p75 Treated", color="k") sns.kdeplot(p_mean[control_idx], label="Control", fill=True, alpha=0.4, ax=axs[0]) axs[0].axvline( np.quantile(p_mean[control_idx], 0.75), label="p75 Control", color="k", linestyle="--", ) axs[0].set_xlabel("Posterior Mean Propensity Score") axs[0].set_ylabel("Density") axs[0].set_title("Propensity Score \n Distributions") axs[0].legend(fontsize=8, frameon=False, loc="upper right")# --- Plot 2: Posterior uncertainty for a subset of individuals ---for i, idx inenumerate(subset_idx): q_low, q_med, q_high = np.percentile(p_post[idx, :], [5, 50, 95]) axs[1].plot([i, i], [q_low, q_high], color="gray", alpha=0.6) # 90% interval axs[1].scatter(i, q_med, color="black", s=10) # median axs[1].set_xlabel("Randomly Selected Units") axs[1].set_ylabel("Posterior Propensity Score") axs[1].set_title("Posterior Uncertainty in \n Individual Propensity Scores")with plt.rc_context( {"font.size": 8,"axes.titlesize": 9,"axes.labelsize": 8,"xtick.labelsize": 7,"ytick.labelsize": 7,"legend.fontsize": 8, }): fig, axs = plt.subplots(2, 3, figsize=(7, 6.0), layout="constrained") axs = axs.flatten() subset_idx = rng.choice(len(df_reg), size=50, replace=False ) # pick 50 units make_plot(result0.idata, axs=[axs[0], axs[3]], subset_idx=subset_idx) make_plot(result1.idata, axs=[axs[1], axs[4]], subset_idx=subset_idx) make_plot(result2.idata, axs=[axs[2], axs[5]], subset_idx=subset_idx) plt.suptitle("Comparing Propensity Scores across model specification(s)", fontsize=11 ) Path("images/weighting").mkdir(parents=True, exist_ok=True) fig.savefig("images/weighting/propensity_score_dist.png", dpi=300, bbox_inches="tight", pad_inches=0.05, )
Balance is the central promise of propensity score methods. If the treated and control groups can be made comparable on observables, then the remaining difference in outcomes can plausibly be attributed to treatment. But before we use the weights, let’s test what sort of balancing material they are made of.
The Figure 5.4 plots the estimated propensity scores under three model specifications, looking at them in two complementary ways. The first panel in each column shows the density of the posterior mean propensity scores for treated versus control individuals. Ideally, the two distributions should overlap substantially, meaning there is “common support”: for any treated unit there are untreated units with similar probabilities of treatment, and vice versa. In the LaLonde data, the propensity score distributions confirm the information gap the imputation model exposed: controls pile up near zero, treated individuals spread across the rest of the range, and the region of genuine ambiguity is thin.
Figure 5.4
The second panel goes a step further by visualizing posterior uncertainty for randomly selected individuals. Each vertical bar shows a 90% interval for a unit’s propensity score, with a dot at the median. We do not know each propensity with certainty: the logistic regression produces a distribution, not a fixed number. For some individuals, the interval is wide, reflecting sparse or ambiguous covariate information. That uncertainty translates directly into uncertainty about the weights we will later apply.
Note📖 Identification: what propensity score methods require
Propensity score methods rest on two assumptions:
Unconfoundedness: \(Y(1), Y(0) \perp T \mid X\) - no unmeasured confounding. The potential outcomes are independent of T given X i.e. conditionally exchangeable
Overlap (Positivity): \(0 < e(X) < 1\) - positive probability of both treatment and control at all covariate values
Unconfoundedness alone is what Rubin calls ignorability: the assignment mechanism is ignorable given \(X\), and this is the condition behind the apparent paradox we saw above. Add positivity and the two together define strong ignorability, the condition propensity-score estimators need once we leave the Bayesian-ideal setting of a correctly specified outcome model and have to estimate the causal contrast from finite, possibly uninformative data. Positivity is a constraint on information content.
By de Finetti’s theorem we can represent \((X_{i}, Y_{i}, T_{i})\) using conditionally independent distributions governed by latent parameters. Concretely, unconfoundedness acts as a restriction on this parameter space: it assumes the treatment assignment mechanism \(p(T \mid X, Y(1), Y(0), \theta_T)\) simplifies to \(p(T \mid X, \theta_T) = e(X)\). And as we’ve seen, estimating this propensity score model independent of the outcome gives us direct insight into the informativeness of our data.
The balance plots above directly diagnose overlap. Where treated and control propensity distributions don’t overlap, causal effects are not well identified i.e. the data cannot tell us what would have happened under the counterfactual treatment. Propensity score weighting (\(1/e(X)\) for treated, \(1/(1-e(X))\) for control) creates balance by reweighting to a pseudo-population where treatment is independent of \(X\). Propensity score regression achieves similar goals by controlling for \(e(X)\) in the outcome model. The key insight of Rosenbaum and Rubin (1983) is that if unconfoundedness holds given \(X\), it holds given \(e(X)\), allowing us to achieve covariate balance in a single dimension rather than across the full covariate space. If unconfoundedness doesn’t hold given \(X\), we should ask what omitted confounders need to be measured to recover conditional exchangeability.
The propensity scores now give us a single-dimensional summary of the overlap problem the strata analysis and the imputation failure already diagnosed. The question becomes what to do about it. Weighting methods attempt to correct for the imbalance by privileging comparisons in the region where treated and control units genuinely resemble each other, up-weighting observations in areas of good overlap and down-weighting those at the extremes.
5.12.1.1 HT balancing
Balance diagnostics are the bread and butter of any propensity score analysis. Without them, we are blind to whether the weights have actually done their job. Here the Horvitz–Thompson (HT) scheme is put to the test by plotting the empirical cumulative distribution functions (ECDFs) of covariates before and after weighting.
The left-hand panel shows the raw data: for age, the treated and control groups do not overlap well, with the control group generally younger. On the right, after HT reweighting, the lines are meant to lie closer together, signaling improved balance. But in practice, for the LaLonde CPS data, the overlap is only modest. HT weights are notorious for their instability when propensity scores are extreme, as they are here. A handful of observations with very small or very large estimated probabilities of treatment dominate the weighting, and rather than pulling the groups together, they exaggerate noise.
Repeating the same exercise with prior earnings (re75) confirms the point: the reweighted ECDF still shows a gap between treated and control groups. Even an unbiased weighting scheme can fail in practice. That is exactly what these diagnostics are for, before we move on to outcome analysis.
Warning⚙️ Two-stage inference with propensity scores
As we saw above when we’re already conditioning on the covariate information in the propensity score, the score itself is technically redundant in the Bayesian setting if the outcome model is properly specified. This presumes that the assumption of unconfoundedness (or conditional exchangeability) used in causal inference holds. We are arguing that there is no unmeasured confounding, so conditioning on \(X\) should be sufficient to identify the causal contrast of interest. The potential outcomes are exchangeable conditional on the propensity score. Yet, if we try and estimate the joint-distribution of the propensity score and the outcome model simultaneously we can introduce a form of bias due to feedback. In most cases, our model is never exactly properly specified, so joint estimation of the propensity score and the outcome can push an improperly specified model to place undue weight on the propensity score.
When we have fit the outcome and the treatment models simultaneously this means that the outcome can influence the posterior distribution of the parameters in the treatment model. This strategy violates the idea of design-before-analysis. With an under-specified outcome model, we may use a well specified propensity score for adjusting the model to retrieve accurate treatment effect estimates. However, this tends to break down if we have estimated both propensity score and outcome in a joint Bayesian model due to feedback effects corrupting the weight accorded to the propensity score.
The solution: Use the propensity score in a 2 stage fashion as we have here; first estimate the propensity score and then feed it into the outcome model or use it for re-weighting where it can augment the accuracy of the treatment effects derived. Ideally this is done in an uncertainty aware fashion, where we sample from the estimated propensity score distribution and feed the values forward into the subsequent inverse weighting scheme or regression model. This again emphasises that it matters which kinds of information we leverage in statistical inference. For more details on the feedback problem see the CausalPy docs
The same feedback risk recurs, in a sharper form, wherever a control-function residual (not just a propensity score) is fed into an outcome equation from within a single joint posterior. Section 6.1 works through this in detail for a weak-instrument IV model. It also shows why the standard two-stage fix costs a small, well-understood amount of second-stage uncertainty in exchange for guaranteeing the first stage is never contaminated by outcome data.
5.12.1.2 Overlap balancing
The choice of weighting scheme determines what comparison is being made and how stable the resulting estimates will be. The Horvitz–Thompson (HT) weights are the most direct: each treated unit is weighted by \(1 / p\) and each control by \(1 / (1 - p)\), where \(p\) is the estimated propensity score. In principle, this creates a population-weighted average treatment effect (ATE). In practice, if some \(p\) is very close to 0 or 1, the corresponding weight becomes enormous, giving a handful of observations disproportionate influence. This is exactly what we saw in the poor rebalancing earlier.
Overlap weighting addresses the problem by design. Instead of inflating extreme cases, it assigns weights proportional to \((1 - p)\) for treated units and \(p\) for controls. Intuitively, units with scores near 0 or 1 get down-weighted. Those in the middle, where there is genuine ambiguity about treatment assignment, get the most influence. The target estimand here is not the ATE but the average treatment effect for the overlap population (ATO), meaning the effect for those individuals who could plausibly have been either treated or untreated.
The ECDF plots show the payoff. For age and prior earnings, the overlap-weighted treated and control groups align much more closely than under HT weighting. Balance is improved because the scheme emphasizes precisely those individuals for whom comparisons are most credible.
Even overlap weighting leaves a residual gap: it narrows the imbalance without erasing it. That caveat is worth carrying into the effect estimates we compute next.
5.13 Deriving treatment effects from weighted outcomes
Having inspected balance, we arrive at the point of the whole exercise: estimating treatment effects. The plots and calculations here illustrate how the different weighting schemes translate into estimates of causal impact. In this process, we have first estimated a propensity-for-treatment for each individual, and we now sample from this propensity score to re-weight the outcomes and derive a “corrected” estimate of the treatment effect.
For the Horvitz–Thompson (raw) scheme, each observed outcome is weighted by the inverse of the probability of the treatment it actually received. This is the \(1/\pi_{i}\) weighting of the elephants, with \(\hat{e}(X_{i})\) in place of the inclusion probability:
The overlap scheme replaces those weights with \(1-\hat{e}(X_{i})\) for treated units and \(\hat{e}(X_{i})\) for controls, normalised within each group:
Each posterior draw of \(\hat{e}(X)\) yields one estimate, so the spread of the estimates carries the uncertainty in the propensity model forward.
Figure 5.5: Propensity scores, re-weighted outcomes and ATE under raw Horvitz-Thompson weighting.
When using the “raw” Horvitz–Thompson weighting scheme, the estimate targets the average treatment effect (ATE) for the whole population represented in the sample. As we have already seen, the HT weights are highly variable in the LaLonde CPS data, and that instability carries over: the ATE estimate comes with wide intervals. The resulting plot shows the distribution of the propensity scores for both groups and the “pseudo-population” created by the weighting scheme. The printed expected_ate summarizes the point estimate across repeated draws of the posterior treatment estimate.
expected_ate = np.mean([ result0.get_ate(i, result0.idata, method="raw")[0] for i inrange(500)])print(f"Expected ATE: {expected_ate}")
Expected ATE: -11598.678972602434
The result is striking: the estimated treatment effect is strongly negative, contrary to the experimental benchmarks. By now, we shouldn’t be too surprised at the warping impacts of extreme propensities, but what can we do about it?
Switching to the overlap weighting scheme changes both the target and the behaviour of the estimator. Instead of the ATE, we now obtain the average treatment effect for the overlap population (ATO), that subset of individuals whose treatment status is genuinely ambiguous given their covariates. This estimand has the advantage of being anchored in the region of common support, where treated and control units look most alike.
Figure 5.6: Propensity scores, re-weighted outcomes and ATO under overlap weighting.
expected_ato = np.mean([ result0.get_ate(i, result0.idata, method="overlap")[0] for i inrange(500)])print(f"Expected ATO: {expected_ato}")
Expected ATO: 565.3601530587802
This result seems closer to a plausible value, while still falling short of the experimental benchmark. The printed expected_ato makes this concrete: in practice, we gain not only interpretability but also statistical efficiency. Different weighting schemes embody different philosophies of causal inference: who is being compared to whom, and how much influence is granted to those on the margins of treatment assignment. In the LaLonde data, the choice between HT and overlap weighting changes both the estimand and the credibility of the conclusions.
Note📖 Weighting schemes and target estimands
As we’ve seen there are different weighting schemes and strategies available. Each target different estimands.
Estimand
Target Population
Weights (T/C)
Stability
ATE
Everyone
\(1/e(X)\), \(1/(1-e(X))\)
Poor when overlap fails
ATT
Treated units
\(1\), \(e(X)/(1-e(X))\)
Better for observational studies
ATO
Overlap region
\(1-e(X)\), \(e(X)\)
Most stable
Doubly-Robust Methods combine propensity weighting with outcome regression, and remain consistent if either the outcome model or the weighting model is correct. We do not construct one here, but CausalPy provides a doubly-robust estimator directly: pass method='doubly_robust' to get_ate or plot_ate (the same method= argument used above for 'raw' and 'overlap'; it is in fact the default).
Which to use? Standard inverse probability weighting (IPW) targeting ATE is unstable in the LaLonde data due to extreme propensities. ATT is appropriate if the treated group is your policy target. ATO provides the most stable inference by focusing on where comparisons are credible.
But we can also test the role of propensity scores in regression strategies too.
5.13.1 Regression enhanced with propensity scores
Regression adjustment and propensity methods need not be rivals; they can be combined to strengthen inference. The block of code below explores exactly this. The idea is to estimate the treatment effect on earnings in 1978 (re78) using a regression model that controls for observed covariates, and then to augment this regression with the estimated propensity score itself as an additional covariate.
The first two models show the contrast clearly. In model0, we regress outcomes on treatment and background characteristics. In model1, we add indicators for the propensity-score quintile strata, summarizing in a single variable the joint likelihood of treatment assignment given covariates. This adjustment can reduce residual confounding and improve precision, particularly when the covariates influence both treatment and outcome in complicated ways.
The second pair of models, model2 and model3, introduce trimming: observations with extreme propensity scores (below 0.1) are dropped. This “clipping” limits the influence of units with no meaningful counterfactual match, a practice consistent with overlap weighting logic. By removing such cases, the regression focuses on the subpopulation where treated and controls are more comparable.
It is worth seeing exactly how much of the sample that trim removes, rather than taking “clipping the extremes” on faith:
n_total =len(df_reg)n_trimmed =len(df_reg[df_reg["pscore"] >0.1])n_treated_total =int((df_reg["treat"] ==1).sum())n_treated_trimmed =int((df_reg[df_reg["pscore"] >0.1]["treat"] ==1).sum())n_control_total =int((df_reg["treat"] ==0).sum())n_control_trimmed =int((df_reg[df_reg["pscore"] >0.1]["treat"] ==0).sum())print(f"Rows before trimming: {n_total}")print(f"Rows after trimming (pscore > 0.1): {n_trimmed} ({n_trimmed / n_total:.1%})")print(f"Treated units retained: {n_treated_trimmed} of {n_treated_total}")print(f"Control units retained: {n_control_trimmed} of {n_control_total}")
Rows before trimming: 16177
Rows after trimming (pscore > 0.1): 448 (2.8%)
Treated units retained: 143 of 185
Control units retained: 305 of 15992
This is not a light prune of a few outliers. Most of the sample is gone, and the control pool shrinks far more, proportionally, than the treated group does. What model2 and model3 are actually fit on is a small, closely matched core. That is exactly why the comparison is more credible: treated and control units in this remaining core genuinely resemble each other on the propensity scale, but it is also why the tighter agreement with the experimental benchmark below should be read as a property of a much narrower dataset, not a free improvement on the original one.
5.13.2 Trimming extremes and comparing to the experimental benchmark
The forest plot makes the payoff visible. Each horizontal line represents an interval estimate for the treatment effect under one of the four approaches. The vertical line marks the experimental benchmark from the original LaLonde randomised evaluation. What we see is that regression alone slightly underestimates the experimental benchmark, while combining regression with propensity scores inflates the uncertainty and improves the treatment effect estimate. Trimming the extremes pulls the estimates closer to the experimental truth again. Even without trimming, though, the credible interval derived from the regression model includes the experimental benchmark. Unlike the imputation model, this regression fits one treatment coefficient across all units, so its coverage rests on that constant-effect assumption rather than on the overlap the data lack.
Regression plus propensity score (PS) treatment estimate compared with the experimental benchmark
Angrist and Pischke (Angrist and Pischke 2008) report the experimental benchmark (black line) as the standard against which the quasi-experimental estimators in this chapter should be judged, which is exactly the role it has played here. But the dispute, noted earlier, about whether a randomised trial is best read as a generalisable natural experiment or as a momentary population survey is particularly acute in social-science settings. The LaLonde benchmark tells us the effect on those who enrolled in and completed a specific training programme, not on the wider population a real policy would need to reach. Job-training interventions like the one behind the LaLonde data have a richer propensity structure than a single enrollment gate: attrition and adoption are themselves selective, correlated with exactly the motivation, circumstance and opportunity that also predict earnings, so a participant who drops out for a job offer or never shows up for a session is not missing at random any more than an untreated comparison unit is. This is not a flaw specific to the LaLonde trial; it is a feature of experiments on social behaviour generally.
The pragmatic lesson of the LaLonde data is that no single adjustment guarantees credible inference, but combining strategies such as regression with covariates, propensity scores or trimming can move us closer to estimates that are robust and less hostage to model misspecification. A regression model can “borrow” information encoded in the propensity score, turning the assignment mechanism from a preprocessing step into a source of insight. The propensity score encodes information about the data-generating process - specifically, what the assignment mechanism reveals about who was treated and why. When incorporated into a regression likelihood, as stratifying covariates, as a direct predictor, or through trimming the comparison class, this information does not circumvent the likelihood; it enriches it, producing a model whose structure better reflects the causal reality we are trying to learn from.
5.14 Conclusion
The challenge, always, is to find an arrangement of the facts in which the likelihood becomes informative about the causal consequences of treatment: a configuration in which the data can genuinely teach us what would have happened under the counterfactual. Propensity scores do not answer that question. But they tell us where it can be credibly asked, and where it cannot. That is their real work here: less to correct a biased estimate than to diagnose whether the data hold a credible comparison at all.7 Where they reveal that it does not, as in the LaLonde CPS sample, no amount of modelling ingenuity can manufacture the missing information. Where they reveal that it does, the design information they carry can be folded back into the likelihood, sharpening the model rather than sitting outside it. What matters, in the end, is not which method we swear by but what evidence we have to hand, whether we are weighing elephants or evaluating a job-training programme. A compelling causal contrast is determined by who showed up, and whether anyone comparable did too. In the next chapter we take up the harder case where the confounder itself is never observed, and inducements to turn-out still help isolate local treatment effects in the responsive population.
Angrist, Joshua, and Jörn-Steffen Pischke. 2008. Mostly Harmless Econometrics: An Empiricist’s Companion. Princeton University Press.
Brewer, KRW. 1995. ‘Combining Design-Based and Model-Based Inference’. Business Survey Methods, 589–606.
Little, Roderick J. A. 2011. ‘Calibrated Bayes, for Statistics in General, and Missing Data in Particular’. Statistical Science 26 (2): 162–74. https://doi.org/10.1214/10-STS318.
Little, Roderick J. A. 2025. Seminal Ideas and Controversies in Statistics. CRC Press.
Mayo, Deborah G. 1996. Error and the Growth of Experimental Knowledge.
Mayo, Deborah G. 2018. Statistical Inference as Severe Testing: How to Get Beyond the Statistics Wars. Cambridge University Press.
Rosenbaum, Paul R., and Donald B. Rubin. 1983. ‘The Central Role of the Propensity Score in Observational Studies for Causal Effects’. Biometrika 70 (1): 41–55. https://doi.org/10.1093/biomet/70.1.41.
Steiner, Peter M., Yongnam Kim, Courtney E. Hall, and Dan Su. 2017. ‘Graphical Models for Quasi-Experimental Designs’. Sociological Methods & Research 46 (2): 155–88. https://doi.org/10.1177/0049124115582272.
See also Brewer (1995) for more information on combining model- and design-based inference.↩︎
This is a deep and somewhat fraught topic, which we’re treating lightly here. Deborah Mayo discusses the likelihood principle from a philosophical perspective in Mayo (1996), Mayo (2018) and a Bayesian perspective can be found in Little (2025).↩︎
There is an ongoing debate about the evidentiary role of randomised controlled trials and whether they should be seen as an experiment or population survey or both (Longford and Nelder 1999; Cartwright and Hardie 2012). The debate comes from the contention that even though trial procedures involve randomisation, they are often quite selective in the trial participants and this can reduce the diversity of treatment responses in the RCT. This lack of diversity undermines the ability to generalise effectively from an RCT. We won’t wade into this debate, more than to say that the discussion does mandate an understanding of propensity for treatment, the topic of this chapter.↩︎
See Angrist and Pischke (2008) for detailed discussion.↩︎
The estimated propensity score is technically downstream of treatment and the covariates, but the hypothetical population propensity score is not.↩︎
The structural logic of: projecting a high-dimensional confounder onto a measured scalar summary, to condition on it and recover exchangeability will reappear. In the panel-data setting we’ll see how Mundlak devices (Chapter 13), decompose unit level confounding so that the unit mean of treatment \(\bar{D}_i\) plays the role similar to \(e(X)\) here.↩︎
This division of labour, Bayesian inference for the estimate, frequentist-style diagnostics for checking whether the model deserves trust, rhymes with Roderick Little’s calibrated Bayes position (Little 2011) and some themes from the model checking and Bayesian workflow literature e.g. Gelman et al. (2026)↩︎