Sub topic 10
Reweighting labeled data under covariate shift
This chapter assumes you know binary classification metrics, basic pandas and scikit-learn, and how train and test splits work. It also assumes you have read the earlier chapters on drift detection and on evaluating matured cohorts. Here you will learn how to reuse labeled historical rows to estimate how a model performs on new, unlabeled traffic.
The problem this solves
A matured cohort tells you how the model did weeks or months ago. The traffic you scored this week has no labels yet. If the inputs this week look different from the labeled cohort, the old accuracy number may no longer describe the model.
Importance weighting gives a label-free estimate under one assumption. The labeled rows you already have are treated as a sample from the wrong distribution. You reweight them so they look like the new traffic, and you then compute the metric on the reweighted rows.
Covariate shift
Covariate shift means the distribution of the features, P(x), changes between a reference period and a new period. The relationship between features and label, P(y | x), stays the same.
Here is a concrete case. A credit model was validated on applicants aged 30 to 50. A marketing campaign now brings in many applicants under 25. Younger applicants are new to the model, but a given combination of income, debt and history still carries the same default risk as before.
If that holds, the model's error rate within each region of feature space is unchanged. Only the mix of regions has changed. A region that was rare in the reference data and is common now should count for more.
The estimate is:
new_accuracy ≈ Σ w(x_i) · correct_i / Σ w(x_i)
w(x) = p_new(x) / p_ref(x)Each correct or incorrect outcome on a labeled reference row is multiplied by its density ratio w(x). This is the ratio of how likely that row is in the new data to how likely it is in the reference data.
Estimating the weights with a domain classifier
You rarely know the two densities. You can avoid estimating them directly. Train a classifier to tell reference rows from new rows. This is a domain classifier. Its output probability is related to the density ratio by Bayes' rule:
p_new(x) / p_ref(x) = [ P(new | x) / P(ref | x) ] · [ n_ref / n_new ]The second factor corrects for the two sample sizes. Without it, the weights would shift whenever you changed how many rows you sampled.
import numpy as np
from sklearn.linear_model import LogisticRegression
def covariate_shift_weights(X_ref, X_new, clip=20.0):
"""Weights for labeled reference rows that mimic the new feature distribution."""
X = np.vstack([X_ref, X_new])
domain = np.r_[np.zeros(len(X_ref)), np.ones(len(X_new))]
clf = LogisticRegression(max_iter=1000).fit(X, domain)
p_new = clf.predict_proba(X_ref)[:, 1]
# Density ratio p_new(x) / p_ref(x), corrected for the two sample sizes.
w = (p_new / (1.0 - p_new)) * (len(X_ref) / len(X_new))
return np.clip(w, 0.0, clip)
# Estimated accuracy on the new data, using only labeled reference rows:
# correct = (y_ref == y_pred_ref).astype(float)
# est_acc = np.average(correct, weights=covariate_shift_weights(X_ref, X_new))Three details matter in this function:
- The classifier is scored on the reference rows only. Those are the rows that have labels, so those are the rows that need weights.
p_new / (1 - p_new)is the odds that a row came from the new data. Multiplying by the sample-size ratio turns odds into a density ratio.np.clipcaps extreme weights. This trades a small bias for a large cut in variance, as the next sections explain.
The overall flow
The diagram shows where the pieces come from. Labeled reference rows and unlabeled new rows feed the domain classifier. Its weights are applied to the correctness of the model on the labeled rows.
A worked example
Suppose the reference data has two segments, and you know the accuracy in each.
| Segment | Share of reference | Share of new data | Accuracy in segment |
|---|---|---|---|
| Established customers | 80% | 40% | 95% |
| New customers | 20% | 60% | 70% |
The reference accuracy is 0.8 × 0.95 + 0.2 × 0.70 = 0.90. The weights are 0.4 / 0.8 = 0.5 for established customers and 0.6 / 0.2 = 3.0 for new customers.
The weighted estimate is (0.8 × 0.5 × 0.95 + 0.2 × 3.0 × 0.70) / (0.8 × 0.5 + 0.2 × 3.0) = (0.38 + 0.42) / 1.0 = 0.80.
The model did not change, but expected accuracy on the new mix is 0.80, ten points lower than the reference number. A plain accuracy figure from the old cohort would have missed this.
The assumptions behind the estimate
The method is only as good as its assumptions. Check each one before you trust the result.
- P(y | x) is unchanged. This is the covariate shift assumption. If fraudsters change tactics, or a new policy changes who defaults, the same features now carry different outcomes. The weights cannot see this, because they use no new labels.
- Overlap. Every region where new data lives must also have reference rows. If the new traffic includes a segment that never appeared in the reference, no weight can create information about it. The weights for the nearest rows will grow very large instead.
- The reference labels are representative of the reference distribution. If the labeled rows were selected in a biased way, for example only approved loans, the weighted estimate inherits that bias. The earlier chapter on censoring covers this problem.
- The domain classifier is good enough. A weak classifier gives noisy weights. A badly overfit classifier gives overconfident weights.
Variance and effective sample size
Weights concentrate influence on a few rows. If a handful of reference rows carry weights of 15 or 20, the estimate depends on those rows and swings with their labels.
Measure this with the effective sample size (ESS):
import numpy as np
def effective_sample_size(w):
w = np.asarray(w, dtype=float)
return float(w.sum() ** 2 / (w ** 2).sum())When all weights are equal, ESS equals the number of rows. When a few weights dominate, ESS falls sharply. If you have 50,000 labeled rows and an ESS of 300, the estimate behaves as if it came from about 300 rows. Report this next to the estimate, in the same way the matured-cohort chapter reported label coverage.
Clipping lowers variance but adds bias, because the clipped rows under-represent the new distribution. Choose the cap by looking at the weight distribution rather than using a fixed number. A common starting point is the 99th percentile of the weights. Then compare estimates at several caps. If the estimate moves a lot between caps, treat it as unreliable.
Practical choices
- Features for the domain classifier. Use the model's input features. You may also add the model's score. A shift in the score distribution is the part of covariate shift that matters most for performance.
- Classifier type. Logistic regression is stable and gives smooth probabilities. Gradient-boosted trees capture interactions but tend to give extreme probabilities, so they need regularization and calibration.
- Fit and apply on different rows. If the domain classifier is trained on a row and then weights that same row, it can memorize it and give an extreme weight. Use cross-fitting: train on some folds and score the held-out fold.
- Which reference rows. Use matured labeled rows. Immature rows have missing labels that are not random, which brings back the bias from the earlier chapters.
- Which metric. Accuracy works as a weighted mean. For AUC, precision and recall, pass the weights to the metric, for example
sample_weightin scikit-learn. The result is then an estimate for the new distribution.
Common errors
- Forgetting the sample-size correction, so the weights have the wrong scale. Normalizing by the sum of weights, as
np.averagedoes, hides this in the final number but not in the ESS or in clipping. - Scoring the domain classifier on rows it was trained on.
- Clipping so hard that the weights become nearly flat, which returns the unweighted number.
- Including features that identify the period directly, such as a timestamp or a campaign ID. The classifier then separates the domains perfectly, probabilities go to 0 and 1, and the weights explode.
- Reading the estimate as proof that nothing is wrong. If the weights are near 1 and the estimate matches the reference, only the claim "covariate shift is small" is supported.
Confirm the method on your own data. Once late labels for the new period arrive, compare the estimate with the true accuracy, as the later chapter on backtesting describes.
Exercise
A reference set has 10,000 labeled rows and the new window has 2,000 unlabeled rows. A domain classifier gives a reference row a probability of 0.30 of coming from the new data. What is that row's importance weight, before clipping? Name one reason you would still not trust an accuracy estimate built from these weights.
Show answer
The odds are 0.30 / 0.70 ≈ 0.4286. The sample-size ratio is 10,000 / 2,000 = 5. The weight is about 0.4286 × 5 ≈ 2.14. You would not trust the estimate if P(y | x) changed (concept drift), if the new data has regions with no reference rows (no overlap), or if the effective sample size is very small. Any one of these is a valid answer.
Exercise
Why does the chapter recommend cross-fitting the domain classifier?
Show answer
A classifier scored on the same rows it was trained on can memorize them and return extreme probabilities, which gives extreme weights. Training on some folds and scoring the held-out fold gives weights that reflect real separability between the two periods.