Machine learning

Week 10: evaluation, distribution shift and deployment

A model wins a prediction competition. What has it shown, and what has it not?

Where we left off

Prediction competition: curated data, the same for every competitor; a task; an agreed score; an evaluation dataset the competitors cannot see. Winning model chosen by best score

The Netflix prize went to a blend that was never put into production

Winning a competition is not always useful

Today, what a winning score does and does not tell us:

  • how variable the leaderboard is
  • what happens when the data the model meets are not like the data it was scored on
  • what the score leaves out

Evaluation, distribution shift and deployment

Part 1: the leaderboard

Part 2: when the data move

Part 3: scores and decisions

Part 1: the leaderboard

Data: patients of a health system

Obermeyer et al. (2019) studied a commercial algorithm that a US health system used to predict patients’ costs, and released synthetic rows that mimic their data: 48,784 patient-years (5,582 Black, 43,202 White)

  • Inputs, from the year before: age band, sex, 34 chronic conditions, 13 kinds of cost, 94 test results and medications (149 columns)
  • Outcomes, the year after: cost, number of active chronic conditions, test results
  • Task: predict whether next year’s cost will be in the top quarter (above $6,800 on the training rows), as a probability \(\hat p(x)\)
  • Score: the Brier score, squared error for a probability, \(\ell(y, \hat p) = (y - \hat p)^2\), between 0 and 1

Split once at random: 16,000 training, 8,000 tuning, 12,000 test, 12,784 kept back for later

CTF competition: the tuning leaderboard

The four models with any structure are within 0.014 of each other, and every bar is about 0.010 wide

Can the same rows separate two models?

The two leaders’ bars overlap. Their scores come from the same 8,000 patients. Can those patients still tell the two models apart?

Score each patient twice and take the difference, \(\Delta_j = \ell\big(y_j, \hat p_A(x_j)\big) - \ell\big(y_j, \hat p_B(x_j)\big)\)

  • The difference of the two scores is \(\bar\Delta\), with standard error \(\mathrm{sd}(\Delta)/\sqrt m\)
  • \(\mathrm{Var}(\ell_A - \ell_B) = \mathrm{Var}(\ell_A) + \mathrm{Var}(\ell_B) - 2\,\mathrm{Cov}(\ell_A, \ell_B)\): the models err on mostly the same patients, so the covariance is large

boosted trees minus lasso: \(\bar\Delta = -0.0021\), standard error 0.0008, against 0.0025 for one score alone

The pair to compare on the test rows: boosted trees against lasso, chosen now

A score and its risk

A score is a mean of \(m\) losses, \(\hat R = \frac1m\sum_j \ell_j\), with mean \(R\), the risk

A loss between 0 and 1 has variance at most \(\frac14\), so \(\mathrm{Var}(\hat R) \le \frac{1}{4m}\)

If \(\hat R\) were normal with that variance: \(P\big(|\hat R - R| \ge t\big) \le 2e^{-t^2/(2\sigma^2)}\) with \(\sigma^2 = \frac{1}{4m}\), which is \(2e^{-2mt^2}\)

\(m = 50\) losses of 0 or 1

The central limit theorem makes the normal shape plausible, but does not control the far tail at a fixed \(m\)

Hoeffding’s inequality

Hoeffding’s inequality (stated). If \(Z_1, \ldots, Z_m\) are independent with \(0 \le Z_i \le 1\) and \(\bar Z\) is their mean, then for every \(t > 0\) and every \(m\), \(P\big(|\bar Z - \mathbb E\bar Z| \ge t\big) \le 2e^{-2mt^2}\)

Why it holds for every \(m\):

  1. Markov’s inequality on \(e^{\lambda D}\), \(D = \bar Z - \mathbb E\bar Z\); by independence, \(\mathbb E\big[e^{\lambda D}\big]\) is a product of \(m\) factors
  2. Hoeffding’s lemma (stated): each factor is at most what a normal with variance \(\frac14\) would give; then choose \(\lambda\)

\(K\) models fixed in advance, by the union bound: every score within \(t_K = \sqrt{\log(2K/\delta)/(2m)}\) of its risk, with probability \(1 - \delta\). Here \(t_K = 0.018\): gaps above \(2t_K\) are resolved for 1 of the 10 pairs, against a paired standard error of 0.0008

The test rows, opened once

Decided before opening: boosted trees against lasso, the paired difference with two standard errors

boosted trees lasso difference ± 2 SE
tuning 0.147 0.149 -0.0021 ± 0.0015
test 0.145 0.147 -0.0023 ± 0.0012

The selected candidate’s score is biased low: the winner of \(K\) noisy scores was partly lucky. A test set scored once, for models fixed before it is opened, has no such bias

The leader scored 0.147 on the tuning rows and 0.145 on the test rows: with \(K = 5\) and \(m = 8{,}000\), no sign of the bias

Resampling the test rows

A program can enroll only the 3% with the highest scores. Of those 360 test patients, the share with top-quarter cost is 84.7% for boosted trees and 82.5% for lasso

Which patients are in the top 3% depends on every patient’s score. This number is not an average of per-patient losses. What replaces \(\mathrm{sd}/\sqrt m\)?

Bootstrap the test rows: draw \(m\) rows with replacement, recompute the difference, repeat \(B\) times, and read off the spread. Each drawn row keeps both models’ predictions, so the comparison stays paired

90% bootstrap interval for the difference: -0.6 to 5.3 percentage points, so this number does not separate them. The models are held fixed: the interval says nothing about refitting, and nothing about how the pair was chosen

Scores that move

Adaptive drift (stated). If the candidates depend on earlier scores on the same rows (tune, look, tune again), the union bound no longer covers them, and the score can be driven away from the risk. A test set scored once, for models fixed before, does not move

Recht et al. (2019) built new test sets for CIFAR-10 and ImageNet to the original recipe. Accuracy fell for every model, many by about 10 percentage points (the best ImageNet model in their Table 1 from 82.9% to 72.2%), with the order of the models almost unchanged. They split the drop into three gaps:

\[ \hat R_{\text{old}} - \hat R_{\text{new}} = \underbrace{\hat R_{\text{old}} - R_{\text{old}}}_{\text{adaptivity}} \;+\; \underbrace{R_{\text{old}} - R_{\text{new}}}_{\text{distribution}} \;+\; \underbrace{R_{\text{new}} - \hat R_{\text{new}}}_{\text{sampling}} \]

and found it was mostly the distribution: slightly harder images. On 120 Kaggle competitions, public and private leaderboards agreed closely (Roelofs et al. 2019)

Part 2: when the data move

In distribution and out of distribution

Fit to 142 countries in 2002, tested on the same countries in 1997: has it predicted anything new?

Built from the patients kept back: a sicker population (kept with a probability rising with last year’s chronic conditions), and one with high cost twice as common (every high-cost patient kept, a third of the others)

Model Tuning rows Sicker population High cost twice as common
boosted trees 0.147 0.164 0.235
lasso 0.149 0.165 0.244
forest 0.150 0.165 0.255
tree 0.160 0.178 0.261
baseline 0.185 0.212 0.305

Covariate shift

The new patients’ costs are not known yet. What is a model’s risk on them?

\(p_{\text{test}}\): where the model will be used. \(r(x) = \mathbb E[\ell(Y, f(X)) \mid X = x]\), \(w(x) = p_{\text{test}}(x)/p_{\text{train}}(x)\)

\[ \begin{alignedat}{2} R_{\text{test}}(f) &= \mathbb E_{\text{test}}\big[r_{\text{test}}(X)\big] &\quad& \color{gray}\small\text{tower property} \\[2pt] &\class{fragment}{{}= \mathbb E_{\text{test}}\big[r_{\text{train}}(X)\big]} && \class{fragment}{\color{gray}\small\text{covariate shift: } p_{\text{test}}(y \mid x) = p_{\text{train}}(y \mid x)} \\[2pt] &\class{fragment}{{}= \textstyle\int r_{\text{train}}(x)\, w(x)\, p_{\text{train}}(x)\, dx} && \class{fragment}{\color{gray}\small\text{needs } p_{\text{train}}(x) > 0 \text{ wherever } p_{\text{test}}(x) > 0} \\[2pt] &\class{fragment}{{}= \mathbb E_{\text{train}}\big[w(X)\, \ell(Y, f(X))\big]} && \class{fragment}{\color{gray}\small\text{tower property again}} \end{alignedat} \]

Inverse propensity weighting: weight \(1/\pi(Z)\), needing \(0 < \pi(Z) < 1\)

Reweighting the tuning rows

The covariate-shift identity on the tuning rows, \(\frac1m\sum_j w(x_j)\,\ell_j\), against the score on the sicker population itself:

Model Tuning rows Reweighted tuning rows Sicker population
boosted trees 0.147 0.163 0.164
lasso 0.149 0.164 0.165
forest 0.150 0.166 0.165
tree 0.160 0.182 0.178
baseline 0.185 0.219 0.212

The weights are needed to evaluate a fixed model’s risk on the new population. Whether to fit with them is a separate question

The weights add variance: for boosted trees, the reweighted score has standard error 0.0031, against 0.0025 unweighted

Label shift

If \(p(x \mid y)\) is unchanged and the share with \(Y = 1\) moves from \(q_{\text{train}}\) to \(q_{\text{test}}\), Bayes’ rule in odds changes only the last factor:

\[ \begin{aligned} \frac{P(Y = 1 \mid X = x)}{P(Y = 0 \mid X = x)} &= \frac{p(x \mid 1)}{p(x \mid 0)} \cdot \frac{q}{1 - q} \\[4pt] \operatorname{logit} P_{\text{test}}(Y = 1 \mid X = x) &= \operatorname{logit} P_{\text{train}}(Y = 1 \mid X = x) + \operatorname{logit} q_{\text{test}} - \operatorname{logit} q_{\text{train}} \end{aligned} \]

  • The fix: move the intercept (a recalibration with the slope kept at 1), with \(q_{\text{test}}\) known or estimated
  • With unchanged costs, the optimal threshold on the correct deployment probability is still \(c^\star\); the old score needs a new threshold. The order of patients by score does not change

Accuracy, calibration and ranking under shift

Covariate shift, \(p(y \mid x)\) fixed Label shift, \(p(x \mid y)\) fixed
Risk changes; estimate it by reweighting with \(w(x)\) changes
Calibration kept by a correct model of \(p(y \mid x)\), not always by others lost; move the intercept
Ranking by score (AUC) can change with the mix of patients kept

When the function itself has moved

If \(p(y \mid x)\) changes (a new payment rule, a new treatment, a change in who gets care), neither fix applies: the old rows contain no information about the new relation, and only new outcomes reveal it

Deploying a model can be what moves it: a program that enrolls the predicted high-cost patients changes their costs, and next year’s training rows record a world the model helped make

Causes and effects as inputs

Theory: the distribution of \(Y\) given all its causes is unchanged by interventions that leave \(Y\)’s own mechanism alone, so a model on the causes should travel

Nastl and Hardt (2024), 16 tabular tasks with several domains each (income by region, voting by region, hospital mortality by insurance type, …): models on all features beat models on causal features in and out of domain in every task. Their advice: approximate the best predictor on all the features available

The invariance holds for the true conditional distribution, not for the risk of a model fitted to a few features

Part 3: scores and decisions

An absurdly abbreviated history of optics

  • Ptolemy (100-170) measured refraction of light passing from air to water, altering measurements so they would fit to a quadratic curve (ancient “machine learning” or curve fitting)

  • Ibn Sahl (940-1000) described the correct law, which English speakers refer to as Snell’s law

  • Fermat (1607-1665) proposed the more general “principle of least time” which can be used to derive Snell’s law and solve other optical problems – predict values in different settings

Ptolemy’s curve in glass

Points: Ptolemy’s table, air to water, within 2.2 degrees of Snell’s law, \(\sin i = n \sin r\) with \(n = 1.33\)

In glass the same curve is off by 1.4 degrees at 10 and 9.0 at 80. Snell’s law changes one number, \(n = 1.5\)

Refitted to new measurements, a quadratic would fit glass too. It could not say anything before them

Put the “science” back in “data science”!

Feynman, Lectures on Physics, Vol. 1:

Now in the further development of science, we want more than just a formula. First we have an observation, then we have numbers that we measure, then we have a law which summarizes all the numbers. But the real glory of science is that we can find a way of thinking such that the law is evident.

And from “Cargo Cult Science”:

When you have put a lot of ideas together to make an elaborate theory, you want to make sure, when explaining what it fits, that those things it fits are not just the things that gave you the idea for the theory; but that the finished theory makes something else come out right, in addition.

CTF competition: what it delivered

Donoho (2017) called prediction plus the common task framework machine learning’s “secret sauce”:

  • training data shared by everyone, competitors, and a referee who scores each submitted rule on data hidden from them
  • effort goes to measured performance; many groups compete; judging is impartial and automatic
  • winners arrive already tested, so they look close to deployable

The Netflix prize: the winning blend was never put into production

Outcome reasoning and model reasoning

Rodu and Baiocchi (2023): a competition justifies “Algorithm A performs better than Algorithm B”, not deployment

Two ways to trust a prediction:

  • outcome reasoning: measured performance
  • model reasoning: the model’s structure, checked against what we know

Only the second can be argued before use

Outcome reasoning is enough only if:

  • measurement: future outcomes can be scored
  • adaptability: the model can be updated in time
  • resilience: accumulated errors are tolerable
  • agnosis: conflict with beliefs is tolerable

Each depends on who is asking, the stakeholders

The winner, deployed

The health system uses a cost score to choose who gets extra care: the 3% with the highest scores are enrolled in a program for patients with complex needs

Use the competition’s winner, boosted trees. On the test patients at or above the 97th percentile of its score, the share with top-quarter cost is 81.8% for Black and 85.4% for White patients

The score predicts cost well, and about equally well in both groups. What could still be wrong?

The same score, by health

Left: what the score was trained for, similar in both groups. Right: at the same score, Black patients are sicker. Enrolled: 6.4 active chronic conditions for Black, 4.6 for White patients

Why, in the study: at the same number of chronic illnesses, $1,801 a year less was spent on Black patients (in these rows, $320), so cost understates their need

Another target

Boosted trees with the same settings, trained on other targets. Who is in the top 3% of the test patients:

Target Share Black Mean active conditions Share of next year's cost
Top quarter of cost (the competition) 18.3% 4.92 16.5%
Total cost 21.4% 5.46 17.8%
Avoidable cost 21.9% 5.99 16.9%
Active chronic conditions 26.7% 7.43 15.2%
The commercial score (in the data) 20.0% 5.59 16.5%

11.9% of all test patients are Black. With chronic conditions as the target, the share among those enrolled rises by 9.0 percentage points (90% bootstrap interval 5.3 to 13.1)

The competition fixed the target before anyone competed. Changing it changes who gets care, and no score on the old target can show that

Should this be predicted at all?

For which of these tasks would a model with a better score make things better?

  1. which patients will cost the most next year, to offer them extra care
  2. which defendants will be re-arrested before trial, to decide who is released
  3. which applicants will stay in a job for two years, to decide who is hired
  4. which drivers will claim on their insurance, to set the price they pay

Limits of predictive optimization

The case for prediction: decisions that are consistent, cheap, auditable, and often more accurate than unaided judgment (Wang et al. 2024). Questions a score does not answer:

  • Acting on it: does acting on the prediction help? A decision can change the outcome it was predicted from
  • The target: is it what we care about? Re-arrest is not offending, and cost is not need
  • Predictability: in a mass competition on life outcomes, 160 teams’ best predictions were only slightly better than a simple benchmark (Salganik et al. 2020)
  • Contesting: can the person decided about get an explanation, their data, and a way to correct the decision?

Some predictions are objected to even when they are accurate: pricing car insurance by credit score holds people accountable for things that are not their fault (Kiviat 2019)

More warnings for data about humans

Social science is hard! Health is also (at least partially) social. It is very difficult to predict life outcomes, even with machine learning models and big data

Strategic/adversarial/adaptive behavior: Goodhart’s law / Campbell’s law / Lucas critique / Friedman’s thermostat / Washback effect / Performativity / Reflexivity / Hammer’s law

For these reasons, when dealing with human data:

  • Almost all variables correlate
  • Unconfoundedness assumptions are always wrong
  • Can’t separate “normative vs scientific” (ethics always important)

Remember: focus on what is importantly wrong

Recap

The loss and the target define the problem optimal model theorem; optimal threshold theorem; quantile optimality
Training error underestimates the risk optimism theorem; the selected candidate’s score is biased low
Faster rates need assumptions no free lunch; the k-NN rate
Shrinkage and averaging trade bias for variance bias–variance decompositions; ridge; the correlated-average variance
Prediction is not intervention adjustment theorem; inverse propensity weighting; partial dependence and causal effects
A score is evidence about one target on one distribution, not a license to deploy Hoeffding’s inequality; covariate and label shift; another target

Before the seminar

  • Do the exercises at the top of the seminar notebook before the seminar

Conclusion

The leaderboard

Compare two models on the same rows, paired. Hoeffding’s inequality bounds every score at once for models fixed in advance. Choose the comparison before opening the test rows; resample the rows for anything that is not a mean

When the data move

Covariate shift: reweight by \(p_{\text{test}}/p_{\text{train}}\), where the supports overlap. Label shift: move the intercept. Neither repairs a change in \(p(y \mid x)\)

Scores and decisions

That one model beats another, on one target and one distribution. Whether to deploy it, and whether the target is the right one, are questions the score does not answer

Course survey

A few minutes for the course survey, now

References (1 of 2)

  • Donoho, D. (2017). 50 years of data science. Journal of Computational and Graphical Statistics 26(4), 745–766. doi:10.1080/10618600.2017.1384734. Section 6.
  • Feynman, R. P., Leighton, R. B. and Sands, M. (1963). The Feynman Lectures on Physics, vol. I, chapter 26, Table 26-1 and section 26-3. feynmanlectures.caltech.edu/I_26.html
  • Feynman, R. P. (1974). Cargo cult science. Engineering and Science 37(7), 10–13.
  • Hoeffding, W. (1963). Probability inequalities for sums of bounded random variables. Journal of the American Statistical Association 58(301), 13–30. doi:10.1080/01621459.1963.10500830
  • Kiviat, B. (2019). The moral limits of predictive practices: the case of credit-based insurance scores. American Sociological Review 84(6), 1134–1158. doi:10.1177/0003122419884917
  • Nastl, V. Y. and Hardt, M. (2024). Do causal predictors generalize better to new domains? Advances in Neural Information Processing Systems 37. doi:10.52202/079017-0983
  • Obermeyer, Z., Powers, B., Vogeli, C. and Mullainathan, S. (2019). Dissecting racial bias in an algorithm used to manage the health of populations. Science 366(6464), 447–453. doi:10.1126/science.aax2342. Synthetic data and code: gitlab.com/labsysmed/dissecting-bias

References (2 of 2)

  • Recht, B., Roelofs, R., Schmidt, L. and Shankar, V. (2019). Do ImageNet classifiers generalize to ImageNet? Proceedings of the 36th International Conference on Machine Learning, PMLR 97, 5389–5400. proceedings.mlr.press/v97/recht19a.html
  • Rodu, J. and Baiocchi, M. (2023). When black box algorithms are (not) appropriate: a principled prediction-problem ontology. Observational Studies. muse.jhu.edu/pub/56/article/883478. Sections as numbered in arXiv:2001.07648v4.
  • Roelofs, R., Shankar, V., Recht, B., Fridovich-Keil, S., Hardt, M., Miller, J. and Schmidt, L. (2019). A meta-analysis of overfitting in machine learning. Advances in Neural Information Processing Systems 32. NeurIPS proceedings
  • Salganik, M. J. et al. (2020). Measuring the predictability of life outcomes with a scientific mass collaboration. Proceedings of the National Academy of Sciences 117(15), 8398–8403. doi:10.1073/pnas.1915006117
  • Wang, A., Kapoor, S., Barocas, S. and Narayanan, A. (2024). Against predictive optimization: on the legitimacy of decision-making algorithms that optimize predictive accuracy. ACM Journal on Responsible Computing 1(1), 1–45. predictive-optimization.cs.princeton.edu. Sections as numbered in the draft of 16 February 2023.