Simple Algorithm
Machine Learning · Descent · 22 min

Deployment & a Changing World

Models in production, and the shifts that break them.

A test score is a promise about data that look like the test set. Deployment breaks that promise slowly: customers change, prevalences drift, the model's own decisions reshape the data it will be retrained on. This lesson follows a model into production and gives you the tools to notice, correct and prove things there: shared feature code, importance weights, prior correction, monitoring, A/B tests and honest documentation.

What you’ll learn

  • Compare batch, online and on-device serving, and explain how training–serving skew arises and how to prevent it.
  • Define covariate, label and concept shift through the two factorizations of P(x,y)P(\mathbf x,y), derive the importance-weighting identity, and correct a classifier's probabilities for a new class prior.
  • Show that label shift leaves recall, the false-positive rate and the ROC curve unchanged while precision moves, and estimate a new prevalence from the rate of positive predictions.
  • Design monitoring for inputs, predictions and outcomes, size an A/B test, and explain why peeking and feedback loops mislead.

From a notebook to a service

A trained model is a file of numbers. A deployed model is a service: other software sends it inputs and acts on what comes back, usually with nobody looking at individual predictions. Most systems serve predictions in one of three ways.

Serving patternHow it worksTypical usesMain risks
BatchScore every customer, item or account on a schedule and store the results; lookups are instantnightly churn or credit-limit scores; recommendations precomputed per userpredictions are as old as the last run; new users have none
OnlineCompute the features and a prediction for each request, within a latency budget that is often tens of millisecondsfraud checks at payment time; search and ad rankingevery feature must exist at request time; the slowest 1% of requests (tail latency); cost per prediction
On-deviceShip the model to phones, cars or sensors and predict locallykeyboard suggestions, camera features, offline usememory and energy limits; slow updates; little visibility into real use
Latency and cost shape the model itself. A model too slow or too expensive to serve is often replaced by a smaller one, distilled or compressed from it, trading a little accuracy for speed.

The most common deployment failure is not a bad model but different inputs. Suppose training features come from a cleaned warehouse table and serving features from a live service. A missing income is filled with the training mean on one path and with zero on the other; a timestamp is in local time here and UTC there; a vocabulary was rebuilt on newer data. The model sees a different customer than the one it was trained on. This training–serving skew produces no error message, only a gap between offline and online performance.

The cure is mechanical: fit every data-dependent transformation once, on training data, save it with the model, and run the identical code on both paths. Better still, log the features exactly as they were served and train the next model on those logs.

python
import joblib
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

# Training: every data-dependent step is fitted on training data only
model = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=1000))
model.fit(X_train, y_train)
joblib.dump(model, "model-v7.joblib")   # the scaler's statistics travel with the weights

# Serving: the same object transforms and predicts
model = joblib.load("model-v7.joblib")

def score(row):                          # row: one example, same columns as X_train
    return model.predict_proba([row])[0, 1]

The means and standard deviations inside the scaler are part of the model. Recomputing them on serving traffic would quietly change every prediction.

Check your understanding

A model scored AUC 0.91 on a held-out test set from last month. In its first week of serving, on the same kind of traffic, it scores 0.78 once outcomes arrive. What should you check first?

  1. Whether the model overfit, by retraining with stronger regularization
  2. Whether the prevalence of positives changed
  3. Whether the serving code computes every feature exactly as the training code did
  4. Nothing: online metrics are always lower than offline ones
Show the answer

C. Whether the serving code computes every feature exactly as the training code did

A sudden drop with no change in the population points at the inputs. Compare logged serving features with recomputed training features for the same examples; skew in a single important feature can cost this much.

Three ways the data can shift

The test set estimated performance under the training distribution, call it the source PsP_s. Deployment draws from a target PtP_t. Any difference is distribution shift, and the two ways of factorizing a joint distribution name the standard cases:

P(x,y)  =  P(x) P(y∣x)  =  P(y) P(x∣y)P(\mathbf x,y)\;=\;P(\mathbf x)\,P(y\mid\mathbf x)\;=\;P(y)\,P(\mathbf x\mid y)
Each kind of shift changes one factor and keeps the conditional next to it.
ShiftChangesStays fixedExample
Covariate shiftP(x)P(\mathbf x)P(y∣x)P(y\mid\mathbf x)a diagnostic model built at a referral hospital meets a clinic's younger, milder patients; for any given patient record, the chance of disease is the same
Label (prior) shiftP(y)P(y)P(x∣y)P(\mathbf x\mid y)flu season: far more patients have flu, but flu still produces the same symptoms
Concept shift (concept drift)P(y∣x)P(y\mid\mathbf x)nothing is guaranteeda recession: applicants with the same profile default more often; a new rule changes what counts as fraud
Real shifts mix these, and add changes that fit none of them: a sensor upgrade, a renamed category, a feature that silently stops being logged.

Covariate and label shift each keep one conditional distribution fixed, and that fixed piece is what lets you correct them with unlabeled production data, as the next step shows. Under concept shift the input–output relationship itself has moved. Unlabeled data cannot reveal how, and only new labels help.

Think first A spam filter's precision falls after spammers start copying the wording of legitimate newsletters. Which factor of P(x,y)P(\mathbf x,y) changed, and can unlabeled email alone fix the filter?

The class-conditional P(x∣spam)P(\mathbf x\mid\text{spam}) changed, and with it P(y∣x)P(y\mid\mathbf x): emails with newsletter wording are now more often spam than before. That is concept shift for the filter. Unlabeled email shows that inputs changed, but not which of them are spam, so the fix needs fresh labels (user reports, a labeling queue) and retraining. Adversarial settings like spam and fraud drift this way by design.

Correcting covariate and label shift

DerivationImportance weighting
  1. Rt(h)=∬ℓ(h(x),y) p(y∣x) pt(x) dy dx=∬ℓ(h(x),y) p(y∣x) pt(x)ps(x) ps(x) dy dxR_t(h)=\iint\ell(h(\mathbf x),y)\,p(y\mid\mathbf x)\,p_t(\mathbf x)\,dy\,d\mathbf x=\iint\ell(h(\mathbf x),y)\,p(y\mid\mathbf x)\,\frac{p_t(\mathbf x)}{p_s(\mathbf x)}\,p_s(\mathbf x)\,dy\,d\mathbf x

    Assume covariate shift, Pt(y∣x)=Ps(y∣x)P_t(y\mid\mathbf x)=P_s(y\mid\mathbf x), and overlap: ps(x)>0p_s(\mathbf x)>0 wherever pt(x)>0p_t(\mathbf x)>0. Write the target risk of a predictor hh as an integral, then multiply and divide by ps(x)p_s(\mathbf x):

  2. Rt(h)=E(x,y)∼Ps[w(x) ℓ(h(x),y)] ≈ 1n∑i=1nw(xi) ℓ(h(xi),yi)R_t(h)=\E_{(\mathbf x,y)\sim P_s}\big[w(\mathbf x)\,\ell(h(\mathbf x),y)\big]\ \approx\ \frac1n\sum_{i=1}^nw(\mathbf x_i)\,\ell\big(h(\mathbf x_i),y_i\big)

    The importance weight w(x)=pt(x)/ps(x)w(\mathbf x)=p_t(\mathbf x)/p_s(\mathbf x) turns a target expectation into a source expectation, which the labeled training data can estimate:

  3. neff=(∑iwi)2∑iwi2 ≤ nn_{\text{eff}}=\frac{\big(\sum_iw_i\big)^2}{\sum_iw_i^2}\ \le\ n

    Minimizing the weighted empirical risk is importance-weighted ERM. The estimate is unbiased for every fixed hh, but a few huge weights make it noisy. The effective sample size of a weighted average counts how many equally weighted examples would give the same variance:

  4. pt(y∣x)=w(y) ps(y∣x)∑y′w(y′) ps(y′∣x)p_t(y\mid\mathbf x)=\frac{w(y)\,p_s(y\mid\mathbf x)}{\sum_{y'}w(y')\,p_s(y'\mid\mathbf x)}

    Under label shift P(x∣y)P(\mathbf x\mid y) is fixed instead, so the weights depend on the label only, w(y)=πt(y)/πs(y)w(y)=\pi_t(y)/\pi_s(y) for class priors π\pi. Bayes' rule then corrects a calibrated classifier's probabilities with no retraining (Saerens, Latinne & Decaestecker, 2002):

Predict before you look

A flu model was calibrated in summer, when 1% of feverish patients had flu, and it gives one patient a probability of 0.5. In winter 10% of feverish patients have flu, and flu still presents the same way (label shift). What is the corrected probability, in percent?

Show the answer

92 %

The odds multiply by w(1)/w(0)=(0.10/0.01)/(0.90/0.99)=11w(1)/w(0)=(0.10/0.01)/(0.90/0.99)=11. Odds of 1 become 11, a probability of 11/12≈91.7%11/12\approx91.7\%. The same score means very different things at different prevalences, which is why a model's probabilities must be re-anchored when the base rate moves.

Where do the weights come from? Not from target labels. Pool the nsn_s training inputs (label d=0d=0) with ntn_t unlabeled production inputs (d=1d=1) and train a probabilistic domain classifier c(x)≈P(d=1∣x)c(\mathbf x)\approx P(d=1\mid\mathbf x). By Bayes' rule, P(d=1∣x)=ntpt(x)/(ntpt(x)+nsps(x))P(d=1\mid\mathbf x)=n_tp_t(\mathbf x)/\big(n_tp_t(\mathbf x)+n_sp_s(\mathbf x)\big), so

w(x)=pt(x)ps(x)=nsnt⋅c(x)1−c(x).w(\mathbf x)=\frac{p_t(\mathbf x)}{p_s(\mathbf x)}=\frac{n_s}{n_t}\cdot\frac{c(\mathbf x)}{1-c(\mathbf x)}.

The same classifier doubles as a shift detector: if its cross-validated AUC is close to 0.5, it cannot tell the two samples apart. For label shift you need the new priors πt\pi_t instead, and those can be estimated from how often the model predicts each class (next step).

python
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import roc_auc_score

X = np.vstack([X_train, X_prod])                          # source rows, then target rows
d = np.r_[np.zeros(len(X_train)), np.ones(len(X_prod))]   # 1 = production
c = cross_val_predict(HistGradientBoostingClassifier(), X, d,
                      cv=5, method="predict_proba")[:, 1]
print("domain AUC:", roc_auc_score(d, c))                 # near 0.5: no detectable shift

c = np.clip(c, 0.01, 0.99)                                # cap extreme ratios
w = (len(X_train) / len(X_prod)) * c / (1 - c)
w_train = w[: len(X_train)]                               # pass as sample_weight when refitting

Clipping trades a little bias for much less variance. If many training rows get weights near zero and a few get huge ones, the effective sample size is small: the production data lie largely outside what the training set covers, and no reweighting can create information that is not there.

Label shift, seen through the metrics

Under label shift each class's inputs look as they did before, so anything computed within a class is unchanged: the recall (true-positive rate, TPR) and the false-positive rate (FPR) at every threshold, and therefore the whole ROC curve and its AUC. Precision mixes the two classes in proportion to the prevalence π\pi:

precision=π TPRπ TPR+(1−π) FPR\text{precision}=\frac{\pi\,\mathrm{TPR}}{\pi\,\mathrm{TPR}+(1-\pi)\,\mathrm{FPR}}
TPR and FPR are conditional on the true class; the prevalence enters only through the mix.

The same algebra runs backward. The fraction of cases the model flags, q=π TPR+(1−π) FPRq=\pi\,\mathrm{TPR}+(1-\pi)\,\mathrm{FPR}, is observable without any labels, and TPR and FPR were measured on validation data. Solve for the prevalence:

π^t=q^t−FPRTPR−FPR.\hat\pi_t=\frac{\hat q_t-\mathrm{FPR}}{\mathrm{TPR}-\mathrm{FPR}}.

At the threshold above (TPR 0.42, FPR 0.045), a week in which 6% of cases are flagged implies a prevalence near (0.06−0.045)/(0.42−0.045)≈4%(0.06-0.045)/(0.42-0.045)\approx4\%. With kk classes this becomes a k×kk\times k linear system in the confusion matrix, black-box shift estimation (Lipton, Wang & Smola, 2018). It needs TPR ≠ FPR (a classifier that is not just guessing), and it fails if P(x∣y)P(\mathbf x\mid y) itself has changed.

Check your understanding

A screening model goes live in a population where the disease is three times rarer than in the validation data, and nothing else changes. At a fixed threshold, which of these changes?

  1. The AUC
  2. The true-positive rate
  3. The false-positive rate
  4. The precision (positive predictive value)
Show the answer

D. The precision (positive predictive value)

With P(x∣y)P(\mathbf x\mid y) fixed, TPR and FPR are unchanged, so the ROC curve and AUC are too. Precision falls: the same fraction of a now much larger healthy group is flagged, so a larger share of the flagged are false alarms.

Monitoring and retraining

Labels arrive late or never: a loan defaults months after approval, a blocked transaction never reveals whether it was fraud. So monitoring works on three levels, from what you see at once to what you see last.

LevelSignalTypical statisticWhat it catches
Inputs, one feature at a timeeach feature's distribution against a reference window; missing rates; schemaKolmogorov–Smirnov for numeric, χ² for categorical features; population stability index ∑i(ai−ei)ln⁡(ai/ei)\sum_i(a_i-e_i)\ln(a_i/e_i) over binscovariate shift, broken pipelines, unit changes
Inputs, jointlycan a classifier tell recent rows from reference rows?the domain classifier's cross-validated AUCshifts in combinations of features that no single feature shows
Predictionsscore histogram; fraction flaggedthe same tests on the scores; π^t\hat\pi_t from the flagged ratelabel shift, and covariate shift where the model is sensitive
Outcomesaccuracy, calibration and cost once labels arrive, overall and by subgroupsequential tests on the error rateconcept shift, the only kind that inputs alone cannot reveal
The population stability index compares binned proportions aia_i (recent) with eie_i (reference); it equals DKL(a ∥ e)+DKL(e ∥ a)\KL(a\,\|\,e)+\KL(e\,\|\,a), a symmetrized KL divergence. Credit-scoring practice reads values above about 0.25 as a major shift. That is a convention, not a test: with no shift at all, the index averages about (B−1)(1/na+1/ne)(B-1)(1/n_a+1/n_e) over BB bins with nan_a recent and nen_e reference rows, already 0.18 for 10 bins and 100 rows on each side, so small windows cross the line by chance.

When monitoring fires, the usual response is retraining. It can run on a schedule (simple, but blind between runs), on a trigger (a drift alarm or a measured drop in accuracy), or continuously from a stream. The training window is a real choice: recent data track concept drift but are fewer and noisier, all of history is stable but slow to adapt, and weighting recent examples more is a compromise. A retrained model should first run in shadow mode, scoring live traffic with its predictions only logged, so you can compare it with the current model before it makes any decision.

Proving it works, and writing it down

Offline metrics are proxies. To learn whether a new model improves what you actually care about, randomize: assign each user at random to the current model (control, A) or the new one (treatment, B) and compare the outcome. Randomization makes the groups alike in everything except the model, so the difference is a causal effect, the logic of a randomized controlled trial. The one number to fix in advance is the sample size.

n ≈ (z1−α/2+z1−β)2 [pA(1−pA)+pB(1−pB)](pB−pA)2users per armn\ \approx\ \frac{\big(z_{1-\alpha/2}+z_{1-\beta}\big)^2\,\big[p_A(1-p_A)+p_B(1-p_B)\big]}{(p_B-p_A)^2}\quad\text{users per arm}
For a two-sided test at level α\alpha with power 1−β1-\beta to detect a change of a rate from pAp_A to pBp_B. Detecting 5.0% → 5.5% at α=0.05\alpha=0.05 and 80% power (zz-values 1.96 and 0.84) takes about 31,000 users per arm. Halving the effect roughly quadruples the sample.

A deployed prediction is more useful with an honest error bar. Conformal prediction wraps any regression model. On a held-out calibration set of nn examples, compute the residuals ∣yi−f^(xi)∣\abs{y_i-\hat f(\mathbf x_i)} and let q^\hat q be the ⌈(n+1)(1−α)⌉\lceil(n+1)(1-\alpha)\rceil-th smallest (infinite if that index exceeds nn). Then f^(x)±q^\hat f(\mathbf x)\pm\hat q contains the true yy with probability at least 1−α1-\alpha, for any model and any distribution, provided calibration and test data are exchangeable. Shift breaks exactly that proviso, which is why the Convergence lesson pairs conformal methods with importance weights.

Finally, write down what the model is for. Model cards (Mitchell et al., 2019) record a model's intended and out-of-scope uses, its evaluation data, and its performance broken down by relevant groups and conditions. Datasheets for datasets (Gebru et al., 2021) record why a dataset was created, what it contains, how it was collected and labeled, and what it should not be used for. Both make explicit the assumptions behind "the test score was 0.91", which is what someone needs when the world moves.

Key takeaways

  • Serve with exactly the transformations you trained with. Training–serving skew is silent; fit preprocessing once, ship it with the model, and log served features.
  • Covariate shift changes P(x)P(\mathbf x) and keeps P(y∣x)P(y\mid\mathbf x); label shift changes P(y)P(y) and keeps P(x∣y)P(\mathbf x\mid y); concept shift changes P(y∣x)P(y\mid\mathbf x). Only the first two can be corrected with unlabeled target data.
  • Importance weighting, Rt(h)=Es[w(x) ℓ]R_t(h)=\E_s[w(\mathbf x)\,\ell] with w=pt/psw=p_t/p_s, needs overlap and pays in effective sample size (∑wi)2/∑wi2(\sum w_i)^2/\sum w_i^2. A domain classifier gives w=(ns/nt) c/(1−c)w=(n_s/n_t)\,c/(1-c); label shift re-weights posteriors by πt(y)/πs(y)\pi_t(y)/\pi_s(y).
  • Under label shift, TPR, FPR, the ROC curve and AUC stay put while precision and the PR curve move, and the flagged rate q=π TPR+(1−π) FPRq=\pi\,\mathrm{TPR}+(1-\pi)\,\mathrm{FPR} yields an estimate of the new prevalence.
  • Monitor inputs, predictions and outcomes with care for multiple testing; prove improvements with randomized A/B tests of fixed size; record intended use and limits in model cards and datasheets.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A readmission model trained at one hospital is deployed at another whose patients are older on average. For patients with identical records, the readmission risk is the same at both. Which shift is this, and what corrects it without new labels?

  1. Label shift: re-weight the classes by their new priors
  2. Covariate shift: importance weights pt(x)/ps(x)p_t(\mathbf x)/p_s(\mathbf x), estimated from unlabeled records of the new hospital
  3. Concept shift: only new labels can fix it
  4. No shift: the risk given the record is unchanged, so nothing needs fixing
Show the answer

B. Covariate shift: importance weights pt(x)/ps(x)p_t(\mathbf x)/p_s(\mathbf x), estimated from unlabeled records of the new hospital

P(x)P(\mathbf x) changed while P(y∣x)P(y\mid\mathbf x) did not: covariate shift. A domain classifier trained to tell the hospitals' records apart gives the density ratio, and weighted retraining focuses the model on the inputs it will now see.

Question 2

The training data contain no applicants under 25; production contains many. Can importance weighting correct for this?

  1. Yes, if the weights are large enough
  2. Yes, if the domain classifier is accurate
  3. No: the identity needs ps(x)>0p_s(\mathbf x)>0 wherever pt(x)>0p_t(\mathbf x)>0, and here the training data say nothing about the new region
  4. Yes, after clipping the weights
Show the answer

C. No: the identity needs ps(x)>0p_s(\mathbf x)>0 wherever pt(x)>0p_t(\mathbf x)>0, and here the training data say nothing about the new region

The weight pt/psp_t/p_s is infinite where ps=0p_s=0: no reweighting of training examples can represent inputs that never occur among them. The model's behavior there is pure extrapolation, and only data from that region, or strong modeling assumptions, can help.

Question 3

A domain classifier cannot tell last year's inputs from this month's (cross-validated AUC 0.50). What can you conclude about the model's accuracy?

  1. Nothing yet: concept shift can change P(y∣x)P(y\mid\mathbf x) without changing P(x)P(\mathbf x), and only outcomes reveal it
  2. It is unchanged, because the data have not shifted
  3. It has dropped, because an AUC of 0.5 means the model is guessing
  4. It is unchanged unless the prevalence moved
Show the answer

A. Nothing yet: concept shift can change P(y∣x)P(y\mid\mathbf x) without changing P(x)P(\mathbf x), and only outcomes reveal it

Input monitoring sees P(x)P(\mathbf x) only. A recession that raises default rates among otherwise identical applicants changes P(y∣x)P(y\mid\mathbf x) with no trace in the inputs. Outcome monitoring, once labels arrive, is the only safeguard against concept shift.

Question 4

On validation data, at a fixed threshold, a classifier has TPR 0.8 and FPR 0.1. In production it flags 24% of cases. Assuming label shift, what is the production prevalence?

  1. 24%
  2. 30%
  3. 20%
  4. 14%
Show the answer

C. 20%

q=π TPR+(1−π) FPRq=\pi\,\mathrm{TPR}+(1-\pi)\,\mathrm{FPR}, so π^=(0.24−0.1)/(0.8−0.1)=0.14/0.7=0.20\hat\pi=(0.24-0.1)/(0.8-0.1)=0.14/0.7=0.20. Check: 0.2⋅0.8+0.8⋅0.1=0.16+0.08=0.240.2\cdot0.8+0.8\cdot0.1=0.16+0.08=0.24.

Question 5

An analyst checks an A/B test's p-value every morning and stops on the first day it falls below 0.05, declaring the new model better. What is wrong?

  1. Nothing, as long as the test is two-sided
  2. The test should use the median instead of the mean
  3. Daily checks are fine, but weekends must be excluded
  4. Repeated looks give chance many opportunities to cross 0.05, so the real false-positive rate is far above 5%
Show the answer

D. Repeated looks give chance many opportunities to cross 0.05, so the real false-positive rate is far above 5%

Under no true effect, the running test statistic wanders, and stopping the first time it crosses a fixed boundary inflates the error rate: about 37% with 100 looks. Fix the sample size in advance, or use a sequential procedure whose error guarantee holds under continuous monitoring.

Go deeper

Further reading

  • H. Shimodaira, "Improving predictive inference under covariate shift by weighting the log-likelihood function," Journal of Statistical Planning and Inference 90(2), 227–244 (2000).
  • Z. C. Lipton, Y.-X. Wang & A. Smola, "Detecting and correcting for label shift with black box predictors," ICML (2018).
  • R. Kohavi, D. Tang & Y. Xu, Trustworthy Online Controlled Experiments: A Practical Guide to A/B Testing (Cambridge University Press, 2020).
  • M. Mitchell, S. Wu, A. Zaldivar, P. Barnes, L. Vasserman, B. Hutchinson, E. Spitzer, I. D. Raji & T. Gebru, "Model cards for model reporting," Proceedings of the Conference on Fairness, Accountability, and Transparency, 220–229 (2019).