Skip to content
mentoor

Topic 5 of 6 · 5 min read

Class imbalance and sampling bias

Goal: Handle a rare positive class with class weights or resampling and check performance for under-represented groups.

When one class is rare, accuracy hides failure, so pick metrics for the rare class, rebalance the training data only, and report results for each group, not just overall. A fraud model that says "not fraud" every time is right 99.8 percent of the time if 0.2 percent of transactions are fraud, and useless.

Check yourself · 1 of 3

On a dataset where 0.5 percent of rows are positive, why is accuracy a poor metric?

Choose one answer

Why it matters

Training treats every example equally, so the common class dominates. The model learns to predict it. Separately, if the data was gathered in a skewed way, the model performs worse on groups that appeared less, even when overall numbers look fine.

How to handle imbalance

  1. Use the right metrics. Look at precision, recall, F1 and precision-recall curves for the rare class, plus the confusion matrix. The Google ML Crash Course explains why accuracy misleads here.
  2. Start with class weights. Many models accept them: LogisticRegression(class_weight="balanced") makes errors on the rare class cost more. It changes nothing in the data.
  3. Resample if needed. Downsample the majority class (and upweight it to keep probabilities calibrated), or oversample the minority with imbalanced-learn. Synthetic methods such as SMOTE create new rows between existing ones.
  4. Resample only the training data, and do it inside the cross-validation loop. Resampling before splitting puts copies of the same row on both sides: leakage.
  5. Choose the decision threshold for your costs. Missing a fraud may cost far more than reviewing a false alarm.

Checking for bias in the sample

  1. Compare the sample with the population the model will serve: region, device, age, language.
  2. Slice the metrics. Compute recall and precision per group on the test set. Model cards report this by group.
  3. Collect more data for weak groups where you can. Reweighting helps a little; new data helps more.

Before and after

# Weak: accuracy only, no weights
model = LogisticRegression().fit(X_train, y_train)
print(accuracy_score(y_test, model.predict(X_test)))
# Better: weights, rare-class metrics, per-group recall
model = LogisticRegression(class_weight="balanced").fit(X_train, y_train)
pred = model.predict(X_test)
print(classification_report(y_test, pred))
for g, idx in test.groupby("region").groups.items():
    print(g, recall_score(y_test.loc[idx], pred[test.index.get_indexer(idx)]))

What goes wrong

  • Oversampling before the split. Duplicates appear in test, and scores inflate.
  • Balancing the test set. The test should keep the real class ratio.
  • Only overall metrics. A model can be strong overall and poor for a small group.

Examples

Accuracy on a rare class

A model flags equipment failures, which happen in 1 of 500 readings. It predicts 'no failure' for everything and scores 99.8 percent accuracy with zero recall. The fix is reporting recall and precision for failures, adding class weights and choosing a threshold from the cost of a missed failure.

Sampling bias in voice data

A speech model is trained on recordings from a lab with mostly one accent. Overall word error looks fine, but slicing by accent shows much higher errors for two accents with few recordings. The remedy is to collect more audio for those accents, not just to reweight.

Key points

  • Accuracy misleads on a rare class; use precision, recall and a confusion matrix for that class.
  • Try class weights first, then resampling, and apply resampling to training data only.
  • Resample inside cross-validation, never before splitting.
  • Keep the real class ratio in the test set so it reflects production.
  • Report metrics per group; overall numbers can hide a weak group.

Common mistakes

  • Reporting accuracy for a dataset with a rare positive class.
  • Oversampling or running SMOTE on the full dataset before the train and test split.
  • Rebalancing the test set so it no longer matches production.
  • Checking only overall performance and never slicing by group.

Check yourself · 2 of 3

When should you oversample the minority class during cross-validation?

Choose one answer

Check yourself · 3 of 3

A model's overall recall is 0.9, but recall for one region is 0.5. What is the best next step?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic