(matching-en)=
# Matching and Propensity Score Matching

An analyst at Rappi compares customers who had at least one order arrive more than 15 minutes late last month with customers whose orders all arrived on time. The result is puzzling: the customers with a late delivery place *more* orders the following month. Should Rappi conclude that late deliveries don't matter, or even that they help?

The [section on DAGs](3_dags.md) ended with an answer in principle: if the variables that cause the problem are observed, it is enough to condition on them (**conditional independence**). This section turns that answer into estimators that do not need to assume a linear regression. The tool is **matching**: compare each customer who had a late delivery with on-time customers who resemble them.

We cover the topic in four steps, each with a dashboard. First, exact matching by segments and how it relates to regression. Second, what happens when characteristics are continuous and the "most similar" customer is never identical. Third, the bias this creates, following Abadie and Imbens, and how to correct it. Fourth, the **propensity score**, which summarizes many characteristics in a single number. The section ends by sorting the estimators by what they model, which sets up the chapter on doubly robust estimators.

*The Rappi scenario is stylized: all the data in this section is simulated.*

---

## 1. Objectives

The previous section told us *what* to condition on; this one tells us *how*. By the end, the reader will be able to:

- State the conditional independence (CIA) and overlap assumptions, and judge when selection on observables is credible.
- Compute the ATT by exact matching as a weighted average of within-cell differences.
- Explain why regression and matching can give different numbers under the same CIA when the effect is heterogeneous.
- Explain why nearest-neighbor matching is biased with several continuous covariates, and how the regression-based bias correction fixes it.
- Use the propensity score to match, check common support and verify balance.
- Classify estimators by what they model: the outcome or the treatment assignment.

---

## 2. Do late deliveries make customers order more?

Back to the analyst. Their comparison is what the [section on experiments](1_rcts.md) called the **naive estimator**, and it suffers from the same problem: the two groups are not comparable. Late deliveries do not fall at random. Customers who live in the **city center** and order at **dinner peak** get more late deliveries (traffic, overloaded restaurants, too few couriers), and they are also the ones who order the most anyway: they have more restaurants nearby and the habit of using the app. The late group is full of customers who would have ordered a lot even without a delay.

In the language of the previous section, zone and time of day ($Z$) are a **fork**: they cause both the late delivery ($T$) and orders ($Y$),

$$T \leftarrow Z \rightarrow Y, \qquad T \rightarrow Y.$$

The backdoor path $T \leftarrow Z \rightarrow Y$ is open, and it biases the naive comparison. But there is an important difference from the driver-bonus example in the [section on experiments](1_rcts.md). There, what drove participation was the driver's *motivation*, which nobody records. Here, what drives late deliveries are variables the platform logs routinely: zone, order time, restaurant load, courier supply. If those variables capture everything that makes the two groups different, the backdoor path can be blocked with data.

We already know one way to do that: include those variables as controls in a [multiple regression](../ch2_regresion_multiple/1_multiple_regression.md). But a linear regression commits to a functional form and, as we will see, also to a particular way of averaging effects. Matching proposes something more direct: **compare like with like**.

---

## 3. Comparing like with like: exact matching

Let us start with the simplest case. Suppose the only thing that distinguishes customers, as far as late deliveries go, is their **segment**, defined by two binary variables: zone (city center or residential) and time (dinner peak or not). That gives four segments:

- **A**: city center, peak (the most exposed to late deliveries, and the heaviest users);
- **B**: city center, off-peak;
- **C**: residential, peak;
- **D**: residential, off-peak (almost never late, the lightest users).

The idea of exact matching is to compare late and on-time customers *within each segment*, where they are alike, and then average those comparisons.

The dashboard simulates 4,000 customers. The true effect of a late delivery is **−1.5 orders** over the next 30 days. The table shows, for one sample, average orders of late and on-time customers in each segment; the chart summarizes three estimators over 500 samples.

- With **Selection intensity** at *Strong* and the **Effect of a late delivery** *Same in all* (the starting setup): where does the naive estimator land? What sign does it have?
- Look at the table: within each segment, do late customers order more or less than on-time ones? How does that combine in the last row?
- Set selection to *None*: what happens to the three estimates?
- Switch **Common support** to *A always late*: what happens to segment A's row? Does the estimate still answer the same question? (Try it with the effect *Varies by segment* too.)

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe src="https://simuecon.com/matching_segments/?lang=en" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen></iframe>
</div>

### What do we observe?

With strong selection, the naive estimator lands around **+0.4**: it concludes that a late delivery *increases* orders, when the true effect is −1.5. It gets the sign wrong. Within each segment, by contrast, late customers consistently order less than on-time ones, and the average of those differences falls right on −1.5. The bias did not come from late deliveries but from *who* gets them: segment A, which orders a lot, is overrepresented among late customers.

Without selection, the three estimates agree: this is the situation of a randomized experiment, where the naive comparison already works. And when a segment has no counterpart (*A always late*), its late customers cannot be compared with anyone. Matching drops them and estimates the effect for the late customers in segments B, C and D. With the same effect in every segment this goes unnoticed; with different effects, the estimate answers a different question.

### Formal results

We use the potential outcomes framework from the [section on experiments](1_rcts.md): $Y_i(1)$ and $Y_i(0)$ are customer $i$'s orders with and without a late delivery, and the naive comparison equals the ATT plus a selection bias,

$$E[Y_i\mid T_i=1]-E[Y_i\mid T_i=0] = \text{ATT} + \underbrace{E[Y_i(0)\mid T_i=1]-E[Y_i(0)\mid T_i=0]}_{\text{selection bias}}.$$

Let $X_i$ be the customer's segment: the observed variables we called $Z$ in the DAG. We need two assumptions.

**Conditional independence assumption (CIA).** Within each segment, a late delivery is "as good as random":

$$\{Y_i(0),Y_i(1)\}\perp T_i \mid X_i.$$

For the ATT, a weaker version involving only the untreated outcome is enough: $E[Y_i(0)\mid X_i,T_i=1]=E[Y_i(0)\mid X_i,T_i=0]$. It is the backdoor condition from the [DAGs section](3_dags.md), written in potential outcomes.

**Overlap (common support).** Each segment has customers from both groups: $0<P(T_i=1\mid X_i)<1$. For the ATT, $P(T_i=1\mid X_i)<1$ is enough: every segment with late customers needs some on-time customer to compare them with.

**Formal result (identification by exact matching).** Under the CIA and overlap, the within-segment difference,

$$\delta_x = E[Y_i\mid X_i=x,T_i=1]-E[Y_i\mid X_i=x,T_i=0],$$

is the average causal effect for late customers in segment $x$, and the ATT is its average weighted by how late customers are distributed across segments:

$$\text{ATT} = \sum_x \delta_x \, P(X_i=x\mid T_i=1).$$

The proof is in the [appendix](appendix-matching-identification). The estimator replaces each term with its sample analog:

$$\widehat{\text{ATT}} = \sum_x \hat\delta_x \,\frac{n_{1x}}{n_1},$$

where $n_{1x}$ is the number of late customers in segment $x$ and $n_1$ the total number of late customers. For the ATE, the weights are the share of *all* customers in each segment, $n_x/n$, and overlap is needed in both directions.

**Example.** Here is the sample the dashboard shows when it opens (selection *Strong*, effect *Same in all*):

| Segment | $\bar Y$ late ($n$) | $\bar Y$ on time ($n$) | $\hat\delta_x$ | Weight $n_{1x}/n_1$ |
|---|---|---|---|---|
| A — center, peak | 7.53 (555) | 9.09 (441) | −1.56 | 0.50 |
| B — center, off-peak | 5.53 (315) | 6.90 (730) | −1.37 | 0.28 |
| C — residential, peak | 3.60 (193) | 5.07 (786) | −1.47 | 0.17 |
| D — residential, off-peak | 2.18 (52) | 3.44 (928) | −1.26 | 0.05 |

$$\widehat{\text{ATT}} = 0.50\times(-1.56)+0.28\times(-1.37)+0.17\times(-1.47)+0.05\times(-1.26)\approx -1.48.$$

The naive comparison in this same sample gives $+0.41$. Half of the late customers are in segment A, which has the highest baseline orders; comparing within each segment neutralizes that advantage. With the ATE weights (each segment's share of customers, roughly a quarter each) the estimate would be $-1.42$: very close, because here the effect is the same in every segment.

```{admonition} A classic case: Dale and Krueger (2002)
:class: tip
Is attending a more selective college worth it? Graduates of selective colleges earn more, but they are also stronger students to begin with. {cite:t}`dale2002estimating` grouped students by the *set of colleges that admitted them* and compared, within each group, those who chose the most selective one with those who chose another. That is exact matching: the cell is the set of admissions, which summarizes what the colleges saw in each student. Within cells, the earnings advantage of the selective college shrank a lot. The example is also a warning: the design is credible because the cell captures something that would otherwise be unobservable.
```

```{admonition} 💻 How to Estimate in Code
:class: dropdown

Part 1 of the section's notebook, which opens at the end of [section 6](matching-bias-en), builds the matching table with `pandas`, computes the ATT and the ATE, and compares them with the dummy regression and the interacted regression, with equal and segment-specific effects.
```

---

## 4. Matching and regression: same assumption, different weights

Under the CIA, a regression with a full set of segment dummies also identifies a causal effect: the coefficient on $T$ in

$$Y_i = \alpha_{X_i} + \beta\,T_i + \varepsilon_i$$

compares late and on-time customers within each segment, just as matching does. If the effect of a late delivery is the same in every segment, both methods estimate the same thing. In the dashboard, with the effect *Same in all*, the *Matching* and *OLS + dummies* dots coincide.

Go back to the dashboard and choose the effect *Varies by segment*. Now city-center peak customers lose more orders after a late delivery (−4), because they have the most alternatives, and segment D customers lose nothing. Compare the matching dot, the OLS dot and the dashed ATE line.

With strong selection, matching gives about **−2.73**, which is the true ATT; OLS with dummies gives about **−2.37**; and the ATE is −1.75. Three different numbers, and none of them is "wrong". The difference lies in how each one weights the segment effects.

**Formal result (weights of the dummy regression).** With a full set of segment dummies, the OLS coefficient converges to a weighted average of the segment effects,

$$\beta^{OLS} = \frac{\sum_x \delta_x\, P(X_i=x)\,p_x(1-p_x)}{\sum_x P(X_i=x)\,p_x(1-p_x)}, \qquad p_x = P(T_i=1\mid X_i=x),$$

while the ATT weights by $P(X_i=x)\,p_x$, and the ATE by $P(X_i=x)$ {cite:p}`angrist2009mostly`. The derivation is in the [appendix](appendix-matching-ols).

Matching for the ATT gives more weight to the segments where the late customers *are*. Regression gives more weight to the segments where lateness *varies* most, that is, where $p_x$ is close to 0.5. In the simulation, segment A has $p_A=0.55$: it weighs a lot in both, but the ATT weights it even more, because it holds half of the late customers. Segment D has almost no late customers and barely counts in either.

Which one should you use? It depends on the question. If Rappi wants to know how much the late deliveries that actually happened cost it, the answer is the ATT. If it wants to know what would happen if late deliveries hit all customers alike, it is the ATE. The dummy regression answers neither question when effects are heterogeneous: it answers a third one, with weights that come from the variance of the treatment. A fully interacted regression (treatment interacted with each dummy, as in the saturated model of the [section on the conditional expectation function](../cef/cef.md)) recovers the segment effects, and with them the ATT or the ATE.

---

## 5. Continuous covariates: how close is the nearest match?

Segments were a convenient starting point, but the characteristics Rappi actually logs are **continuous**: past order frequency, distance to the city center, share of orders at peak, tenure, basket size. No two customers are exactly alike, so there are no cells to compare within.

The natural fix is **nearest-neighbor matching**: each late customer $i$ is assigned the on-time customer $j(i)$ with the most similar characteristics, and their orders are used as an estimate of what $i$ would have ordered without the delay:

$$\hat\tau^{M}=\frac{1}{N_1}\sum_{i:T_i=1}\Big(Y_i-\frac{1}{M}\sum_{m=1}^{M} Y_{j_m(i)}\Big).$$

Three choices define the estimator:

- **The distance.** Characteristics come in different units (orders per month, kilometers), so they are measured in **standardized** units, dividing each by its standard deviation. The **Mahalanobis** distance does the same and also accounts for correlations between characteristics.
- **Replacement.** With **replacement**, the same on-time customer can be the match of several late customers. That improves the matches but raises the variance, because some controls carry a lot of weight.
- **The number of matches $M$.** Using more than one neighbor reduces the variance, but the extra neighbors are farther away, which increases the bias.

The match is never exact: there is always a **matching discrepancy** $U_i = X_{j(i)}-X_i\neq 0$. The question is how large it is, and whether it shrinks with more data. The dashboard simulates customers with $k$ continuous characteristics, with 4 on-time customers per late one, and finds each late customer's nearest neighbor.

- With $k=1$, raise the number of late customers from 100 to 3,000: how fast do the lines joining each late customer to their match shrink?
- Switch to $k=8$: why do some "nearest" matches look far apart in the two-dimensional plot?
- In the log–log plot, compare the slope of each line with the reference slope $-1/k$.
- In the *How different is the nearest match?* panel, compare the typical gap with that between two customers picked at random.

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe src="https://simuecon.com/matching_discrepancy/?lang=en" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen></iframe>
</div>

### What do we observe?

With a single characteristic, the nearest neighbor is practically identical: the average distance is 0.012 standard deviations with 100 late customers and 0.001 with 3,000. With eight characteristics, the average distance is 1.6 standard deviations with 100 late customers and still 1.04 with 3,000: thirty times more data reduced it by only a third. This is the **curse of dimensionality**: in many dimensions, everyone is far from everyone.

The matches that look poor in the two-dimensional plot are not mistakes: they were chosen to be close in all eight characteristics *at once*, and in eight dimensions "close in everything" means "not that close in any".

### Formal results

**Formal result (size of the discrepancy).** With $k$ continuous characteristics, the typical discrepancy shrinks like

$$\lVert U_i\rVert \;\propto\; N^{-1/k}$$

{cite:p}`abadie2006large`. On a log–log scale this is a straight line with slope $-1/k$, which is what the dashboard shows. Doubling the data multiplies the discrepancy by $2^{-1/k}$: by 0.50 with $k=1$, but only by 0.92 with $k=8$. To halve it you need $2^k$ times more data: twice as much with one characteristic, 256 times as much with eight.

---

(matching-bias-en)=
## 6. The bias of matching and its correction

A gap in characteristics would not be a problem if it did not affect orders. But it does: if frequent, city-center customers order more anyway, and a late customer's match is a bit less frequent and lives a bit farther from the center, their orders understate what the late customer would have ordered without the delay. Let $\mu_0(x)=E[Y_i(0)\mid X_i=x]$ be the expected level of orders without a late delivery. Each pair carries an error $\mu_0(X_i)-\mu_0(X_{j(i)})$, and their average is the estimator's **conditional bias**:

$$B_M=\frac{1}{N_1}\sum_{i:T_i=1}\frac{1}{M}\sum_{m=1}^{M}\Big(\mu_0(X_i)-\mu_0(X_{j_m(i)})\Big).$$

Since the discrepancy shrinks slowly with many characteristics, so does the bias. The uncomfortable question is whether it shrinks faster than the noise. The dashboard compares three ATT estimators (true effect: −1.5) over 500 samples: **simple matching**, the **bias-corrected matching** presented below, and **regression imputation**, which uses a linear regression on its own. For each one it shows the bias, the standard deviation and the **coverage**: how often the 95% confidence interval contains the true effect.

- With $k=1$: are all three estimators centered on −1.5, whatever the shape of expected orders?
- With $k=4$ or $8$ and a *Linear* shape, raise $N_1$: what happens to simple matching's coverage? Is that what you expected from "more data"?
- In the bottom chart, does the simple-matching line enter the green band as $N_1$ grows, or move away from it?
- With a *Strongly curved* shape, compare regression imputation with bias-corrected matching.

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe src="https://simuecon.com/matching_bias/?lang=en" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen></iframe>
</div>

### What do we observe?

With one characteristic, simple matching works: its bias is a small fraction of the noise and its intervals cover about 95% of the time. With several, the problem appears. With $k=8$ and a linear shape, simple matching's coverage is 82% with 100 late customers, 71% with 300, 45% with 1,000 and **17% with 3,000**. More data makes the intervals *worse*. The bottom chart shows why: bias divided by the standard deviation grows with $N_1$, because the noise shrinks faster than the bias.

Bias-corrected matching, with the same data and the same matches, keeps coverage between 92% and 96%. Regression imputation also works when expected orders are linear, and it is then the most precise estimator. But when they are curved, imputation misses badly: its bias does not depend on the sample size, so with 300 late customers or more its intervals cover the true effect 25% of the time or less, and with 1,000 never. In contrast, bias correction, which uses *the same* misspecified linear regression, removes much of matching's bias.

### Formal results

**Formal result (Abadie and Imbens, 2006).** The conditional bias of nearest-neighbor matching is of the order of the discrepancy, $B_M = O_p(N^{-1/k})$, while the standard error is of order $N^{-1/2}$. As a consequence {cite:p}`abadie2006large`:

1. With **one** continuous characteristic ($k=1$), the bias becomes negligible relative to the noise: the estimator is $\sqrt{N}$-consistent and its intervals are valid.
2. With $k\ge 2$, the bias does not vanish fast enough. The estimator is not, in general, $\sqrt{N}$-consistent, and intervals centered on it cover less and less as the sample grows.
3. For the ATT, having many more controls than treated units helps: if $N_0$ grows sufficiently faster than $N_1$, the discrepancies shrink enough.
4. The bias is larger where $\mu_0$ changes quickly and where there are few controls near the treated.

The decomposition of the estimator into effect, noise and bias is in the [appendix](appendix-matching-bias).

**Bias-corrected matching** {cite:p}`abadie2011bias`. Fit a regression $\hat\mu_0(x)$ for on-time customers and use it to adjust each pair for the gap in characteristics:

$$\hat\tau^{bc}=\frac{1}{N_1}\sum_{i:T_i=1}\Big(Y_i-\frac{1}{M}\sum_{m=1}^{M}\big[\,Y_{j_m(i)}+\hat\mu_0(X_i)-\hat\mu_0(X_{j_m(i)})\,\big]\Big).$$

The intuition is that the regression does not have to get each customer's whole level of orders right. It only has to get the **small difference** between two close neighbors right, and for that it is enough to capture the local slope. That is why a linear regression, even a misspecified one, removes most of the bias. In the dashboard the regression is fitted on the controls used as matches, each weighted by the number of times it is used, as Abadie and Imbens propose; that way the estimated slope is the one in the region where the late customers are. If the regression is correct, the correction adds a little noise but no bias.

The dashboard also shows the limit of the idea. With strongly curved expected orders and many characteristics, a *linear* correction reduces the bias but not enough: with $k=4$ and 3,000 late customers the coverage of corrected matching falls to 72%. Abadie and Imbens address this by letting the regression become more flexible as the sample grows.

Behind the correction there is an idea worth naming: **two models that protect each other**. Matching does not need the regression to be right, because the regression only corrects small differences. The regression does not need the matches to be perfect, because it corrects what they miss. The next chapter, on doubly robust estimators, generalizes exactly this idea.

Two practical notes. First, the usual **bootstrap** is not valid for nearest-neighbor matching {cite:p}`abadie2008failure`; the dashboard's standard errors use the Abadie–Imbens (2006) analytical variance formula, which accounts for how many times each control is reused. Second, Abadie and Imbens (2011) show with real data that uncorrected estimates change considerably with the number of neighbors $M$, while corrected ones are stable.

<div class="jupyterlite-embed-wrapper" data-paid-gated="true"
     data-lite-url="_jupyterlite/notebooks/index.html?path=8_matching_notebook.ipynb"
     data-button-label="💻 How to Estimate in Code"></div>

The section's notebook (Part 2) implements this pipeline on a sample with four continuous characteristics: nearest-neighbor matching with `scipy`, the bias correction, the Abadie–Imbens standard errors from scratch and a check with the `causalinference` package. Parts 1 and 3 cover exact matching and the propensity score.

---

## 7. The propensity score: matching on a single number

The two previous sections showed that matching on many characteristics is hard. {cite:t}`rosenbaum1983central` proposed a way out: instead of matching on all characteristics, match on a single number, the **propensity score**,

$$e(X)=P(T_i=1\mid X_i),$$

the probability of a late delivery given the characteristics.

**Formal result (Rosenbaum and Rubin, 1983).** If the CIA holds conditional on $X$, it also holds conditional on $e(X)$:

$$\{Y_i(0),Y_i(1)\}\perp T_i\mid X_i \;\;\Longrightarrow\;\; \{Y_i(0),Y_i(1)\}\perp T_i\mid e(X_i).$$

Moreover, whether or not the CIA holds, the score has the **balancing property**: $X_i\perp T_i\mid e(X_i)$. Among customers with the same score, characteristics are distributed alike between late and on-time customers. The intuition: two customers with the same probability of a late delivery are, on average, alike in everything that drives lateness. The proof is in the [appendix](appendix-matching-pscore).

The **propensity score matching** (PSM) recipe has four steps:

1. Estimate $e(X)$, typically with a logit like the one in the [section on categorical dependent variables](../ch2_regresion_multiple/3_classification.md).
2. Match each late customer to the on-time customer with the closest estimated score (in practice, on the logit of the score).
3. **Check balance** of the characteristics in the matched sample.
4. Estimate the ATT as the average difference within pairs.

The dashboard applies this recipe to 3,000 customers with five characteristics: city-center location, share of orders at peak, order frequency, tenure and basket size. The probability of a late delivery depends on the first three and on the interaction center × peak. The effect of a late delivery is heterogeneous: frequent customers and city-center peak customers lose more, and they are also the ones most often late.

- Raise **Selection intensity** from *Moderate* to *Extreme*: what happens to the overlap of the two histograms? And to the most uses of one on-time customer?
- With *Extreme* selection, apply **Trimming** $[0.1, 0.9]$: compare the two "true ATT" numbers in the card.
- Go back to *Strong* selection without trimming and switch the **Score model** to *Misspecified logit*: which rows of the love plot leave the green band? What happens to the estimate?

<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe src="https://simuecon.com/psm_overlap/?lang=en" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;" allowfullscreen></iframe>
</div>

### What do we observe?

**Overlap.** With moderate selection, the scores of late and on-time customers overlap well and PSM recovers the ATT (−1.78 vs. −1.77). With extreme selection, many late customers have scores close to 1 and almost no on-time customer resembles them: a single on-time customer ends up matched to more than 200 late customers, and the standard deviation of the estimate more than triples. Matching still "works" in the sense that it finds a neighbor, but the neighbor is poor and overused.

**Trimming.** The $[0.1, 0.9]$ rule drops customers with extreme scores. With extreme selection, that removes almost half of the late customers, and the estimate becomes much more precise. But the card shows the cost: the true ATT for *all* late customers is −2.00, while for the late customers who remain it is −1.56. PSM estimates the latter well (−1.54). The dropped customers were precisely the ones most affected by the delay: **trimming changed the question**. The min–max rule drops fewer (21%) and changes the estimand less.

**Balance.** Before matching, city-center location, share of orders at peak and their interaction are badly unbalanced. With the correct logit, all of them end up inside the $\pm0.1$ band after matching (except with extreme selection and no trimming, where overlap is too poor). With the logit that omits the interaction, the interaction (0.49) and city-center location (0.31) stay clearly outside the band, and the estimate is biased: −1.61 vs. −1.89 with strong selection. The model's error shows up in the balance.

### Formal results

**Overlap and trimming.** If $P(T_i=1\mid X_i)$ is close to 1 for some customers, there are no comparable controls for them. The two most common rules are to keep only customers with $0.1\le\hat e(X_i)\le0.9$ {cite:p}`crump2009dealing`, or to drop late customers whose score exceeds the maximum among on-time customers (min–max common support). Any rule redefines the estimand: after trimming we estimate

$$\text{ATT}_{\mathcal{A}} = E\big[Y_i(1)-Y_i(0)\mid T_i=1,\ X_i\in\mathcal{A}\big],$$

the effect for the late customers who remain in the region $\mathcal{A}$. It is a legitimate question, but it has to be reported as such.

**Balance.** For each characteristic, the **standardized mean difference** compares the two groups in standard-deviation units:

$$SMD=\frac{\bar x_{late}-\bar x_{on\ time}}{\sqrt{(s^2_{late}+s^2_{on\ time})/2}}.$$

It is computed before and after matching (in the matched sample, each control weighted by the number of times it is used), and plotted in a **love plot**. A common rule of thumb is $|SMD|<0.1$ {cite:p}`stuart2010matching`. The key point is that **the diagnostic is balance, not the fit of the logit**. A high pseudo-$R^2$ guarantees nothing: a model that predicts late deliveries very well may, precisely for that reason, leave many customers without common support. What matters is whether, after matching, the groups look alike.

```{admonition} 💻 How to Estimate in Code
:class: dropdown

Part 3 of the same notebook in [section 6](matching-bias-en) implements PSM: the score logit with `statsmodels` (correct and misspecified), the overlap histogram, trimming rules, matching on the logit of the score and a love plot.
```

---

## 8. PSM in practice: caveats

```{admonition} Before reporting a PSM
:class: warning
- **The PSM paradox.** {cite:t}`king2019propensity` show that if you keep pruning matches to tighten the matching on the *estimated* score, imbalance in the characteristics can *increase*. The score is one tool among several, not a goal: always check balance on the characteristics themselves.
- **Standard errors.** The score is estimated, and that changes the estimator's variance. {cite:t}`abadie2016matching` derive the correction; using standard errors as if the score were known is incorrect.
- **Calipers and matching without replacement.** A *caliper* drops pairs whose score difference exceeds a threshold: it improves match quality but, like trimming, changes the estimand. Matching without replacement keeps a control from being used many times, but it worsens the matches and makes the result depend on the order in which units are matched.
- **Balance is necessary, not sufficient.** Matching can only balance what is observed. If each customer's price sensitivity, which nobody records, affects both exposure to late deliveries and orders, the CIA fails and no matching fixes it. Nor should you match on post-treatment variables such as "contacted support": they are mediators or colliders, and conditioning on them biases the estimate (see the [DAGs section](3_dags.md), §3.2 and §6).
```

---

## 9. Consolidation: what does each estimator model?

All the estimators in this section rest on the same identifying assumption, the CIA with overlap. What distinguishes them is which part of the problem they model:

| Estimator | Models the outcome? | Models the assignment? |
|---|---|---|
| Regression | Yes | No |
| Exact / nearest-neighbor matching | Imputes $Y(0)$ without a parametric model | No |
| Bias-corrected matching | Yes (to adjust the pairs) | No |
| Propensity score matching | No | Yes |
| *Doubly robust (next chapter)* | *Yes* | *Yes* |

A checklist for a matching analysis:

1. **Argue the CIA**, drawing the DAG: which variables drive the treatment, and are they all observed?
2. **Check overlap**.
3. **Match**.
4. **Check balance**.
5. **Correct the bias** when there are several continuous characteristics.
6. **Report the estimand**, including what changed with trimming.

Bias correction already combined a matching design with an outcome model. The next chapter combines the *propensity score* with an outcome model: the resulting estimators are consistent if *either* model is correct.

---

(appendix-matching)=
## Appendix: Formal derivations

(appendix-matching-identification)=
### A.1 Identification of the ATT by exact matching

**Step 1 —** By the law of iterated expectations over the distribution of $X_i$ among the treated,

$$\text{ATT}=E[Y_i(1)-Y_i(0)\mid T_i=1]=\sum_x \Big(E[Y_i(1)\mid X_i=x,T_i=1]-E[Y_i(0)\mid X_i=x,T_i=1]\Big)P(X_i=x\mid T_i=1).$$

**Step 2 —** The first term is observable: $E[Y_i(1)\mid X_i=x,T_i=1]=E[Y_i\mid X_i=x,T_i=1]$.

**Step 3 —** The second is counterfactual. By the CIA (in its weak form), $E[Y_i(0)\mid X_i=x,T_i=1]=E[Y_i(0)\mid X_i=x,T_i=0]=E[Y_i\mid X_i=x,T_i=0]$. Overlap ($P(T_i=1\mid X_i=x)<1$ for every $x$ with treated units) guarantees that this expectation is defined.

**Step 4 —** Substituting,

$$\text{ATT}=\sum_x \delta_x\,P(X_i=x\mid T_i=1).$$

For the ATE, repeat the argument with $P(X_i=x)$ as weights, also using $E[Y_i(1)\mid X_i=x,T_i=0]=E[Y_i\mid X_i=x,T_i=1]$, which requires $P(T_i=1\mid X_i=x)>0$.

(appendix-matching-ols)=
### A.2 Weights of the regression with segment dummies

**Step 1 —** By the Frisch–Waugh–Lovell theorem, the coefficient on $T$ in the regression of $Y$ on $T$ and a full set of segment dummies equals the coefficient of $Y$ on the residual of $T$ given the dummies. That residual is $\tilde T_i=T_i-p_{X_i}$, with $p_x=P(T_i=1\mid X_i=x)$:

$$\beta^{OLS}=\frac{E[\tilde T_i\,Y_i]}{E[\tilde T_i^2]}.$$

**Step 2 —** Within segment $x$, $E[\tilde T_i^2\mid X_i=x]=p_x(1-p_x)$, and

$$E[\tilde T_i Y_i\mid X_i=x]=p_x(1-p_x)\big(E[Y_i\mid X_i=x,T_i=1]-E[Y_i\mid X_i=x,T_i=0]\big)=p_x(1-p_x)\,\delta_x.$$

**Step 3 —** Averaging over segments,

$$\beta^{OLS}=\frac{\sum_x \delta_x\,P(X_i=x)\,p_x(1-p_x)}{\sum_x P(X_i=x)\,p_x(1-p_x)}.$$

**Step 4 —** The ATT, by contrast, uses $P(X_i=x\mid T_i=1)\propto P(X_i=x)\,p_x$. The two coincide if $\delta_x$ is constant, or if $p_x$ is the same in every segment (an experiment).

(appendix-matching-bias)=
### A.3 Decomposition of the matching estimator

Let $\mu_t(x)=E[Y_i(t)\mid X_i=x]$, and write $Y_i=\mu_{T_i}(X_i)+\varepsilon_i$. For the ATT estimator with $M$ matches,

$$\hat\tau^{M}-\text{ATT}=\underbrace{\Big(\frac{1}{N_1}\sum_{i:T_i=1}\big[\mu_1(X_i)-\mu_0(X_i)\big]-\text{ATT}\Big)}_{\text{heterogeneity}}+\underbrace{\frac{1}{N_1}\sum_{i}\Big(T_i-(1-T_i)\frac{K_M(i)}{M}\Big)\varepsilon_i}_{\text{noise}}+\underbrace{B_M}_{\text{bias}},$$

where $K_M(i)$ is the number of times control $i$ is used as a match and $B_M$ is the conditional bias defined in section 6.

The first two terms have mean zero and are of order $N^{-1/2}$; the noise term shows why reusing controls (large $K_M(i)$) raises the variance. The bias depends on the discrepancies: if $\mu_0$ is differentiable, $\mu_0(X_i)-\mu_0(X_{j(i)})\approx -\nabla\mu_0(X_i)'U_i$, and since $\lVert U_i\rVert=O_p(N^{-1/k})$, also $B_M=O_p(N^{-1/k})$. Multiplying by $\sqrt{N}$, the scaled bias is $O_p(N^{1/2-1/k})$, which does not vanish for $k\ge2$: that is the source of the coverage problem {cite:p}`abadie2006large`.

Bias correction subtracts an estimate of $B_M$, $\hat B_M=\frac{1}{N_1}\sum_{i:T_i=1}\frac1M\sum_m\big(\hat\mu_0(X_i)-\hat\mu_0(X_{j_m(i)})\big)$. What remains is $B_M-\hat B_M$, which depends on the error in the estimated *slope* of $\mu_0$ times the discrepancies: the product of two small quantities {cite:p}`abadie2011bias`.

(appendix-matching-pscore)=
### A.4 The balancing property of the propensity score

**Step 1 —** It suffices to show that $P(T_i=1\mid X_i,e(X_i))=P(T_i=1\mid e(X_i))$. The left-hand side is $P(T_i=1\mid X_i)=e(X_i)$, because $e(X_i)$ is a function of $X_i$.

**Step 2 —** The right-hand side, by iterated expectations, is $E\big[P(T_i=1\mid X_i)\mid e(X_i)\big]=E[e(X_i)\mid e(X_i)]=e(X_i)$. Both sides coincide, so $X_i\perp T_i\mid e(X_i)$.

**Step 3 —** For the CIA: $P(T_i=1\mid Y_i(0),Y_i(1),e(X_i))=E\big[P(T_i=1\mid Y_i(0),Y_i(1),X_i)\mid Y_i(0),Y_i(1),e(X_i)\big]$. By the CIA given $X_i$, the inner probability is $e(X_i)$, so the expression equals $e(X_i)$, which does not depend on the potential outcomes. Therefore $\{Y_i(0),Y_i(1)\}\perp T_i\mid e(X_i)$.

## Test what you learned

<div class="quiz-widget" data-quiz-slug="ch4-matching"></div>

## References

```{bibliography}
:filter: docname in docnames
```
