Sub topic 11
Errors from distribution shift
This chapter assumes you can compute accuracy, precision, recall and F1, and that you know what train, validation and test splits are. It also assumes basic pandas and scikit-learn. It builds on the earlier chapters on slicing results and building an error taxonomy.
What distribution shift is
A model learns from a training distribution, which is the mix of texts, labels and writing styles in its training data. It is later used on data from a deployment distribution. Distribution shift means these two differ. Your validation score is only trustworthy for data that looks like the validation set, so a shift can leave that score high while real-world quality drops.
Shift often shows up as a cluster of errors that your taxonomy cannot explain with a single linguistic cause. Typical signs:
- Errors concentrate in one source, time period or genre.
- Many errors contain words the model never saw in training.
- Confidence stays high on wrong answers.
- The score on a fresh sample is much lower than the held-out test score.
Three kinds of shift
The kind of shift tells you what kind of fix to try.
| Kind | What changes | NLP example | Typical symptom |
|---|---|---|---|
| Covariate shift | The inputs, but not the rule linking text to label | A sentiment model trained on product reviews is applied to tweets | Unknown words, new styles, lower accuracy |
| Label shift (prior shift) | The proportion of each class | Complaints triple during an outage | Precision drops for the class that became more common or rarer |
| Concept shift | The meaning of the label for the same input | "Sick" changes from negative to positive slang | The same text now deserves a different label |
Real shifts mix these. Treat the categories as hypotheses to test, not as a classification you can read off from one number.
Step 1: Measure how the inputs differ
Start with cheap checks on the text itself. The out-of-vocabulary (OOV) rate is the share of tokens in the new data that never appeared in training. A high OOV rate is a strong hint of covariate shift.
train = [
"great phone",
"battery died in a day",
"love it",
"screen is sharp and bright",
]
shifted = [
"lol this slaps fr",
"ngl battery is mid",
"screen is sharp",
"rizz",
]
train_vocab = {w for text in train for w in text.lower().split()}
def oov_rate(texts):
tokens = [w for text in texts for w in text.lower().split()]
return sum(w not in train_vocab for w in tokens) / len(tokens)
def mean_length(texts):
return sum(len(t.split()) for t in texts) / len(texts)
print(f"train OOV={oov_rate(train):.2f} mean tokens={mean_length(train):.1f}")
print(f"shifted OOV={oov_rate(shifted):.2f} mean tokens={mean_length(shifted):.1f}")The training texts have an OOV rate of 0 by construction, so compare the shifted set against a held-out in-domain set in real work. The in-domain held-out OOV rate is your baseline. Some OOV is always present, so the gap matters, not the absolute value.
Word counts miss many differences, such as punctuation habits, casing, emoji, code-mixing and topic. A more general check is a domain classifier. Train a simple model to tell training texts apart from new texts. If it can do so well, the two sets differ in ways the model can see.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
source = [
"The battery lasts all day and the screen is excellent.",
"I returned this item because it arrived damaged.",
"Good value for the price, would buy again.",
"The camera quality is disappointing in low light.",
"Shipping was fast and the packaging was careful.",
"The keyboard feels cheap and several keys stick.",
"Setup was simple and the instructions were clear.",
"The speaker sounds thin at high volume.",
]
target = [
"lol this phone slaps fr fr",
"ngl the battery is mid #disappointed",
"cant believe it died on day 2 smh",
"omg love it!!! best purchase ever",
"bruh the screen cracked, so done",
"tbh its fine i guess lmao",
"this thing is trash, wasted my money",
"yo the camera goes hard at night",
]
texts = source + target
is_target = [0] * len(source) + [1] * len(target)
clf = make_pipeline(
TfidfVectorizer(lowercase=True),
LogisticRegression(max_iter=1000),
)
cv = StratifiedKFold(n_splits=4, shuffle=True, random_state=0)
auc = cross_val_score(clf, texts, is_target, cv=cv, scoring="roc_auc")
print(f"domain-classifier AUC: {auc.mean():.2f}")An AUC near 0.5 means the classifier cannot separate the two sets, so shift is unlikely to explain your errors. An AUC near 1.0 means the sets are easy to tell apart. Inspect the classifier's top-weighted features to see what differs, such as slang, hashtags or formatting.
Step 2: Measure the performance gap by domain
Input differences only matter if they hurt the task. Compute the metric per domain, and keep the count next to it. Use the uncertainty tools from the earlier chapter before you act on a gap.
import pandas as pd
df = pd.DataFrame({
"domain": ["reviews"] * 6 + ["tweets"] * 6,
"label": ["pos", "neg", "pos", "neg", "pos", "neg",
"neg", "neg", "pos", "neg", "neg", "pos"],
"pred": ["pos", "neg", "pos", "neg", "pos", "pos",
"pos", "neg", "neg", "pos", "neg", "pos"],
})
df["correct"] = df["label"] == df["pred"]
print(df.groupby("domain")["correct"].agg(["mean", "count"]))
# Compare class proportions to look for label shift.
print(pd.crosstab(df["domain"], df["label"], normalize="index").round(2))The first table shows the accuracy gap. The second shows whether the class mix differs. If tweets contain far more neg labels than reviews, part of the drop may come from label shift, and thresholds tuned on the source data will be wrong for the target.
Step 3: Separate shift from other causes
A gap between domains has several possible causes, and they need different fixes.
- Label noise. The target data may have been annotated by different people or with different guidelines. Read a sample of confident errors in the target domain. If the model looks right and the label looks wrong, you have an annotation problem, not a model problem.
- Small sample. A gap measured on 30 tweets may be noise. Report an interval for each slice.
- Leakage in the source score. Near-duplicates between train and test can make in-domain performance look inflated, which makes the gap look like a shift. Deduplicate before concluding.
- A genuinely harder task. Tweets may be harder even for humans. Compare against a human or simple-baseline score on the target domain if you can.
Apply your taxonomy to the target-domain errors only. Compare its category proportions with those from the source domain. Categories that grow in the target domain are the ones the shift created. For example, unknown slang or sarcasm may rise from 5% to 40% of errors.
Time shift
Language and the world change. A model trained on 2021 news will not know a 2025 product name, and a topic classifier may meet new events. Time shift is the shift you can most easily test before it hurts you.
- Split by date, not randomly: train on older data, validate on newer data. A random split mixes periods and hides the drift.
- Evaluate on the most recent slice separately and track it over time.
- Look at errors involving named entities and new terms first.
Confidence under shift
Models usually become less calibrated on shifted data. Confidence stays high while accuracy falls, so the model gives few warnings. Compute the expected calibration error separately on in-domain and out-of-domain data. Do not reuse a temperature or threshold fitted on the source domain without checking it on the target. If a cluster of high-confidence errors appears only in the target domain, treat that as a strong sign of shift.
Choosing a fix
Match the fix to the kind of shift you found.
| Finding | Likely fix | Watch out for |
|---|---|---|
| High OOV, informal text | Normalize text, use a tokenizer with subwords, add target-like data | Normalization can remove signal such as capitalization or emoji |
| Domain-specific vocabulary | Continue pretraining on unlabeled target text, then fine-tune | Needs enough unlabeled text, and takes compute |
| Few labeled target examples | Label a few hundred target examples, chosen from the errors, and add them to training | Choosing only errors biases the sample, so also include random examples |
| Label shift | Re-weight classes or adjust decision thresholds on a target sample | Needs a target sample with trusted labels |
| Concept shift | Relabel with current guidelines and retrain on recent data | Old data may now be wrong and should be down-weighted or dropped |
| Shift keeps changing | Monitor the input and prediction distribution, and re-evaluate on a schedule | Monitoring without labels tells you something changed, not how much accuracy fell |
Keep the original in-domain test set unchanged after you fix the shift. If the target score rises but the source score falls, you have traded one problem for another. The final chapter covers regression checks.
Common mistakes
- Concluding shift from a gap without checking the sample size or label quality.
- Fixing the vocabulary difference when the real change is in class proportions.
- Tuning on the target test set, which removes your only honest estimate of target performance. Split the target data into a development part and a final test part.
- Treating unlabeled production data as if it had labels. You can measure input drift without labels, but not accuracy.
Exercise
A sentiment classifier scores 91% accuracy on its held-out test set of product reviews but 74% on 200 labeled tweets. The tweets have an OOV rate of 30% against the training vocabulary, compared with 4% for the review test set. The class mix is similar in both sets. Which kind of shift is most likely, and what are your first two steps?
Show answer
Covariate shift is most likely, since the inputs differ (high OOV) while the class proportions are similar. First, report an uncertainty interval for the 74% figure (a bootstrap over the 200 tweets) and read a sample of the tweet errors to rule out label noise. Second, categorize those errors in a taxonomy and compare its proportions with those from the review errors, to see which categories (such as slang or hashtags) grew. Then choose a fix, such as adding labeled tweets or normalizing the text.