Your dataset has sampling bias — how do you detect and correct it?
Written by the mlprep team · Updated
You have a dataset collected from production logs to train a new ML model. How do you detect whether it has sampling bias, and what techniques can you use to correct for it?
Production data is never a random sample of the population you want to model. It's filtered by the current system's decisions, user self-selection, and survivorship. This creates systematic bias that, if ignored, makes your model reinforce existing patterns rather than learning the true signal.
Types of sampling bias in ML systems#
1. Selection bias (the current model filters what you see)#
A recommendation system that never shows item X to user Y means you have no data on whether Y would like X. You only have feedback on items the current model chose to show. Training on this data without correction means the new model inherits the current model's blind spots.
This is the "bandit feedback" problem: you observe rewards only for the actions you took, not for actions you didn't take.
2. Survivorship bias (you only see users who stayed)#
If you build a churn prediction model using data from active users, you're missing users who already churned. Your model learns the patterns of survivors, not the patterns that predict churn. Similarly: modeling loan default from approved loans (you never see what would have happened with rejected applicants).
3. Popularity bias (common items dominate)#
Popular items have 1000x more training examples than niche items. The model learns to recommend popular items (which get more clicks, which generates more training data — a feedback loop). Niche items that would be highly relevant to specific users are never explored.
4. Temporal bias (the past ≠ the future)#
Data collected during a promotion, holiday season, or viral event doesn't represent normal behavior. If you train on Black Friday data, your model thinks everyone always buys 5 items per session.
Detection methods#
Compare feature distributions#
from scipy.stats import ks_2samp
for feature in features:
stat, pval = ks_2samp(
training_data[feature],
production_sample[feature]
)
if pval < 0.01:
print(f"{feature}: distribution shift detected (KS stat={stat:.3f})")Population Stability Index (PSI): measure how much the distribution shifted between training and production for each feature. PSI > 0.2 indicates significant shift.
Propensity analysis: for each example in your training set, estimate the probability it would have been sampled given the current system's behavior. If some regions of feature space have near-zero propensity, you have coverage gaps.
Subgroup analysis: compute your metric for each subgroup (geography, demographic, user segment). If performance varies wildly across subgroups, the underperforming groups are likely underrepresented in training.
Correction techniques#
1. Inverse Propensity Weighting (IPW)#
Weight each training example by the inverse of its probability of being observed:
weight_i = 1 / P(example_i was observed | features_i)Examples that were unlikely to be observed (rare items, niche users) get upweighted. Examples that were very likely to be observed (popular items) get downweighted.
The propensity P(observed | features) is estimated separately — often with a logistic regression on whether an item was shown, conditioned on user and context features.
Problem: if propensity is near zero (some examples are almost never observed), the weight explodes → high variance. Fix: clip weights at some maximum (say 100) or use doubly-robust estimators.
2. Domain adaptation#
Treat training data and production as two domains. Use domain adaptation techniques (importance reweighting, adversarial training) to learn representations that transfer from training distribution to production distribution.
3. Counterfactual evaluation / off-policy learning#
For recommendation/ranking: estimate what a new policy would have achieved using historical data from the old policy. IPS (Inverse Propensity Scoring) or SNIPS (Self-Normalized IPS) let you evaluate new models without deploying them.
new_policy_value = mean(
reward_i * new_policy_probability_i / old_policy_probability_i
)4. Collect unbiased data (most reliable)#
Run a small fraction of traffic (1-5%) with random exposure: show random items, collect unbiased feedback. This "exploration" data is expensive (bad user experience) but gives you ground truth for calibrating your biased models.
5. Stratified resampling#
If you know the target population distribution (e.g., production traffic is 40% mobile, 60% desktop, but training is 80% desktop, 20% mobile), resample or reweight to match:
weight_mobile = (0.40 / 0.20) # upweight mobile
weight_desktop = (0.60 / 0.80) # downweight desktopYou mentioned inverse propensity weighting. In practice, how do you estimate the propensity scores when the selection mechanism is a complex recommendation model with billions of parameters? And what goes wrong when propensity estimates are inaccurate?
Estimating propensity for complex systems#
In a real recommendation system, the "true" propensity P(item shown to user | context) is determined by the full recommendation pipeline: retrieval, ranking, re-ranking, business rules. Modeling this exactly is intractable.
Practical approaches#
-
Log the propensity directly: if you control the serving system, log the probability/score assigned to each shown item at serving time. This is the gold standard — you get the true propensity by construction. No estimation needed.
-
Position-based propensity: for ranked lists, users are more likely to see items higher in the list. Model propensity as a function of position: P(observed | position) = 1/position^α (fitted from clickstream data). Items at position 1 have propensity ~1, items at position 50 have propensity ~0.02.
-
Simplified propensity model: fit a simpler model (logistic regression) to predict "was this item shown" given user and item features. It won't perfectly match the complex recommender's behavior, but it captures the major biases (popular items have high propensity, niche items have low propensity).
What goes wrong with inaccurate propensity#
-
Underestimated propensity → overweighted examples → high variance. A few examples get extreme weights and dominate the loss. The model effectively trains on a handful of examples.
-
Overestimated propensity → underweighted examples → still biased. You haven't corrected enough.
-
Systematic errors → new bias. If your propensity model has a systematic blind spot (say it overestimates propensity for all niche items), your correction introduces a new systematic bias.
Robust alternatives#
-
Clipped IPS: cap weights at a maximum (w_max = 50-100). Reduces variance at the cost of some residual bias. In practice, this tradeoff is almost always worth it.
-
Self-Normalized IPS (SNIPS): divide each weight by the sum of all weights. This removes the dependence on absolute propensity accuracy — only relative propensities matter.
-
Doubly-robust estimator: combines a reward model (predicts reward for any action) with IPS. If either the propensity model or the reward model is correct, the estimate is unbiased. Provides a safety net for propensity estimation errors.
DR_estimate = mean(
reward_model(x_i, a_i) +
w_i * (observed_reward_i - reward_model(x_i, a_i))
)If the reward model is perfect, the IPS correction term is zero (doesn't matter if propensity is wrong). If propensity is perfect, the reward model errors cancel out. You only need one of them to be right.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Production data is always biased: selection bias (model filters observations), survivorship bias, popularity bias, temporal bias. Detect with KS tests on feature distributions, PSI, propensity analysis, and subgroup evaluation. Correct with: inverse propensity weighting (upweight underrepresented examples), doubly-robust estimators (robust to propensity errors), stratified resampling, or collecting unbiased exploration data. Log propensity at serving time when possible — estimating it retroactively is error-prone.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How does Simpson's paradox relate to sampling bias, and can you give an ML example where ignoring a confounding variable reverses the apparent relationship?
- Your recommendation model has a feedback loop — it only recommends items it's confident about, so it never collects data on uncertain items. How do you break this loop without hurting user experience?
- When is reweighting insufficient and you fundamentally need new data collection to fix the bias?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
How does causal inference differ from correlation-based ML, and when does it matter?
What is the multiple testing problem and how do you control for it?
How do you determine the sample size needed for an A/B test?
Walk me through how you'd design and analyze an A/B test