SStatistics, Built

Stage V · PhD Research

Part 60 of 65

Robustness and Distribution Shift

PhDstarts at this level51 min of film13 chaptersprerequisites: Part 30, Part 51, Part 57

What can be guaranteed when the data are corrupted, or the future differs from the past?

In 2019 Recht, Roelofs, Schmidt and Shankar rebuilt ImageNet's test set, and on their MatchedFrequency collection the evaluated classifiers lost eleven to fourteen points of accuracy: a test set samples one collection process, and deployment may use another. The first half of the part is about corrupted data. Tukey's depth finds the centre of a cloud whatever a minority of the points do, shown in the depth map on Old Faithful with thirty planted eruptions; in high dimensions the mean and the medians are pulled by a planted cluster by an amount that grows like root d, and the spectral filter, list decoding and median-of-means estimators are the computable answers. The second half is about shift. On an NHANES extract the unweighted source mean of blood pressure is 118.5 against a target of 126.2 and its interval never covers, while the weighted mean with a logistic density ratio covers 95% at an effective sample size of 268 out of 600; on the breast cancer biopsies, black-box shift estimation recovers a target prevalence of 0.70 that classify-and-count puts at 0.64. Distributionally robust optimization, invariant causal prediction and anchor regression, transfer learning and tests that detect shift follow, each with the scope of its guarantee stated, and the part ends with open problems.

What you need. Stages I to IV of the series: Part 30's one-dimensional robust estimators and breakdown, concentration and random matrices (Part 51), convex duality, instrumental variables (Part 37), and Part 57's weighted conformal inference.

Hook
ImageNet's new test set (Recht et al. 2019)
Mathematics
depth, filtering and SoS, list decoding, covariate and label shift, DRO, invariance and anchor regression, transfer minimax
Built
statkit.shift

What you will be able to do

Bachelor's

  • Explain the ImageNetV2 result: what a test set measures, and why a new sample collected the same way can score lower.
  • Compute the Tukey depth of a point in a small planar data set and say why the deepest point resists a planted cluster that moves the mean.

Master's

  • Estimate a density ratio with a classifier, form the importance-weighted mean, and compute Kish's effective sample size.
  • Estimate target class proportions under label shift from a confusion matrix (BBSE), and say when the matrix does not identify them.
  • Compute the chi-square robust risk of a loss sample and verify it against mean plus root of 2 rho times the variance.

PhD

  • State the minimax rate of robust mean estimation under contamination, why coordinatewise and geometric medians miss it by root d, and what a certified filter must control beyond the top eigenvalue.
  • State the list-decoding guarantee when the clean points are a minority, and the sub-Gaussian rate of median-of-means tournaments under two moments.
  • Derive the anchor regression estimator and its limits (OLS at gamma = 1, two-stage least squares as gamma grows, when identified), and state what invariant causal prediction guarantees.

Practice

  • Diagnose a shift before correcting it: compare covariates with a two-sample test, report the effective sample size of the weights, and refuse to extrapolate without overlap.
  • Report a transported estimate with the assumption that licenses it (covariate shift, label shift, or a robustness ball) and an interval that includes the estimation of the weights.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 9 min · Master's 22 min · PhD 51 min · Practice 22 min.

  1. 0Recht, Roelofs, Schmidt and Shankar, 2019Bachelor's3 min
  2. 1DepthBachelor's4 min
  3. 2Efficient high-dimensional robustnessPhD5 min
  4. 3List-decodable learningPhD3 min
  5. 4Heavy tails in high dimensionsPhD4 min
  6. 5Covariate shiftPractice4 min
  7. 6Label shiftPractice4 min
  8. 7Distributionally robust optimizationPhD6 min
  9. 8InvariancePhD4 min
  10. 9Transfer learningPhD4 min
  11. 10Detecting shiftPractice4 min
  12. 11Open problemsPhD4 min
  13. Recap, problems, and the road aheadAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Recht, Roelofs, Schmidt and Shankar, 2019Bachelor's3 min

Recht, Roelofs, Schmidt and Shankar rebuilt ImageNet's test set in 2019. On their MatchedFrequency collection the evaluated classifiers lost eleven to fourteen percentage points of top-one accuracy. Other collection variants gave different gaps. Improvements on the old benchmark generally transferred to the new one. Preserved rankings alone do not rule out adaptive overfitting. The result shows that apparently similar collection procedures can produce consequential distribution differences. A test set samples one collection process; deployment may use another.

Our guarantees depend on assumptions about sampling, dependence and the target. Earlier parts already considered adaptation and drift; here we study contamination and distribution shift directly. Some observations may be corrupted or adversarial. Alternatively, valid observations may come from a distribution different from the target. Robust estimation and shift correction address these problems under explicit structural assumptions.

The two threats in symbols. Huber's contamination model: the data come from one minus epsilon times P plus epsilon times anything. The strong contamination model is harsher: an adversary who sees the clean sample replaces an epsilon fraction of it with points of its choosing. Distribution shift: the training data come from P, the target is Q. With no assumption linking P and Q nothing can be said; with a structured link, such as covariate shift, label shift, or invariance across environments, a great deal can.

A preview on real data. This fixed, unweighted complete-case NHANES extract of adults have mean systolic pressure . Draw samples of that over-represent the young, as an online panel might: their mean age is , against in the empirical extract. The sample mean pressure is about , and its ninety-five percent interval contains the truth in percent of samples. Reweighting by estimated importance weights recovers , and covers percent of the time: chapter five's method.

The plan. Chapters one to four: robustness, from Tukey's depth to efficient filters, list decoding, and heavy tails. Chapters five and six: covariate shift and label shift, each with a correction and its price. Chapters seven to nine: protecting against shifts one cannot name, by robust optimization, invariance, and transfer. And chapter ten: detecting that a shift has happened at all.

Two promises come due. Part thirty built robust estimators of location and scale in one dimension; chapters one to four take robustness into many dimensions, with algorithms that run in polynomial time. Part fifty-seven's weighted conformal assumed the shift's weights were known; chapters five and six estimate them, and count the price.

1DepthBachelor's4 min

Depth: Tukey's way to find the centre of a cloud of points, whatever a minority of them do.

John Tukey, in 1975, defined the depth of a point among data in many dimensions. Draw every half-plane, or half-space, whose boundary passes through the point. The depth is the smallest fraction of the data in any of them. Points far outside the cloud have depth near zero; points in its middle have depth near a half. The Tukey median is the deepest point: in one dimension, the ordinary median.

The part's instrument, the depth map, on Old Faithful: eruption length against waiting time for two hundred and seventy-two eruptions. The shading is Tukey depth, computed by an angular sweep at each displayed grid point: bright in the core, fading to the rim. Our grid approximation to the deepest point, sits inside the larger cluster of long eruptions. The mean falls between the clusters, where few eruptions are. Depth is about the shape of the cloud; the mean is about its balance.

Now plant thirty false eruptions, ten percent of the data, in an empty corner: long eruptions followed by short waits. The mean is dragged toward them, by in these units. The depth map grows a thin, shallow wedge toward them, but its bright core holds, and the grid depth median moves by . The grey marks show where each was: the median held its place.

The sample mean has replacement breakdown one over n: one point can send it arbitrarily far. Coordinatewise medians have breakdown near one half, but contamination bias can accumulate across coordinates. Exact halfspace-median breakdown depends on sample geometry and the contamination convention; centerpoint bounds give order one over d, and symmetric population results yield one third. These are not guarantees for our finite grid search. Dimension-free contamination error requires a distributional model. For an isotropic Gaussian, exact depth estimation attains root d over n plus epsilon, up to confidence factors and constants.

Chen, Gao and Ren study minimax estimation under Huber contamination. For an isotropic Gaussian with small contamination fraction, the Euclidean mean-error rate is root d over n plus epsilon, with additional terms for high confidence. An exact halfspace-depth median attains this rate. Our planar grid picture illustrates depth, rather than implementing this high-dimensional theorem. Matrix-depth covariance estimators have related robust rates under covariance bounds and the specified matrix norm. Those assumptions and loss functions matter.

The catch is computation. Depth is defined by a minimum over all directions, and in d dimensions there are too many: exact depth computation is NP-hard when dimension is part of the input; standard exact algorithms have costs that grow rapidly with dimension. In two dimensions it is easy, as the map showed; in fifty, hopeless. For decades, statistics had estimators that were robust or computable in high dimensions, not both. Chapter two is the 2016 breakthrough that ended the dilemma.

2Efficient high-dimensional robustnessPhD5 min

Efficient robust estimation in high dimensions: the filter. The goal: estimate the mean of a d-dimensional Gaussian from n samples, an epsilon fraction of them chosen by an adversary. The best possible error is of order epsilon, plus the sampling error root d over n. The Tukey median achieves it, but cannot be computed. The coordinatewise and geometric medians can be computed, but their error grows like epsilon root d. In 2016 two groups, Ilias Diakonikolas, Gautam Kamath, Daniel Kane, Jerry Li, Ankur Moitra and Alistair Stewart, and independently Kevin Lai, Anup Rao and Santosh Vempala, found polynomial-time estimators whose error barely depends on the dimension: Lai, Rao and Vempala's grows like root log d, and Diakonikolas and co-authors' is epsilon times a root-log factor, with no d at all.

The adversary's simplest effective move: put every planted point at the same location, with every coordinate equal to two. Each coordinate's median moves by about one and a quarter times epsilon, since the median shifts until it has absorbed the extra mass on one side. Across d coordinates, those shifts add in quadrature: the error is about one and a quarter epsilon root d. The mean moves by two epsilon root d. Neither notices that the planted points are, as a cluster, very far from the rest.

Spectral filtering exploits the relation between a displaced mean and inflated variance, together with stability of the clean sample. The displayed implementation uses a Marchenko-Pastur edge plus heuristic slack as its stopping threshold. This threshold alone is not a robust-estimation certificate. It removes the most extreme five percent of top-eigenvector projections each round. Certified filters instead choose thresholds with a proof that contamination decreases relative to retained clean mass. Our deterministic trimming illustrates the idea on this planted attack; it does not implement that theorem.

Why can spectral information help? One needs both clean-sample stability and control of the contamination budget. Moving the mean by delta using epsilon mass creates a variance contribution with scale delta squared over epsilon. Deletions and changes in the retained clean mean also need bounds. Under appropriate Gaussian stability conditions, certified filters obtain error of order epsilon root log one over epsilon, plus sampling error, in the strong contamination model. An eigenvalue is part of this certificate. A small top eigenvalue, without the other assumptions, does not certify proximity to any particular clean mean.

The four estimators, as the dimension grows, with two thousand points and ten percent planted. The mean and the coordinatewise median grow like root d. So does the geometric median, more slowly. The filter tracks the grey oracle, the mean of the clean points alone: its observed error is close to the clean-sample error in these four seeded repetitions. This is not a worst-case guarantee. At a hundred dimensions, the mean is off by , the medians by and , the filter by .

Fix a hundred dimensions and vary the contamination. The mean and the two medians grow linearly in epsilon, with slopes proportional to root d. The filter stays near the sampling error throughout, at twenty percent contamination. It removed percent of the planted points, and percent of the clean ones: the price of caution is small.

Convex reweighting offers another route to spectral control. Sum-of-squares methods certify higher moments for more demanding robust-estimation problems. Computational limits depend on the corruption model. Statistical-query lower bounds support an epsilon root log one over epsilon barrier for strong or total-variation corruption of isotropic Gaussians. They do not give that barrier for Huber mixtures. In fact, Diakonikolas, Kane, Pensia and Pittas obtained order-epsilon error with near-optimal samples and almost-linear time for the Huber model in 2023. Their algorithm is more elaborate than this demonstration.

3List-decodable learningPhD3 min

List-decodable learning: when most of the data are not what you want. What if the contamination is more than half? With an alpha fraction of inliers, alpha below a half, no single estimate can be right: the outliers could be a second, equally plausible population. Moses Charikar, Jacob Steinhardt and Gregory Valiant asked in 2017 for a list instead: a short list of candidates, one of which is close to the inliers' mean. The list must have about one over alpha entries, since the adversary can plant that many fake populations. Its best entry can achieve dimension-free error of order one over root alpha for bounded-covariance inliers, apart from sampling terms.

A two-dimensional picture. Ninety inliers, thirty percent, and three planted clusters of seventy points each. The overall mean, in red, is from the inliers' centre, near none of the groups. A list of four candidates, one over alpha rounded up, found by clustering, has an entry from the inliers' centre: as close as the mean of the ninety inliers themselves. Which entry is right cannot be told from the data alone: a small labelled set, or a known property of the inliers, picks it.

Clustering is adequate for these four well-separated groups. K-means has no adversarial list-decoding guarantee here. Theoretical algorithms use convex relaxation, filtering or moment certificates and need explicit inlier covariance and sample assumptions. For bounded covariance, dimension-free error of order one over root alpha is the reference scale. Runtime depends on the chosen accuracy, list size and model; we make no universal near-linear runtime claim. Crowdsourcing provides one motivation: a reliable minority may need a small amount of trusted information to select from the list.

List size and accuracy are separate questions, and both depend on the inlier model. Around one over alpha equally plausible clusters force a list of comparable order in worst-case constructions. The exact integer count involves rounding. For inliers with covariance bounded by the identity, the natural worst-case accuracy scale is one over root alpha, apart from sampling terms and the specified list-size regime. Gaussian inliers have additional structure and allow stronger accuracy guarantees with list-size and computational trade-offs. The bounded-covariance lower bound is not a Gaussian minimax theorem.

Where list decoding is used. Clustering mixtures: each component is a minority, and list decoding finds every component's mean. Learning from untrusted sources: a trusted few verify the list. And robust regression with a majority of corrupted responses, where a short list of candidate regressions replaces a single fit.

4Heavy tails in high dimensionsPhD4 min

A different threat: no adversary, but heavy tails. If the data have only a finite variance, the sample mean's deviations are controlled only by Chebyshev's inequality. To be within t of the truth with probability one minus delta, the mean needs n of order one over delta: a polynomial dependence on the confidence, where Gaussian data give a logarithm. Can an estimator do as well, for heavy-tailed data, as the mean does for Gaussian data?

The median of means, from Nemirovski and Yudin, and Alon, Matias and Szegedy: split the data into k blocks, average each, and take the median of the averages. Each block mean is within two sigma root of k over n of the truth with probability at least three quarters, by Chebyshev. The median fails only if half the blocks fail, which by Hoeffding has probability e to the minus k over eight. With k of order log one over delta, the median of means has the Gaussian width, for any finite-variance distribution: Part thirty's robust estimators, in their sharpest form.

Median of means tunes its block count to a requested confidence level, with at most n nonempty blocks. Devroye, Lerasle, Lugosi and Oliveira distinguish this from a single estimator with guarantees at many confidence levels. Over the full class of finite-variance laws, without further scale information, that stronger property is impossible. Known variance, or variance known within fixed factors, changes the answer. Bounded kurtosis also permits multiple-confidence estimators over stated ranges. Near-optimal constants require a smaller range than a blanket claim down to exponential minus n; the constants and kurtosis bound enter the theorem.

In twenty dimensions, with Student t data of two and a half degrees of freedom, whose variance is finite but whose tails are heavy. The curves show, for each error t, the fraction of four hundred samples whose error exceeds it, on a log scale. The sample mean's curve, in red, falls slowly: one sample in a hundred, the dashed line, has error above . The median of block means, with the geometric median for the vector case, falls much faster: its one-in-a-hundred error is . Their typical errors differ less, against : the gain is in the tail, which illustrates upper-tail behavior. The empirical ninety-ninth percentile uses only about four tail observations among four hundred; its order-statistic uncertainty is recorded with the computation.

In high dimensions, the geometric median of block means is good but not optimal: its width has the wrong dependence on the covariance. Gábor Lugosi and Shahar Mendelson's median-of-means tournament, in 2019, compares every pair of candidate means block by block, and keeps those that win most of their matches. The winner's error is the trace of the covariance over n, plus the top eigenvalue times log one over delta over n, under roots: exactly the Gaussian sample mean's. Sam Hopkins found a polynomial-time version through sum-of-squares, in 2020.

Catoni's scalar estimator uses a smoothed estimating equation. Near-optimal constants require the theorem's variance information, tuning and confidence range. Extensions to regression and covariance estimation require their own moment and structural assumptions. Median-of-means methods can also resist adversarial observations, provided enough blocks remain clean: the block count must account for the number of corrupted points as well as the confidence level. A fixed thirty-block choice does not resist an arbitrary fraction at every sample size. Heavy-tail and contamination guarantees can be combined when these conditions are made explicit.

5Covariate shiftPractice4 min

Covariate shift: when the people change, but the relationship does not. Covariate shift, named by Hidetoshi Shimodaira in 2000: the training data come from a distribution P over covariates x and outcomes y, the target from Q. The covariates' distribution changes, from p of x to q of x. But the conditional law of y given x is the same in both. In a survey, the panel over-represents the young, but a forty-year-old's blood pressure has the same distribution whether or not they joined the panel. That is the assumption, and it is Part forty-one's missing at random, under another name.

The importance weight is the ratio of the two covariate densities, q over p. Any expectation under the target is an expectation under the training distribution, reweighted: the weighted average of the training outcomes estimates the target mean, the same Horvitz–Thompson idea as Part eighteen's surveys. It needs the weights to exist: wherever q puts mass, p must too. If the panel has no one over seventy, no reweighting can bring them back.

The densities are unknown, and estimating each in many dimensions is hard. The ratio is easier. Pool the training sample with an unlabelled sample from the target, and fit a classifier for which one each point came from. By Bayes' rule, the classifier's odds are the density ratio, up to the ratio of the two sample sizes. Here a logistic regression on age, age squared, sex and body-mass index, against two thousand unlabelled NHANES adults: the outcomes of the target are never needed.

The two age distributions. In gold, the empirical extract: NHANES adults, from eighteen to eighty. In blue, one sample of , drawn with selection probability falling exponentially with age, as an online panel might be. The sample's mean age is , the empirical extract's . There are few people over seventy in the sample, but they exist: their weights will be large, and that is where the price is paid.

We independently resample four hundred source datasets and unlabelled reference datasets from a fixed unweighted NHANES extract. The target is its empirical mean, not a survey-weighted national estimand. The red curve is a Gaussian fit to the simulated unweighted means, which are biased toward younger adults' pressures. Their nominal ninety-five percent intervals cover the extract mean in none of these four hundred runs. The green curve is a Gaussian fit to the importance-weighted means. Source sampling is with replacement and its true log density ratio is linear in age. The displayed coverage uses a joint sandwich standard error that includes fitting the logistic ratio and sampling the unlabelled target reference. It is asymptotic and model-dependent; empirical coverage has Monte Carlo uncertainty.

Kish's effective sample size is the squared sum of weights divided by their squared sum. It diagnoses weight concentration. The displayed average is smaller than the source sample size. It is not an exact information count for this estimator: outcome heterogeneity, dependence of outcomes on weights, and estimation of the ratio also affect variance. The empirical spreads are shown separately. Weak overlap may make the second moment of the weights enormous or infinite, undermining usual variance and normal approximations.

Clipping weights trades bias for variance. Kernel mean matching and KLIEP estimate the ratio through other criteria. A doubly robust target-mean estimator averages an outcome regression on target covariates and adds a weighted source residual correction. Consistency can survive one correctly estimated nuisance; confidence intervals additionally require overlap and suitable error rates. Weighted conformal is exactly valid under its known-ratio and exchangeability conditions. Estimated ratios need a compatible fitting or splitting scheme and an explicit approximation-error bound.

6Label shiftPractice4 min

Label shift: when the mix of outcomes changes, but each outcome looks the same.

The mirror image of covariate shift. A classifier for breast biopsies is trained on an empirical biopsy sample, where percent of biopsies are malignant. We simulate a target mixture, where seventy percent are. A malignant biopsy looks the same at both: the law of the features given the label is unchanged; only the label's distribution moved. Two questions: what is the new prevalence, and how should the classifier's probabilities be corrected? Neither needs a single label from the new site.

Classify and count uses the fraction predicted malignant. Its expectation is q times the true-positive rate plus one minus q times the false-positive rate. The bias is q times TPR minus one, plus one minus q times FPR. Its sign depends on both rates and q; it is not always toward one half. The observed downward bias is specific to this example. Forman's adjusted count inverts this relation if TPR differs from FPR. Estimated rates add uncertainty and boundary projection can add finite-sample bias.

Zachary Lipton, Yu-Xiang Wang and Alexander Smola generalized it in 2018, to any number of classes: black-box shift estimation. On held-out training data, estimate the joint matrix of predicted against true labels. On the target, estimate the distribution of predictions. Under label shift, the one is the other times the vector of weights, Q of y over P of y. Solve the linear system. The classifier can be anything, even a poor one, as long as the confusion matrix is invertible: its quality affects the variance, not the consistency.

An older route uses the classifier's probabilities, not just its labels. Marco Saerens, Patrice Latinne and Christine Decaestecker, in 2002: given a guess of the new prevalence, correct each target point's probability by Bayes' rule, multiplying by the prior ratio and renormalizing. Then update the prevalence to the average corrected probability, and repeat. It is EM for the mixing weights of a mixture whose components are known, and it is more efficient than BBSE when the classifier's probabilities are calibrated; when they are not, it can be badly biased.

These are three hundred semi-synthetic repetitions on the Wisconsin dataset. Each classifier trains on two hundred and fifty biopsies. Independent calibration and target draws then use the same remaining class-conditional reservoir, with replacement, at source prevalence about thirty-seven percent and target prevalence seventy percent. Realized target counts fluctuate. The gold line is the target mixture parameter. The curves are smoothed empirical densities. Classify and count is biased downward in this experiment. Projected BBSE is close to the truth on average but is not exactly unbiased; both calibration and target variation contribute to its spread. EM is more concentrated here but retains finite-sample bias. This plot alone does not establish calibrated probabilities or clinical performance.

Under exact label shift, known source posterior probabilities can be adjusted by the class-prior ratio and normalized. Estimated probabilities and weights introduce error. A source score of forty percent would become about seventy-three percent under these priors if that score were the correct source posterior. BBSE uncertainty depends on both source calibration and target sample sizes, amplified by inverse confusion-matrix conditioning. A causal story may suggest a shift model, but the direction of causation alone does not identify the actual shift from unlabelled data.

7Distributionally robust optimizationPhD6 min

Distributionally robust optimization: guarding against every shift in a ball. Chapters five and six assumed the shift had a known structure. What if it does not? Distributionally robust optimization fits the model that minimizes the worst expected loss over a whole set of distributions near the training distribution: an uncertainty set. The idea comes from robust optimization, from Aharon Ben-Tal, Laurent El Ghaoui and Arkadi Nemirovski; Ben-Tal and co-authors gave the divergence-ball form in 2013. Its answer is a bound: whatever the test distribution, if it lies in the set, the risk is at most the robust objective.

The choice of set is the whole art. A divergence ball: distributions whose density ratio to the training distribution is not too far from one, in chi-square or Kullback–Leibler divergence. These reweight the training points but cannot move them. A Wasserstein ball: distributions reachable by moving the training points a limited total distance. These can move points to places never seen. Group DRO, from Shiori Sagawa and co-authors in 2020: the mixtures of a few known subpopulations, so the objective is the worst group's risk.

A supremum over distributions sounds intractable, but convex duality makes it a few scalars. For the chi-square ball, with small radius, the worst case is the mean loss plus a multiple of its standard deviation: DRO is variance regularization, as John Duchi and Hongseok Namkoong showed, and it penalizes models whose losses are uneven across the data. For the Kullback–Leibler ball, the dual is a one-dimensional minimization over a temperature lambda, of an exponentially tilted mean: the worst case upweights the largest losses exponentially.

An example. Fit a regression of systolic pressure on sex and body-mass index, using only NHANES adults under forty. Its mean squared error on the young, in units of ten millimetres of mercury, squared, is . Applied to adults of forty to fifty-nine, it is . At sixty to eighty, it is : more than seven times the training error, because pressure rises with age and the young-trained model never learned it.

This age example displays unequal empirical risks. It does not by itself establish every notion of fairness. Hashimoto and co-authors study a feedback mechanism in which poorly served groups leave and become less represented. A divergence ball can bound every subgroup risk when its radius is large enough to contain each subgroup-conditional distribution of the same base law. For our chi-square convention, groups of mass at least alpha fit at radius one half times one over alpha minus one. Moving from an empirical base to a population needs generalization assumptions. This links robust worst-group risk with one fairness objective. It does not ensure parity or individual fairness.

These curves use fifteen hundred young-adult training losses; radius zero is that subsample's mean loss. The full young group's risk is a separate dashed comparison. The green curve is chi-square DRO, evaluated with a feasible primal weighting and a checked dual upper bound. Purple is KL DRO with the same numerical checks. Their radii are different divergence units and are not directly interchangeable. The older groups' observed empirical risks are comparisons, not certified by the young-only balls: those groups have different support. A curve crossing a dashed line does not prove membership. For a valid finite-empirical group bound, instead take all adults as the base. A group of mass p lies in the chi-square ball of radius one half times one over p minus one, or the KL ball of radius minus log p. We compute and verify those bounds separately; neither is a national-population guarantee.

Transport duality can turn Wasserstein uncertainty into tractable optimization. The ground cost is part of the specification. For a globally Lipschitz loss, a one-Wasserstein radius gives an upper bound equal to empirical risk plus radius times Lipschitz constant. Equality needs additional conditions. The square-root-lasso identity uses squared feature transport with outcomes held fixed and the appropriate dual norm: worst-case root mean squared loss becomes empirical root mean squared loss plus a norm penalty. A quadratic loss is not globally Lipschitz under arbitrary joint transport. Label-preserving perturbations bounded pointwise correspond to an infinity-Wasserstein formulation under a matching ground metric.

The price is pessimism. A large set protects against shifts that will never happen, and the robust model is worse on the training distribution; the radius is rarely known. Divergence balls guard against reweighting but are blind to genuinely new regions, and Weihua Hu and co-authors showed in 2018 that for classification, DRO with a divergence ball can return the same classifier as ordinary training. So the set should carry knowledge: known groups, plausible directions of change, or, as the next chapter shows, the causal structure.

8InvariancePhD4 min

Invariance: what stays the same across environments is what will stay the same next time.

A structural outcome mechanism may remain fixed across some environments. This is an assumption, not a property of every hospital or year. For a linear causal model with independent outcome noise, interventions on covariates can preserve the conditional law given all direct causes, provided the outcome mechanism and noise law are unchanged. Noncausal predictors may change their association with the outcome, but can also remain invariant by coincidence or insufficient environmental diversity. Observed invariance is therefore evidence under a causal model, not a standalone proof of causation or robustness to arbitrary future change.

Invariant causal prediction tests candidate parent sets across environments. Our implementation tests a common Gaussian linear conditional model, combining a pooled-versus-environment coefficient F test with residual-variance F tests and Bonferroni corrections. Distribution-free residual comparisons would not give the same guarantee. Intersect the accepted subsets. If the true-parent subset has a valid level-alpha test and the structural assumptions hold, the selected set contains no false parent with probability at least one minus alpha. False positives remain possible with probability at most alpha; an empty result is allowed.

A small example. Three environments shift the mean of X one; y depends on X one; X two is a child of y, also pushed by the environment. Using no predictor, y's mean changes between environments: rejected. Using X one, the residuals look the same everywhere: a p-value of one, accepted. Using X two, or both, the child's relation to y changes with the environment: rejected. The intersection of accepted sets is X one, the true parent. The child, which can be useful for prediction within an environment, is correctly left out.

Hidden confounding may prevent exact conditional invariance. Anchor regression instead penalizes residual association with exogenous anchors. Its criterion is residual energy orthogonal to the anchors plus gamma times projected residual energy. Gamma one is least squares. The infinite-gamma limit agrees with a unique two-stage-least-squares solution only when the projected design identifies the coefficients. This simulation has fewer anchor directions than coefficients, so that uniqueness condition fails. Under the paper's linear structural model and exogeneity conditions, the population criterion has a worst-case shift interpretation for a specified anchor-induced perturbation class. The finite simulation illustrates prediction under one shift, not a certificate for every intervention.

A simulated system with a hidden confounder. The anchor pushes on X one and on X two; in training its mean is zero, in the test environment three. As gamma grows, beyond least squares the training error, in blue, rises: the fit gives up some in-sample accuracy. Least squares, at gamma one, has test error . At gamma , the test error falls to , half of least squares': the coefficient on X one turns negative, cancelling the part of the child X two that the anchor contaminates. Partialling the anchors out entirely, gamma zero, is the worst of all, : it fits exactly the directions that will shift.

Invariant risk minimization seeks a representation on which the same classifier is optimal across training environments. Rosenfeld, Ravikumar and Risteski give failures and environment-diversity requirements in their studied models; more environments than spurious dimensions is not a universal theorem for all IRM settings. DomainBed found carefully tuned empirical-risk minimization competitive with evaluated domain-generalization methods on its benchmarks and selection protocols. It did not establish that every invariance method always ties ordinary training. Causal structure, environmental diversity and model selection determine how far these ideas transfer.

9Transfer learningPhD4 min

Transfer learning: borrowing from a related problem, and knowing when not to. Transfer learning combines source data with a smaller target sample. A classic binary-classification bound relates target risk to source risk. It adds one half of the hypothesis-disagreement divergence between covariate distributions. It also adds the minimum combined source and target error within the hypothesis class. A large joint error makes this bound uninformative; it does not prove that no source information can help any procedure.

Bounds like that are loose; minimax theory asks for exact rates. Samory Kpotufe and Guillaume Martinet, in 2021, measured covariate shift by a transfer exponent gamma: how much less mass the source puts on small balls of the target's support. Then a source point is worth a fractional power of a target point, and the minimax rate depends on the source size raised to a power that shrinks as gamma grows. Tony Cai and Hongji Wei found the analogous rates for posterior drift, where the regression function itself changes, with an adaptive classifier that needs no knowledge of how similar the problems are.

Li, Cai and Li study high-dimensional transfer under restricted coefficient contrasts. An l-one bound h describes the total contrast, rather than a single-coordinate shift. Our demonstration uses one chosen source: first fit a lasso on the pooled source and target. Then fit a sparse correction on target residuals. This is a simplified two-step core, without the paper's adaptive source aggregation. Theoretical gains depend on sparsity, design, sample sizes, contrast size and tuning. A source can pay for shared structure when target data can estimate the correction.

A simulation: two hundred predictors, ten of them active, a thousand source points, and between fifty and four hundred target points. The total l-one contrasts are zero point seven five and five. With a similar source, the target-only lasso, in red, needs many target points; with fifty its error is . Pooling everything, in gold, and Trans-Lasso, in green, are both near : the source does almost all the work. With a dissimilar source, pooling is a disaster: even with four hundred target points, worse than ignoring the source. Trans-Lasso's correction step reduces the error in these repetitions: , still better than the target alone at .

The failure of pooling has a name: negative transfer. Adding data can make an estimator worse, when the added data answer a different question. Guarding against it needs either knowledge of the similarity, or a way to estimate it. With several candidate sources, Li, Cai and Li aggregate the Trans-Lasso fits from each, with weights chosen on held-out target data, so that useless sources are ignored automatically. The principle generalizes: a transfer method should never do much worse than using the target alone.

In deep learning, domain adaptation learns a representation in which source and target look alike: Yaroslav Ganin and co-authors' domain-adversarial networks, in 2016, train a feature extractor to fool a classifier of domain membership. It shrinks the divergence term in Ben-David's bound. But matching the covariate distributions can hurt, when the label proportions also differ: aligning the features then misaligns the classes, as Han Zhao and co-authors showed in 2019. Every adaptation method encodes an assumption about what stays fixed; the statistics is in knowing which.

10Detecting shiftPractice4 min

Detecting shift: has the world changed, and does it matter? Every correction in this part needs to know that a shift happened. Detecting it is a two-sample test: are the training covariates and the deployment covariates from the same distribution? In one dimension, Part sixteen's Kolmogorov–Smirnov test answers. In many, a test must compare whole distributions without estimating their densities. Two modern answers: compare the distributions' embeddings in a kernel's feature space, or ask whether a classifier can tell them apart.

Maximum mean discrepancy compares kernel mean embeddings. For a fixed kernel, within-sample off-diagonal and between-sample averages give an unbiased squared-MMD U statistic, which can be negative. Our pooled, label-invariant bandwidth selection changes this fixed-kernel unbiasedness interpretation. A characteristic kernel separates distinct population laws; consistency also requires a suitable fixed or controlled kernel sequence. Under independent IID samples and the null, pooled labels are exchangeable. A permutation test with conservative handling of ties is level-valid. With three hundred sampled permutations we use the plus-one p-value, whose minimum is one over three hundred and one.

Chapter five's shift, detected. Three hundred adults from the young-skewed sample, against three hundred from the empirical extract, compared on age, body-mass index and sex. The grey bars are the permutation null. The observed statistic, , is larger than the sampled permutation statistics: a p-value of one over three hundred and one, the smallest three hundred permutations can give. Two independent samples from the empirical extract give a statistic in the middle of the null, with p equal to : the null is not rejected in this one run. Nonrejection does not prove equality.

A classifier two-sample test learns to distinguish the groups, then tests independent held-out predictions. With fixed balanced holdout labels, accuracy is not generally an exact binomial proportion. Conditional on the pooled number of positive predictions, the number assigned to the source is hypergeometric under exchangeability. The displayed accuracy and p-value now use that exact conditional randomization law, with the classifier frozen before holdout. Calibrated membership odds, adjusted for the training class proportions and orientation, can also estimate a density ratio. Discrimination accuracy alone does not validate those probabilities.

Detection sample size depends on the alternative, kernel and distribution. For a fixed bounded kernel and balanced samples, the unbiased squared-MMD statistic is order one over n under the null. Its alternative variance and local structure also affect power. Our empirical statistic is large compared with the sampled permutation null. The null scale alone does not justify a universal inverse-effect sample-size law, or extrapolation to a shift a hundred times subtler. Kernel learning can improve power, but it must use independent data or be incorporated into the randomization scheme to preserve validity.

Detectable covariate change need not increase predictive risk, and a fixed classifier or non-characteristic feature map may miss some changes entirely. Failing Loudly compares detection representations and methods; low-dimensional model outputs often helped on its evaluated shifts, not uniformly on every alternative. Risk increase is a separate, task-relevant null. It usually needs outcome feedback or additional assumptions. Sequential risk monitoring can use anytime-valid methods under the stated bounded-loss or conditional assumptions, with uncertainty in the reference risk accounted for.

A deployment protocol, assembled from this part and the last two. Monitor the model's outputs and its error on a trickle of labelled cases, with a confidence sequence. When the risk rises, test which kind of shift it is: covariates, labels, or the mechanism. Correct for the kinds that can be corrected, by weights or by label-shift estimation. And retrain, with transfer from the old data, when the mechanism itself has moved.

11Open problemsPhD4 min

The part in one table: each threat, the assumption that tames it, the method, and what it guarantees. A small adversarial fraction, against Gaussian inliers: depth and the filter, with error free of the dimension. A majority of adversarial points: a list. Heavy tails: median of means. Covariate shift, with the conditional law fixed and overlap: importance weights. Label shift: BBSE and EM. An unknown shift in a ball: distributionally robust optimization. And interventions on a causal system: invariance and anchors.

Computational gaps are model-specific. For isotropic Gaussian means, information-theoretic contamination error is order epsilon. Strong or total-variation corruption has statistical-query and related restricted-model evidence for a larger efficient-error scale. Huber mixtures instead admit order-epsilon polynomial algorithms, including the 2023 almost-linear-time result. Sparse means, covariance estimation and mixtures have different gaps, assumptions and reductions. Restricted-model lower bounds are not unconditional lower bounds for every polynomial algorithm. Pinning down which gaps follow from standard complexity assumptions remains an active question.

Which shift happened? Unlabelled target covariates do not in general distinguish covariate shift, label shift and outcome-mechanism changes. These models impose different assumptions, which can overlap in special cases. Real shifts can combine several changes. ImageNetV2 alone does not identify which conditional mechanism changed. Identification and sharp risk bounds require a specified model, labels, multiple environments or other information; many formulations remain open.

The uncertainty set is the essential modeling choice. A risk bound is useful only when the target is actually in that set. Ordinary random-split validation evaluates the same distribution and cannot certify protection from an arbitrary unseen shift. Environment-held-out validation and theoretically calibrated radii can still help under suitable assumptions. Learning useful future-environment sets from limited environments, domain knowledge or drift models remains an active problem.

Problem four: robustness at scale. The WILDS benchmark of Pang Wei Koh and co-authors, in 2021, collected real shifts, across hospitals, cameras and countries, and found large gaps between in-distribution and out-of-distribution accuracy that no method closed. One regularity, found by John Miller and co-authors that year: across many models, out-of-distribution accuracy is close to a linear function of in-distribution accuracy, on a probit scale. A theory of why, and of which training choices move models off that line, is open, and is Part sixty-four's question.

Inference under shift needs more than point estimation. Our low-dimensional example includes ratio-fit and reference-sample uncertainty, but its observed coverage is a finite Monte Carlo result under a correctly specified logistic ratio. It is not a guarantee for arbitrary estimated weights. Doubly robust estimation, balance and weighted conformal each require their own support, fitting and error-rate assumptions. Honest inference in high dimensions and under weak overlap requires careful formulation of the estimand and what can be identified.

Five open problems. Which statistical-computational gaps in robust estimation are real. Identifying the kind of shift, or bounding its damage. Principled uncertainty sets. A theory of robustness for large models. And honest inference under estimated shift.

Recap, problems, and the road aheadAll tracks2 min

Part sixty in twelve lines. The MatchedFrequency rebuilt ImageNet set cost the evaluated models eleven to fourteen percentage points. Tukey's depth is robust in any dimension but hard to compute; certified spectral filters are robust and efficient; our trimming is an illustration. List decoding handles a majority of outliers, and median of means needs only two moments. Covariate shift is corrected by importance weights, at a price in effective sample size. Label shift is corrected through the confusion matrix, or by EM. Distributionally robust optimization certifies the risk over a ball of distributions. Invariance turns causal structure into robustness. Transfer learning borrows from a source and corrects the difference. Kernel and classifier tests detect a shift. And five problems remain open.

A promise for the next part. This part measured shifts with divergences, the maximum mean discrepancy, and Wasserstein balls. It used them as tools without studying them. Part sixty-one studies the Wasserstein distance itself: optimal transport, its computation, and its statistics.

Where it comes back. Part sixty-one's study of Wasserstein distances. Part sixty-two's transport of causal effects to new populations. Part sixty-three, where robustness and differential privacy turn out to be two sides of one coin. Part sixty-four's large models and their accuracy line. And the dissertation's robustness checks.

Six problems, with full solutions in the README. The contaminated median's shift; the importance-weighting identity and Kish's effective sample size; classify and count's bias and the adjusted count; the chi-square ball's worst case; anchor regression's two limits; and the classifier's odds as a density ratio. Pause here if you want to try them.

The books behind this part: Diakonikolas and Kane on algorithmic robust statistics; Quiñonero-Candela, Sugiyama, Schwaighofer and Lawrence on dataset shift; and Peters, Janzing and Schölkopf on causal inference; with the papers from Tukey to Trans-Lasso.

Sixty parts of sixty-five. The models on the rebuilt ImageNet kept their ranking but lost substantial accuracy on the rebuilt collection: a guarantee is only as good as its assumption about where the data come from. Next, Part sixty-one: optimal transport.

Where it goes next. Optimal transport, the geometry behind Wasserstein balls, is Part 61; Part 62 transports causal effects between populations; Part 63 relates robustness to privacy; Part 64 examines the behaviour of large models under shift; Part 65 revisits robustness in the dissertation.

Key results

The part's results in one place, for revision.

Tukey depth\(\displaystyle D(x;P)=\inf_{\lVert u\rVert=1}P\bigl(u^\top X\ge u^\top x\bigr),\qquad\allowbreak \text{Tukey }\allowbreak \text{median}=\arg\max_x D(x;P_n)\)
A planted cluster in d dimensions\(\displaystyle \text{coordinatewise }\allowbreak \text{median: } \lVert\hat\mu-\mu\rVert\approx\Phi^{-1}\Bigl(\frac{1}{2(1-\varepsilon)}\Bigr)\sqrt d\approx 1.25\,\varepsilon\sqrt d;\qquad\allowbreak \text{minimax: } \varepsilon+\sqrt{d/n}\)
Importance weighting\(\displaystyle \operatorname{E}_P\bigl[w(X)f(X,Y)\bigr]=\operatorname{E}_Q f(X,Y),\quad\allowbreak w=\frac{dQ_X}{dP_X};\qquad\allowbreak n_{\mathrm{eff}}=\frac{(\sum_i w_i)^2}{\sum_i w_i^2}\)
Black-box shift estimation\(\displaystyle Cw=\mu,\qquad\allowbreak C_{ij}=P_{\text{source}}(\hat y=i,\,y=j),\quad\allowbreak \mu_i=P_{\text{target}}(\hat y=i),\quad\allowbreak w_j=\frac{q(j)}{p(j)}\)
Chi-square DRO\(\displaystyle \sup\Bigl\{\sum_i q_i\ell_i:\ \tfrac n2\sum_i\bigl(q_i-\tfrac1n\bigr)^2\le\rho\Bigr\}=\bar\ell+\sqrt{2\rho\operatorname{Var}_n(\ell)}\quad\allowbreak \text{while }\allowbreak \text{every } q_i\ge 0\)
Anchor regression\(\displaystyle \hat b_\gamma=\arg\min_b\ \lVert(I-P_A)(y-Xb)\rVert^2+\gamma\,\lVert P_A(y-Xb)\rVert^2\)

Try it

Lab 60 · A planted cluster, and a shifted population

Replace 10% of n = 2,000 Gaussian points in d dimensions by a tight cluster and measure the error of the mean, the coordinatewise median, the geometric median and the spectral filter as d grows. Then estimate a target population's mean from a source sample whose covariate is shifted, with and without importance weights, and compare Kish's effective sample size with its formula.

Figure produced by Lab 60: A planted cluster, and a shifted population
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.stats.labs 60 needs numpy, scipy, matplotlib · download lab60.py · source on GitHub
error of the mean, d = 100                      2.02   theory eps x 2 x sqrt(d) = 2.00
error of the coordinatewise median, d = 100     1.43   theory 0.140 x sqrt(d) = 1.40
error of the geometric median, d = 100          1.15
error of the spectral filter, d = 100           0.24   clean points' mean 0.24   sqrt(d/n) = 0.22
filter removed                                  100% of the planted points, 4.7% of the clean ones
unweighted source mean                          2.003   target 2.700   95% interval covers 0.0%
importance-weighted mean                        2.704   95% interval covers 95.8%
Kish effective sample size                      368 of 600   theory n / E w^2 = 368
sd of the weighted mean / sd of the unweighted  1.37

A planted tenth moves the mean and both medians by an amount that grows like the square root of the dimension, while the filter stays at the clean sample's error; reweighting removes the bias of a shifted sample and pays for it in effective sample size.
The code (82 lines; it asserts its own result)
"""Lab 60: plant a cluster in high-dimensional data, then shift the covariates, and see which estimates survive."""

import numpy as np
from scipy import stats

from videos.coursekit import labs
from explainer.stats.kit import shift

TITLE = "A planted cluster, and a shifted population"
GOAL = ("Replace 10% of n = 2,000 Gaussian points in d dimensions by a tight cluster and measure the error of the "
        "mean, the coordinatewise median, the geometric median and the spectral filter as d grows. Then estimate a "
        "target population's mean from a source sample whose covariate is shifted, with and without importance "
        "weights, and compare Kish's effective sample size with its formula.")
TASKS = [
    "Move the planted cluster from 2 to 0.5 in every coordinate (value=0.5). Which estimators still notice it, and does the filter still remove it?",
    "Raise the covariate shift from 0.7 to 2. What happens to the effective sample size, and to the weighted interval's coverage?",
    "Estimate the weights with shift.logistic_density_ratio from the source x and 2,000 unlabelled target draws, in place of the true ratio. How much coverage is lost?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. contamination: n points from N(0, I_d), a fraction eps replaced by a cluster at (2, ..., 2)
    n, eps, value = 2000, 0.1, 2.0
    dims = np.array([10, 25, 50, 100])
    errs = [shift.robust_mean_errors(n, int(d), eps, rng, value) for d in dims]
    names = ("mean", "coord_median", "geo_median", "filter", "oracle")
    E = {k: np.array([e[k] for e in errs]) for k in names}
    med_shift = stats.norm.ppf(1 / (2 * (1 - eps)))  # the median of (1 - eps) N(0, 1) + eps at +infinity
    lab.row("error of the mean, d = 100", f"{E['mean'][-1]:.2f}   theory eps x 2 x sqrt(d) = {eps * value * 10:.2f}")
    lab.row("error of the coordinatewise median, d = 100", f"{E['coord_median'][-1]:.2f}   theory {med_shift:.3f} x sqrt(d) = {med_shift * 10:.2f}")
    lab.row("error of the geometric median, d = 100", f"{E['geo_median'][-1]:.2f}")
    lab.row("error of the spectral filter, d = 100", f"{E['filter'][-1]:.2f}   clean points' mean {E['oracle'][-1]:.2f}   sqrt(d/n) = {np.sqrt(100 / n):.2f}")
    lab.row("filter removed", f"{errs[-1]['removed_bad']:.0%} of the planted points, {errs[-1]['removed_good']:.1%} of the clean ones")

    # 2. covariate shift: source x ~ N(0, 1), target x ~ N(0.7, 1), y = 2 + x + noise in both
    m, delta, reps = 600, 0.7, 400
    target = 2 + delta
    plain, weighted, ess, cover_p, cover_w = (np.empty(reps) for _ in range(5))
    z = stats.norm.isf(0.025)
    for r in range(reps):
        x = rng.standard_normal(m)
        y = 2 + x + rng.standard_normal(m)
        w = np.exp(delta * x - delta ** 2 / 2)  # the density ratio N(delta, 1) / N(0, 1)
        ci = shift.weighted_mean_ci(y, w)
        plain[r], weighted[r], ess[r] = y.mean(), ci["mean"], ci["ess"]
        cover_p[r] = abs(y.mean() - target) <= z * y.std(ddof=1) / np.sqrt(m)
        cover_w[r] = ci["lo"] <= target <= ci["hi"]
    ess_theory = m / np.exp(delta ** 2)  # n / E w^2
    lab.row("unweighted source mean", f"{plain.mean():.3f}   target {target:.3f}   95% interval covers {cover_p.mean():.1%}")
    lab.row("importance-weighted mean", f"{weighted.mean():.3f}   95% interval covers {cover_w.mean():.1%}")
    lab.row("Kish effective sample size", f"{ess.mean():.0f} of {m}   theory n / E w^2 = {ess_theory:.0f}")
    lab.row("sd of the weighted mean / sd of the unweighted", f"{weighted.std() / plain.std():.2f}")
    lab.note = ("A planted tenth moves the mean and both medians by an amount that grows like the square root of the "
                "dimension, while the filter stays at the clean sample's error; reweighting removes the bias of a "
                "shifted sample and pays for it in effective sample size.")
    assert abs(E["mean"][-1] / (eps * value * 10) - 1) < 0.15, "the mean moves by eps x value x sqrt(d)"
    assert abs(E["coord_median"][-1] / (med_shift * 10) - 1) < 0.2, "each coordinate's median absorbs the planted mass"
    assert E["coord_median"][-1] > 2 * E["coord_median"][0] and E["geo_median"][-1] > 2 * E["geo_median"][0], "medians grow with d"
    assert np.all(E["filter"] < 2 * E["oracle"] + 0.05) and E["filter"][-1] < 0.35 * E["coord_median"][-1], "the filter tracks the oracle"
    assert errs[-1]["removed_bad"] > 0.9
    assert cover_p.mean() < 0.02 and abs(weighted.mean() - target) < 0.02, "weights remove the bias"
    assert cover_w.mean() > 0.89 and abs(ess.mean() / ess_theory - 1) < 0.1 and weighted.std() > plain.std(), "at the price of variance"

    fig, ax = labs.figure(2, size=(11, 4.2))
    for k, color, label in (("mean", labs.RED, "mean"), ("coord_median", labs.ORANGE, "coordinatewise median"),
                            ("geo_median", labs.PURPLE, "geometric median"), ("filter", labs.GREEN, "spectral filter"),
                            ("oracle", labs.GREY, "mean of the clean points")):
        ax[0].plot(dims, E[k], marker="o", color=color, ms=4, label=label, ls="--" if k == "oracle" else "-")
    ax[0].set(title="10% planted at (2, ..., 2): error of the estimated centre", xlabel="dimension d (log scale)",
              ylabel="distance from the true mean (log scale)", xscale="log", yscale="log")
    ax[0].legend(loc="center right")
    bins = np.linspace(1.8, 3.0, 61)
    ax[1].hist(plain, bins=bins, density=True, color=labs.RED, alpha=0.6, label=f"unweighted: covers {cover_p.mean():.0%}")
    ax[1].hist(weighted, bins=bins, density=True, color=labs.GREEN, alpha=0.6, label=f"weighted: covers {cover_w.mean():.0%}")
    ax[1].axvline(target, color=labs.GOLD, label="target mean")
    ax[1].set(title=f"Covariate shift of {delta}: {reps} source samples of {m}", xlabel="estimated target mean", ylabel="density")
    ax[1].legend(loc="upper center")
    lab.fig = fig
    return lab

Now change it

  1. Move the planted cluster from 2 to 0.5 in every coordinate (value=0.5). Which estimators still notice it, and does the filter still remove it?
  2. Raise the covariate shift from 0.7 to 2. What happens to the effective sample size, and to the weighted interval's coverage?
  3. Estimate the weights with shift.logistic_density_ratio from the source x and 2,000 unlabelled target draws, in place of the true ratio. How much coverage is lost?

Problems, with solutions

Try each problem before opening its solution.

  1. Contaminated scalar median. Contaminate \(N(0, 1)\) with \(\varepsilon\) of mass at \(+\infty\): show the median moves to \(\Phi^{-1}\big(\tfrac{1}{2(1 - \varepsilon)}\big) \approx 1.25\,\varepsilon\).

    Solution

    For epsilon<1/2 and added mass at positive infinity, (1-epsilon)Phi(m)=1/2. Hence m=Phi^-1(1/[2(1-epsilon)])=sqrt(pi/2) epsilon+O(epsilon^2). Coordinate biases can accumulate in Euclidean norm under a common-coordinate attack.

  2. Importance weights and ESS. Show \(E_P[w(X) f(X, Y)] = E_Q[f(X, Y)]\) under covariate shift, and that \(n_{\mathrm{eff}} = (\sum w)^2/\sum w^2\) equals the conditional information count for independent homoskedastic outcomes with a constant mean.

    Solution

    If Q_X is absolutely continuous with respect to P_X and the conditional outcome law is unchanged, integration gives E_P[w f]=E_Q[f]. Conditional on fixed covariates, independent outcomes with a constant conditional mean and variance sigma squared give Var(sum(wY)/sum w)=sigma squared sum(w squared)/(sum w) squared. Without constant mean/variance, or with estimated weights, this is not the full Hajek variance.

  3. Adjusted counts. Derive \(E[\hat q_{\mathrm{CC}}] = q\,\mathrm{TPR} + (1 - q)\,\mathrm{FPR}\), and show BBSE with two classes is Forman's adjusted count.

    Solution

    E[q_CC]=q TPR+(1-q)FPR. If TPR differs from FPR, q=(E[q_CC]-FPR)/(TPR-FPR). Binary BBSE gives the same moment equation. Estimated rates and projection produce sampling uncertainty and possible finite-sample bias; singular confusion matrices do not identify prevalence.

  4. Chi-square DRO. Show the \(\chi^2\)-ball worst case is \(\bar\ell + \sqrt{2\rho\,\widehat{\mathrm{Var}}(\ell)}\) when no weight hits zero.

    Solution

    Under (n/2)sum(q_i-1/n)^2<=rho, Cauchy-Schwarz bounds risk by mean(loss)+sqrt(2 rho Var_n(loss)). Equality holds for weights proportional to the centered loss perturbation while all weights remain nonnegative. At larger radii positivity binds; the checked KKT solver handles that regime.

  5. Anchor limits. Show anchor regression with \(\gamma = 1\) is OLS, and tends to unique 2SLS as \(\gamma \to \infty\) when the projected design has full column rank.

    Solution

    Since P_A is an orthogonal projection, W=I-(1-sqrt(gamma))P_A gives the criterion ||W(y-Xb)|| squared. At gamma=1 this is OLS. As gamma grows, minimization first prioritizes ||P_A(y-Xb)|| squared. A unique limit equals 2SLS if X'P_A X is invertible; otherwise a further criterion can select among projected-loss minimizers and there is no unique IV coefficient vector.

  6. Classifier odds. Show that a classifier's odds \(c/(1 - c)\), times \(n_0/n_1\), equal the density ratio \(q(x)/p(x)\).

    Solution

    In a pool of n0 source and n1 target draws, Bayes membership c=n1 q/(n0 p+n1 q). Therefore (n0/n1)c/(1-c)=q/p, with the orientation and class proportions specified. Fitted classifier probabilities need to approximate this posterior for the equality to be useful.

Notes and sources

Where it comes back

Part 61 studies optimal transport; Part 62 transports causal effects; Part 63 relates robustness and privacy; Part 64 examines large-model behavior; Part 65 revisits robustness in research.

Sources

  • The hook. B. Recht, R. Roelofs, L. Schmidt & V. Shankar, ICML (2019).

  • Depth. J. Tukey, Proc. ICM (1975); D. Donoho & M. Gasko, Ann. Stat. 20 (1992); M. Chen, C. Gao & Z. Ren, Ann. Stat. 46 (2018).

  • Efficient robustness.

    • I. Diakonikolas, G. Kamath, D. Kane, J. Li, A. Moitra & A. Stewart, FOCS (2016);
    • K. Lai, A. Rao & S. Vempala, FOCS (2016);
    • I. Diakonikolas, D. Kane & A. Stewart, FOCS (2017);
    • I. Diakonikolas & D. Kane, Algorithmic High-Dimensional Robust Statistics (2023).
  • List decoding. M. Charikar, J. Steinhardt & G. Valiant, STOC (2017).

  • Heavy tails.

    • A. Nemirovski & D. Yudin (1983); N. Alon, Y. Matias & M. Szegedy, STOC (1996);
    • S. Minsker, Bernoulli 21 (2015);
    • L. Devroye, M. Lerasle, G. Lugosi & R. Oliveira, Ann. Stat. 44 (2016);
    • G. Lugosi & S. Mendelson, Ann. Stat. 47 (2019) and Found. Comput. Math. 19 (2019);
    • S. Hopkins, Ann. Stat. 48 (2020); O. Catoni, Ann. IHP 48 (2012).
  • Covariate shift.

    • H. Shimodaira, J. Stat. Plan. Inference 90 (2000); L. Kish, Survey Sampling (1965);
    • J. Huang, A. Smola, A. Gretton, K. Borgwardt & B. Schölkopf, NeurIPS (2006);
    • M. Sugiyama et al., Ann. Inst. Stat. Math. 60 (2008).
  • Label shift.

    • G. Forman, ECML (2005);
    • M. Saerens, P. Latinne & C. Decaestecker, Neural Computation 14 (2002);
    • Z. Lipton, Y.-X. Wang & A. Smola, ICML (2018);
    • B. Schölkopf et al., ICML (2012).
  • DRO.

    • A. Ben-Tal, D. den Hertog, A. De Waegenaere, B. Melenberg & G. Rennen, Management Science 59 (2013);
    • J. Duchi & H. Namkoong, JMLR 20 (2019) and Ann. Stat. 49 (2021);
    • P. Mohajerin Esfahani & D. Kuhn, Math. Programming 171 (2018);
    • J. Blanchet & K. Murthy, Math. Oper. Res. 44 (2019); J. Blanchet, Y. Kang & K. Murthy, J. Appl. Prob. 56 (2019);
    • S. Sagawa, P. W. Koh, T. Hashimoto & P. Liang, ICLR (2020);
    • T. Hashimoto, M. Srivastava, H. Namkoong & P. Liang, ICML (2018);
    • W. Hu, G. Niu, I. Sato & M. Sugiyama, ICML (2018).
  • Invariance.

    • J. Peters, P. Bühlmann & N. Meinshausen, JRSS B 78 (2016);
    • D. Rothenhäusler, N. Meinshausen, P. Bühlmann & J. Peters, JRSS B 83 (2021);
    • M. Arjovsky, L. Bottou, I. Gulrajani & D. Lopez-Paz, arXiv:1907.02893 (2019);
    • E. Rosenfeld, P. Ravikumar & A. Risteski, ICLR (2021);
    • I. Gulrajani & D. Lopez-Paz, ICLR (2021).
  • Transfer.

    • S. Ben-David, J. Blitzer, K. Crammer, A. Kulesza, F. Pereira & J. Vaughan, Machine Learning 79 (2010);
    • S. Kpotufe & G. Martinet, Ann. Stat. 49 (2021); T. Cai & H. Wei, Ann. Stat. 49 (2021);
    • S. Li, T. Cai & H. Li, JRSS B 84 (2022);
    • Y. Ganin et al., JMLR 17 (2016); H. Zhao, R. Tachet des Combes, K. Zhang & G. Gordon, ICML (2019).
  • Detection.

    • A. Gretton, K. Borgwardt, M. Rasch, B. Schölkopf & A. Smola, JMLR 13 (2012);
    • D. Lopez-Paz & M. Oquab, ICLR (2017);
    • S. Rabanser, S. Günnemann & Z. Lipton, NeurIPS (2019);
    • A. Podkopaev & A. Ramdas, ICLR (2022);
    • F. Liu et al., ICML (2020).
  • Open problems. P. W. Koh et al. (WILDS), ICML (2021); J. Miller et al., ICML (2021).

  • Data. A. Azzalini & A. Bowman, Appl. Stat. 39 (1990); NHANES (CDC); W. Wolberg, W. Street & O. Mangasarian (1995).

  • Contamination-model distinction. Diakonikolas, Kane, Pensia & Pittas, NeurIPS (2023), arXiv:2312.01547, especially Theorem 1.3 and section 1.3.

About this partfrom its README

Part 60 of the 65-part course. The central question is which assumptions let a statistical procedure survive contamination or deployment shift.

The ImageNetV2 hook concerns the MatchedFrequency collection: evaluated models lost 11–14 percentage points of top-one accuracy. Benchmark gains generally transferred, but preserved rankings do not establish absence of adaptive overfitting. Collection variants have different gaps.

The chapters cover halfspace depth, efficient robust means, list decoding, heavy tails, covariate and label shift, DRO, causal invariance, transfer and shift detection. Their numerical examples have narrower scopes than the referenced theorems:

  • Angular sweeps calculate planar closed-halfplane depth at each query. The 50-by-50 grid search approximates the depth median; it is not an exact global maximizer or the high-dimensional minimax algorithm.
  • Deterministic spectral trimming removes five percent of extreme projections per iteration. It illustrates one planted-cluster attack and is not a certified adversarial filter. Four replicates and empirical Monte Carlo errors are saved.
  • K-means supplies four candidates in a separated-cluster illustration. General bounded-covariance list decoding has an order-one-over-root-alpha accuracy scale; that is not the Gaussian minimax lower bound.
  • The heavy-tail experiment uses a geometric median of 30 block means, not the covariance-optimal tournament estimator. Its empirical 99th percentiles from 400 runs have order-statistic uncertainty.
  • Huber mixtures and strong sample corruption have different computational guarantees. The strong/TV statistical-query barrier must not be applied to Huber mixtures, which admit order-epsilon algorithms.
What is computed and builtEmpirical examples and calibration

NHANES is a fixed, unweighted complete-case empirical extract of 5,176 adults, with age top-coded at 80. Pressure averages available SBP readings. It is not a survey-weighted national estimand. Source and unlabelled reference draws are independent, with replacement. Selection probability is proportional to exp(-(age-18)/20); the correctly specified log ratio is linear in age.

Procedure Repetitions Result Nominal 95% interval coverage (Monte Carlo SE)
Unweighted source mean, n=600 400 118.450, SD 0.677; empirical target 126.187 0.00% (0.00 percentage points)
Logistic-ratio weighted mean 400 126.242, SD 1.242; mean Kish ESS 267.6 95.25% (1.06 points)
Classify-and-count prevalence 300 0.6424; target .70 72.00% (2.59 points)
Projected BBSE prevalence 300 0.6993, SD 0.0699 92.33% (1.54 points)

The weighted interval uses a joint logistic-ratio/Hajek sandwich, centered separately within fixed source and target strata. It includes ratio fitting and the 2,000-point reference sample. Its normal approximation requires correct specification, overlap and regularity. Kish ESS diagnoses concentration; it is not an exact information count for heterogeneous outcomes and estimated weights. Plotted sampling curves are Gaussian fits.

The biopsy experiment is semi-synthetic. Each classifier trains on 250 biopsies; independent 150-point source calibration and 100-point target samples are drawn from a shared remaining class-conditional reservoir, with replacement. Labels have source prevalence 0.3726 and target probability .70, with fluctuating realized counts. This makes label shift exact conditional on the empirical reservoir. BBSE enforces the simplex and checks identifiability. The 100-resample percentile bootstrap is approximate: its observed undercoverage is retained. EM averages 0.6871; narrower spread does not establish posterior calibration. These are not clinical validation results.

For DRO, young-only training-loss balls cannot certify older-group membership just because a risk curve crosses a group's observed loss. The displayed curves are comparisons. Separate all-adult empirical calculations verify membership: for a group of base mass p, D_chi2(P(.|G)||P)=(1/p-1)/2 and D_KL=-log p. Both robust risks are checked against the group's empirical risk. Scalar KKT solves record feasible primal weights, divergences and dual gaps; no future-population guarantee is implied.

ICP uses Gaussian linear coefficient-invariance and residual-variance F tests with multiplicity corrections. Its no-false-parent probability requires valid testing of the true-parent model and an unchanged outcome mechanism. Anchor regression agrees with unique 2SLS in the infinite-penalty limit only when the projected design identifies the coefficients; the plotted example is underidentified for IV. The zero label represents gamma=1e-9.

Transfer shows a simplified one-source pooled-lasso/residual-correction core over 40 repetitions, with paired draws and Monte Carlo errors. Five coordinate shifts of .15 or 1 have total l-one contrast .75 or 5. It does not implement adaptive multi-source aggregation.

Detection uses a pooled label-invariant Gaussian-kernel bandwidth and plus-one permutation p-values. The statistic can be negative. The shifted example has MMD squared 0.1192, p=0.00332; the null comparison p=0.950. Held-out classifier accuracy 0.670, p=9.19e-10, uses the exact conditional hypergeometric, rather than binomial, law for balanced labels. Risk monitoring needs labels or additional assumptions.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: ImageNetV2. Upgrade card from Part 30.
  2. Depth (Tukey 1975). Minimax robust estimation via depth (Chen, Gao & Ren 2018).
  3. Efficient high-dimensional robust estimation. Filtering (Diakonikolas et al. 2016; Lai, Rao & Vempala 2016); sum-of-squares.
  4. List-decodable learning (Charikar, Steinhardt & Valiant 2017).
  5. Heavy tails in high dimensions. Median-of-means tournaments (Lugosi & Mendelson 2019).
  6. Covariate shift. Importance weighting and its variance (Board).
  7. Label shift (Lipton, Wang & Smola 2018) (Board).
  8. DRO. f-divergence and Wasserstein balls (Duchi & Namkoong 2021).
  9. Invariance. ICP; anchor regression (Rothenhäusler et al. 2021).
  10. Transfer learning minimax (Cai & Wei 2021).
  11. Detecting shift.
  12. Open problems.

Built: statkit.shift. Books: Diakonikolas & Kane.

Build the film

python -m videos.stats.stats60.compute        # the part's numbers, into .cache/stats60
python tools/build.py stats60                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats60 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats60. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python -m videos.stats.stats60.compute --force
pytest -q tests/test_stats60_checked.py tests/test_stats_kit_shift.py
python tools/build.py stats60 -q l
python tools/lecture_length.py stats60 --floor 50

All 11 computed inputs regenerated; 24 tests pass (17 audited local checks, seven legacy checks). Estimated English narration: 51.7 minutes. Audited kernels are used by this part; the shared statkit contains the earlier educational implementations. The instrument is DepthMap.

Scientific QA and data/proof receipts. The recorded English sampled visual checkpoint is complete. Chinese narration/caption tables, continuous listening/playback and final masters remain open; this checkpoint is not bilingual production approval.