Causality in ML practice: spurious features, distribution shift and off-policy evaluation
Before this lesson: confounders, colliders and selection (lessons 01 and 03); inverse probability weighting (lesson 05); uplift models (lesson 08). Helpful: drift detection (mlops 07), bandits (reinforcement learning 03) and generalization in deep learning (deep learning 17). Time: about 80 minutes, plus the notebook.
Why this matters #
- Models that fail after launch. A pneumonia model trained in one hospital used hospital-specific tokens in the images and lost accuracy in other hospitals (Zech et al. 2018). Image classifiers label cows on beaches wrongly, because cows in the training data stand on grass (Beery, Van Horn and Perona 2018). These are spurious features, and they are a causal problem, not a capacity problem.
- Shift in production. Monitoring tools detect that inputs changed (mlops 07). Causal reasoning tells you whether the change matters: under covariate shift in a causal task the old is still right; under label shift it is not, but it can be corrected without new labels.
- Domain generalization and robustness. Group DRO, invariant risk minimization and last-layer retraining are used to make models robust to spurious correlations, for example for minority groups in medical imaging and fairness benchmarks.
- Recommenders, ads, search and credit. Every logged dataset was produced by an old policy. Offline evaluation of a new ranking or bidding policy, and unbiased learning to rank, use the importance weights of this lesson every day.
- Decision making. Targeting by predicted churn or purchase is not the same as targeting by effect (uplift, lesson 08).
1. Predict first #
2. The picture #
2.1 A spurious feature #
Take a tabular version of the Waterbirds benchmark (Sagawa et al. 2020). The label is the bird type. A core feature is caused by the label: it is or plus noise, and it predicts the label with accuracy about everywhere. A spurious feature (the background) is linked to the label only through how the data were collected: in training, background and bird type agree with probability . A spurious feature is a feature that predicts the label in the training distribution, but not because of a stable causal mechanism; its link to the label can change when the data collection changes.
Start with "link flips". Points are colored by label (blue , orange ). The magenta boundary belongs to logistic regression on both features, the aqua dashed boundary to the model with the core feature only. In training the magenta model reaches about 0.94; on test data where the link flips it falls below 0.5, worse than a coin. The core-only model stays near 0.84. Now choose "strong shortcut" (no shift): the magenta model is accurate on average, but its worst group (birds on the "wrong" background) is near 0.4. Choose "no shift" with : the weight of drops to about 0.
The answer to question 1: far below 84%. The training data say, correctly, that the background predicts the label. More data from the same source only estimates this association more precisely. The model is not overfitting; it learns the training distribution well, and the training distribution contains a link that the deployment distribution does not.
A pneumonia classifier uses a text token printed by the portable X-ray machine. Portable machines are used for the sickest patients. What kind of association does the token carry?
The token is a descendant of a common cause (patient severity), so it is associated with the label through a backdoor-like path, not through a mechanism of the disease. With more data the association is estimated more precisely, not removed. It breaks in a hospital that uses portable machines for other patients.
2.2 A shift is an intervention on one mechanism #
An SCM factorises the joint distribution into mechanisms, one per variable: if (causal learning: we predict an effect from its cause), and if (anticausal learning: we predict a cause from its effects, like a diagnosis from symptoms). The principle of independent mechanisms (Schölkopf et al. 2012) says that a change in one mechanism does not change the others. A distribution shift is then an intervention on one mechanism.
Move the shift slider. The top chart shows (blue) and (orange), dashed before and solid after the shift. The bottom chart shows . With "X → Y" and "distribution of the cause" (covariate shift), the posterior curve does not move (aqua), and the old threshold stays the best. Switch to "Y → X": now the shift changes (label shift), the posterior moves (magenta), and the best threshold moves away from 0. The table says which factors are fixed and which change. Choose "mechanism of the effect": in both graphs the conditional you wanted to learn changes.
In the figure, with "Y → X" and a shift of , which factor stays fixed?
In the anticausal graph the label is the cause. A change in its distribution leaves the mechanism untouched (independent mechanisms). and both change, because they are built from .
2.3 Invariance across environments #
If we see data from several environments (hospitals, years, countries), each with a different intervention on some variables but not on 's own mechanism, then the regression of on its causal parents is the same in all of them. A set of features that includes a child of , or a variable linked to only through a changing mechanism, gives regressions that differ between environments.
Read the three panels. In each panel, a regression of on one candidate set is fitted separately in three environments; the lines join its coefficients (solid: , dashed: ). Here is the cause of and is a child of whose mechanism changes. Only has the same coefficient everywhere (aqua: accepted by the test, ); the sets with are rejected. has the smallest training error (about 0.48 vs 0.97) but a much larger error in a new environment (about 2.9 vs 1.0). Move the slider to 0.1: with weak differences the test cannot reject much, and ICP returns the empty set: no conclusion, but no wrong one.
In the figure at full strength, the set has the lowest training error. Why is it not the best choice for a new environment?
With 600 points, three coefficients do not overfit. predicts well in training because , but changes with the environment. A rule that uses relies on the training value of ; in a new environment with another its error grows. The coefficient on the parent is the same in every environment.
3. Definitions and main results #
3.1 Spurious features and shortcut learning #
A learner that minimizes the expected loss on converges to the best predictor for , for example for the log loss. If carries information about in , the best predictor uses it. Nothing in the loss says "use only stable mechanisms". So:
Fact. A spurious feature is used because it is predictive in the training distribution. More data from the same distribution, stronger models or better regularization do not remove it. Only a change of the data (other environments, balanced groups, augmentation that breaks the link) or of the objective (robust or invariant objectives) does.
Shortcut learning (Geirhos et al. 2020) is the name in deep learning: networks pick the simplest rule that works on the training set (texture instead of shape, a watermark, a hospital token), and fail on data where the shortcut does not hold.
Measuring it. Split the data into groups by label and spurious attribute. The worst-group accuracy is . Average accuracy can be high while the minority groups (where the spurious attribute disagrees with the label) are badly served. Report both.
Tools that help (they need the group labels, at least on a validation set):
- Reweighting or subsampling so that every group has the same weight in the training loss.
- Group DRO (Sagawa et al. 2020): minimize the largest group loss, , with strong regularization.
- Last-layer retraining (Kirichenko, Izmailov and Wilson 2022): keep the learned features, retrain only the last linear layer on a small group-balanced set. Often enough, because the core features are usually already present in the representation.
- Augmentation that changes the spurious attribute and keeps the label (new backgrounds, swapped tokens), which is counterfactual data augmentation (lesson 09).
3.2 Distribution shift as an intervention #
Definitions. With and at deployment:
- Covariate shift: , .
- Label shift (prior shift): , .
- Concept shift: (or ): the mechanism itself changes.
Theorem (stability of the causal mechanism). If with no hidden common cause, and the shift is an intervention on the mechanism of only, then : covariate shift. If and the shift is an intervention on the mechanism of only, then : label shift.
Proof. In the SCM , with , the conditional is the distribution of , which depends only on and . An intervention on the mechanism of changes or , not or . The anticausal case is the same with the roles exchanged.
Now question 2 of section 1: if the new hospital differs only in the distribution of the risk factor (the cause), is unchanged, and a well-specified model need not be retrained. Two warnings. (1) If the model is misspecified or the new lie outside the training range, the fit there is poor; reweighting training points by (Shimodaira 2000) focuses the fit on the new region. (2) If a hidden variable affects both and and its distribution changes, changes too; the theorem needs the shift to touch only the mechanism of .
Correcting label shift. Under label shift, Bayes' rule gives the new posterior from the old one without new labels:
Proof. . Normalize over .
The new prevalence can be estimated from unlabeled deployment data, for example with black-box shift estimation (Lipton, Wang and Smola 2018), which inverts the confusion matrix of the classifier.
A classifier trained with balanced classes () outputs . In deployment the prevalence is and the shift is label shift. What is the corrected probability?
and . The new posterior is . Multiplying by forgets the normalization.
3.3 Invariance: ICP and IRM #
Invariance principle. Let be the set of causal parents of . If the environments come from interventions on variables other than (and there are no hidden confounders of ), then
So is the same in every environment.
Invariant causal prediction (ICP; Peters, Bühlmann and Meinshausen 2016) turns this into a test.
- For every subset of the features, test the null hypothesis " is the same in all environments" (in the linear case: the same coefficients and the same residual variance; for example a Chow F-test, as in the figure).
- Output the intersection of all accepted sets, .
Theorem (coverage). If the invariance assumption holds and each test has level , then : with high probability ICP outputs only causal parents.
Proof. satisfies the null hypothesis, so it is accepted with probability at least . When it is accepted, the intersection of the accepted sets is a subset of .
ICP can say "I don't know" (the empty set) when the environments are too similar. It needs many tests ( subsets), so it is used with few features or after a preselection.
Invariant risk minimization (IRM; Arjovsky, Bottou, Gulrajani and Lopez-Paz 2019) turns invariance into a training objective for a representation and a classifier : find such that the same is optimal in every environment. The practical version (IRMv1) is
where the penalty is small when the scalar classifier is already optimal in environment .
What is known about the limits.
- Rosenfeld, Ravikumar and Risteski (2021): in a linear model IRM recovers the invariant predictor only with more environments than spurious dimensions; in nonlinear models it can fail and behave like ERM.
- Gulrajani and Lopez-Paz (2020): on standard domain-generalization benchmarks, careful ERM (plain training with good model selection and augmentation) matches most specialised methods.
- Invariance gives robustness to large or new shifts; under small shifts a non-causal predictor can be more accurate (try a slider value of 0.3 in the figure: the set with is still better in that new environment). Choose by the shifts you expect.
3.4 Decisions need effects, and logs are biased #
Prediction vs effect. A churn model ranks customers by . A retention offer should go to customers with the largest effect of the offer on churn (lesson 08). Customers who will surely leave, or surely stay, may have .
Selection bias in logged data. A deployed model decides which outcomes we see:
- A credit model sees repayment only for approved loans. A new model trained on approved loans learns , not . If the old approval used information that is not in (an interview, a branch manager's judgement), these differ: this is the selective labels problem (Lakkaraju et al. 2017).
- A recommender sees clicks only on items it showed, mostly items its old version liked. A model trained on these logs inherits the old policy's choices, and the feedback loop gets stronger with each retraining.
In graph terms, "observed" is a collider or a descendant of the old decision. The fixes are causal: randomize a small share of decisions (exploration), log the probability of every decision, and reweight.
3.5 Off-policy evaluation #
We have a log produced by a logging policy : , , . We want the value of a target policy without deploying it. This is off-policy evaluation (OPE). It is the causal question "what would the mean reward be under ?".
Assumptions.
- No unmeasured confounding: chose using only the logged (true when the system logs everything its policy used).
- Overlap: wherever .
- The logging probabilities are recorded (or can be computed exactly).
Estimators. With the importance weight and a reward model :
- Direct method (DM): . Low variance; biased when is wrong, especially for actions rarely logged.
- Inverse propensity scoring (IPS): .
- Self-normalized IPS (SNIPS): (Swaminathan and Joachims 2015). Small bias, usually much smaller variance, and always inside the range of the rewards.
- Doubly robust (DR): (Dudík, Langford and Li 2011): the DM plus an IPS correction of its errors.
Theorem (IPS is unbiased). Under assumptions 1–3, .
Proof. One term is enough, because the rows are identically distributed.
- . Assumption 1 lets us use for the logged actions.
- Overlap lets us cancel for every with ; the other actions have weight 0 in both sides.
- So .
This is the same computation as for IPW in lesson 05, and as importance sampling in probability 14.
Theorem (double robustness). is unbiased if the weights are correct (any ), or if (and then the weights may be wrong).
Proof. Write the expectation of one DR term as . With correct weights the second part equals, as in the IPS proof, ; the terms cancel and is left. With , , so the second part is 0 for any weights, and the first part is .
Variance and overlap. For a deterministic target policy, on the rows where the logged action agrees with , and 0 elsewhere. If , one matching row has weight 50. The estimate then depends on a few rows. The effective sample size measures how many rows really count. Now question 3 of section 1: IPS stays unbiased, but its variance is huge; a few rewards multiplied by 50 decide the number. Clip weights (bias), use SNIPS or DR, or log with more exploration.
Press "Run 200 logs", then move the first slider. Each histogram shows one estimator over 200 simulated logs; the aqua line is the true value . The logging policy prefers an old favourite action with probability ; the target policy picks other actions. The direct method uses a reward model that ignores the context: its spread is small, but it is centered near 0.45, far from the truth. IPS, SNIPS and DR are centered on the truth. Move to 0.95: the largest weight grows to 40, the effective sample size of a log of 500 falls to about 13, and the standard deviation of IPS is about 0.2. SNIPS and DR are less noisy.
The logging policy never shows action in context (), and the new policy would show it there. What can IPS do?
Overlap fails. Rows with never appear, so the sum in the IPS proof misses the term for any . DR falls back on there, which is only as good as its extrapolation. The fix is exploration: log with for every action the new policies might take.
Position bias and learning to rank. In search and recommendation, a click needs two things: the user examined the item and found it relevant. Users examine top positions more often, so raw clicks underestimate the relevance of items shown low. Unbiased learning to rank (Joachims, Swaminathan and Schnabel 2017) weights each click by , an IPS weight, with the examination propensities estimated from small randomized swaps of results.
3.6 A checklist for causal questions in ML projects #
- Write the question as an estimand. "Effect of the new ranking on 7-day retention, averaged over active users" (), or "value of policy " (). Not "does the feature matter?".
- Draw the graph. Include how the data were collected: which past decisions selected the rows, and which variables the old system used.
- Choose a design, experiment first. A randomized A/B test answers most launch questions; use it when you can (mlops 06, probability 12). Otherwise: adjustment with logged propensities, OPE, or a natural experiment (lessons 05–07).
- Check what can be checked. Overlap and weights (ESS), balance of covariates, pre-trends, worst-group metrics, behavior in held-out environments.
- Do a sensitivity analysis for what cannot be checked (unmeasured confounding, lesson 05).
- Report the assumptions next to the number, and log propensities from now on, so the next analysis is easier.
4. Worked example #
(a) Off-policy evaluation by hand. Two contexts , three actions. The logging policy is for actions in both contexts. The target policy picks when and when . The true mean rewards are and , so (with equally likely contexts) . An old reward model gives and . The log has 8 rows:
| row | |||||||
|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 2 | 0 | 0.6 | 0.5 |
| 2 | 0 | 2 | 1 | 2 | 4 | 0.6 | 0.6 |
| 3 | 0 | 0 | 0 | 2 | 0 | 0.6 | 0.3 |
| 4 | 0 | 1 | 0 | 2 | 0 | 0.6 | 0.5 |
| 5 | 1 | 0 | 1 | 0 | 4 | 0.5 | 0.5 |
| 6 | 1 | 1 | 0 | 0 | 0 | 0.5 | 0.4 |
| 7 | 1 | 0 | 0 | 0 | 4 | 0.5 | 0.5 |
| 8 | 1 | 2 | 0 | 0 | 0 | 0.5 | 0.3 |
The weight is when the logged action is the one would take (rows 2, 5, 7), and 0 otherwise.
- DM: the mean of the column : .
- IPS: . Unbiased in expectation, but with only three matching rows this log gives a value above the largest possible mean reward.
- SNIPS: .
- DR: the corrections are (row 2), (row 5) and (row 7). Their mean is . .
- ESS: . Only three rows carry the estimate.
With 8 rows every estimate is noisy; the figure shows their behavior over many logs.
(b) Label shift. A spam filter was trained with 50% spam. In a new mailbox 20% of mail is spam, and the mail of each class looks the same as before (label shift). For a message with : , , and . The decision at threshold 0.5 flips from "spam" to "not spam".
5. In code #
NumPy checks the worked examples and shows a spurious feature with scikit-learn.
import numpy as np
from sklearn.linear_model import LogisticRegression
# (a) off-policy evaluation of the 8-row log
p0 = np.array([0.25, 0.5, 0.25]) # logging policy, same in both contexts
pi = {0: 2, 1: 0} # target policy (deterministic)
qhat = {0: [0.3, 0.5, 0.6], 1: [0.5, 0.4, 0.3]} # old reward model
log = [(0, 1, 1), (0, 2, 1), (0, 0, 0), (0, 1, 0), (1, 0, 1), (1, 1, 0), (1, 0, 0), (1, 2, 0)]
x, a, r = (np.array(c) for c in zip(*log))
w = np.array([1 / p0[ai] if ai == pi[xi] else 0.0 for xi, ai in zip(x, a)])
q_pi = np.array([qhat[xi][pi[xi]] for xi in x])
q_a = np.array([qhat[xi][ai] for xi, ai in zip(x, a)])
dm, ips = q_pi.mean(), np.mean(w * r)
snips, dr = (w * r).sum() / w.sum(), np.mean(q_pi + w * (r - q_a))
print(round(dm, 3), round(ips, 3), round(snips, 3), round(dr, 3)) # 0.55 1.0 0.667 0.75
print(w.sum() ** 2 / (w ** 2).sum()) # 3.0 (effective sample size)
# (b) label shift correction
p, w1, w0 = 0.7, 0.2 / 0.5, 0.8 / 0.5
print(round(p * w1 / (p * w1 + (1 - p) * w0), 3)) # 0.368
# (c) a spurious feature: train with agreement rho = 0.9, test with rho = -0.8
rng = np.random.default_rng(0)
def gen(n, rho):
y = rng.integers(0, 2, n)
s = np.where(rng.uniform(size=n) < (1 + rho) / 2, y, 1 - y) # spurious attribute
X = np.column_stack([(2 * y - 1) + rng.normal(size=n), (2 * s - 1) + 0.5 * rng.normal(size=n)])
return X, y, s
Xtr, ytr, _ = gen(20000, 0.9)
Xte, yte, ste = gen(20000, -0.8)
both = LogisticRegression().fit(Xtr, ytr)
core = LogisticRegression().fit(Xtr[:, :1], ytr)
print(round(both.score(Xtr, ytr), 2), round(both.score(Xte, yte), 2)) # 0.95 0.46
print(round(core.score(Xtr[:, :1], ytr), 2), round(core.score(Xte[:, :1], yte), 2)) # 0.84 0.84
pred = both.predict(Xte)
print(min(np.mean(pred[(yte == g) & (ste == h)] == g) for g in (0, 1) for h in (0, 1)) < 0.4) # True
The model with both features is better in training (0.95 vs 0.84) and much worse after the shift (0.46 vs 0.84). Its worst group on the shifted test set is below 0.4.
6. Where it shows up #
- Medical imaging. Models pick up scanner type, hospital tokens, rulers in skin-lesion photos or chest drains in X-rays. Multi-site validation, worst-group reporting and stratified evaluation by acquisition site are now expected in good studies.
- Recommendation, ads and search. Offline evaluation of new policies with IPS, SNIPS and DR on logs that record propensities; small randomized exploration traffic keeps overlap; unbiased learning to rank corrects position bias.
- Credit and hiring. Selective labels (outcomes only for approved applicants) and feedback loops; reject inference, randomized approvals of a small share, and fairness audits with causal models.
- Robustness benchmarks. WILDS, Waterbirds, CelebA and colored-MNIST measure worst-group accuracy and out-of-distribution performance; methods include group DRO, IRM, JTT and last-layer retraining.
- Monitoring. Drift detectors (mlops 07) say that inputs changed; the causal view says whether the old is still right (covariate shift in a causal task) or needs a prior correction (label shift).
- ML for science. In genomics and Earth science, data come from many labs, sites or years; invariance across these environments is used to find stable predictors and causal genes (ICP was introduced with gene knockout data). In climate modeling, emulators trained on one scenario are tested on others, which is a shift of the cause (the forcing).
7. Common mistakes #
- "More data will fix the spurious feature." It will not: the association is real in the training distribution. Check with worst-group accuracy and data from another environment.
- Reporting only average accuracy. A model can be 94% accurate on average and below 40% on a minority group. Report worst-group or per-group metrics.
- Treating every shift as covariate shift. In anticausal tasks (diagnosis from images) a prevalence change is label shift; importance weighting on is then the wrong correction. Ask which mechanism changed.
- Dropping a feature and calling the model robust. Other features can carry the same spurious signal (proxies). Test on shifted environments.
- Evaluating a new policy on logs as if they were random. Training or testing on logs from the old policy without weights measures how well the new policy agrees with the old one. Log propensities and use IPS/DR.
- Not logging propensities, or estimating them badly. IPS needs the probability the old system gave to the action it took. If the system was deterministic, there is no overlap: add exploration.
- Trusting an IPS number with a tiny ESS. Look at the largest weights and the effective sample size; use SNIPS or DR, and report a confidence interval (bootstrap over rows).
- Targeting with a risk model when the decision needs an effect. Use uplift models (lesson 08) or an experiment.
8. Check yourself #
- In the spurious-feature figure, why does the model with both features have a worst-group accuracy near 0.4
even when the test distribution equals the training distribution?
Answer
With the background agrees with the label 95% of the time and is less noisy than the core feature. The model gives it a large weight. In the minority groups (background disagrees with the label) the large weight on pushes the decision to the wrong side, so most of these units are misclassified. They are only 5% of the data, so the average accuracy stays high. - A model predicts crop yield from rainfall (a cause). Next year is much drier. Which part of the data
distribution changes, and what is the risk for a linear model fitted last year?
Answer
changes; stays the same if nothing else changed (covariate shift). The risk is extrapolation: the dry region had few training points, so a misspecified model (linear where the true curve bends) can be wrong there. Reweighting by or a more flexible model helps; itself is still the right target. - Three environments: the regression of on has coefficients 1.02, 0.98, 1.01; on the
coefficients of are 0.2, 0.9, −0.4 and the test rejects. On the coefficients are stable and
accepted. What does ICP output, and what does it mean?
Answer
Suppose the empty set and the other sets are rejected. The accepted sets are and , and their intersection is . ICP claims, with probability at least , that is a causal parent of . It says nothing about : it may be a parent or not. - Show that SNIPS equals IPS when , and explain why SNIPS can never be above the largest reward.
Answer
. SNIPS is a weighted average of the rewards with non-negative weights that sum to 1, so it lies between the smallest and the largest reward. IPS divides by instead and can leave this range (1.0 in the worked example, with only three matching rows). - A credit model is trained on approved loans only. When can it still estimate for all
applicants without bias?
Answer
When approval depended only on the logged features and every region of had some approvals (overlap). Then (selection on observables). If approval used information not in , or some regions were never approved, the two differ and the model is biased for the rejected population. - In the off-policy figure, why is DR centered on the truth although it uses the same wrong reward model as DM?
Answer
The logging probabilities are known exactly, so the weights are correct. Then the correction term has mean , which removes the bias of (double robustness). DR keeps part of DM's low variance because the residuals are smaller than .
What is a spurious feature?
A feature that predicts the label in the training distribution through a non-causal link (a common cause or selection), so its link to the label can change when the data collection changes.
Why does more training data from the same source not remove a spurious feature?
The association is real in that distribution, so the best predictor for it uses the feature; more data only estimates the association better.
What is worst-group accuracy?
The minimum accuracy over groups defined by the label and the spurious attribute, .
Causal vs anticausal learning: which conditional is stable under a shift of the cause?
If , a shift of leaves fixed (covariate shift). If , a shift of leaves fixed (label shift).
How do you correct a classifier's probabilities for label shift?
with , then normalize over .
State the invariance principle used by ICP.
For the causal parents of , is the same in every environment that does not intervene on .
What does IRM look for?
A representation such that the same classifier on top of it is optimal in every training environment.
Write the IPS estimator of a policy's value.
.
What is the doubly robust OPE estimator, and when is it unbiased?
; unbiased if the weights are correct or the reward model is correct.
What is selection bias in logged feedback?
Outcomes are observed only for the actions the old system took (approved loans, shown items), so a model trained on the logs learns the outcome given selection, not for everybody.
9. Interview angle #
- "Your model works offline but fails after launch. How could causality explain it?" — The offline test set came from the same distribution as training, so spurious features (proxies of the collection process) looked good. After launch the mechanism that created the spurious link changed (new site, new device, new policy), or the model's own decisions changed the data (feedback loop). Check per-group metrics, compare environments, ask which mechanism changed, and test on a held-out environment before launch.
- "How do you evaluate a new recommender policy without an A/B test?" — Off-policy evaluation on logs from the current policy: IPS, SNIPS or DR with the logged propensities. Assumptions: the old policy used only logged features, overlap, recorded propensities. Look at the ESS and the largest weights; if overlap is poor, the answer is an A/B test or more exploration traffic.
- "Covariate shift or label shift: how do you tell, and why does it matter?" — Ask the causal direction. For diagnosis-type tasks (label causes features) a prevalence change is label shift: re-weight the posterior by , estimating from unlabeled data (BBSE). For prognosis-type tasks it is covariate shift: is fine, watch extrapolation.
- "A churn model or an uplift model for retention offers?" — Uplift: the offer should go to customers whose churn it changes most, which needs the effect, from a randomized campaign.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution:
- A Waterbirds-like tabular dataset: train logistic regression with and without the spurious feature, compute worst-group accuracy on a shifted test set, then reweight the groups and compare.
- Covariate shift in a causal and in an anticausal SCM: measure the drop in accuracy, and correct the anticausal classifier for label shift with Bayes' rule.
- A minimal invariant causal prediction: fit OLS on every candidate set in every environment, test equality with a Chow F-test, and return the intersection of the accepted sets.
- Off-policy evaluation: implement DM, IPS, SNIPS and DR on a simulated contextual bandit, and measure bias and standard deviation as overlap gets worse.
- Selection bias in logged data: train a credit model only on approved loans and compare it with a model trained on everybody.
11. Watch and read #
- Schölkopf et al. (2021), Toward causal representation learning: a survey of causality and machine learning.
- Schölkopf et al. (2012), On causal and anticausal learning.
- Geirhos et al. (2020), Shortcut learning in deep neural networks.
- Beery, Van Horn and Perona (2018), Recognition in terra incognita.
- Sagawa, Koh, Hashimoto and Liang (2020), Distributionally robust neural networks for group shifts.
- Kirichenko, Izmailov and Wilson (2022), Last layer re-training is sufficient for robustness to spurious correlations.
- Peters, Bühlmann and Meinshausen (2016), Causal inference using invariant prediction.
- Arjovsky, Bottou, Gulrajani and Lopez-Paz (2019), Invariant risk minimization; Rosenfeld, Ravikumar and Risteski (2021), The risks of invariant risk minimization; Gulrajani and Lopez-Paz (2020), In search of lost domain generalization.
- Lipton, Wang and Smola (2018), Detecting and correcting for label shift with black box predictors.
- Dudík, Langford and Li (2011), Doubly robust policy evaluation and learning.
- Joachims, Swaminathan and Schnabel (2017), Unbiased learning-to-rank with biased feedback.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.