Imbalanced Data

Handling rare positive classes with the right metrics, class weights, resampling and threshold tuning.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Evaluation Metrics

Fraud, churn, disease and defects are rare events. With 1% positives, a model that always says no is 99% accurate and completely useless. Imbalance is mostly an evaluation and decision problem, not a mysterious data defect.

Toolbox, roughly in order of what to try

  • Use the right metric: PR AUC, recall at fixed precision, or cost-weighted metrics.
  • Tune the decision threshold on validation data instead of using 0.5.
  • Class weights (class_weight='balanced', scale_pos_weight in XGBoost).
  • Resampling: random undersampling of the majority, oversampling of the minority, or SMOTE variants via imbalanced-learn.
  • Collect more positive examples when possible; nothing beats real data.

Pitfalls

  • Resampling before splitting or outside the CV loop leaks synthetic copies into validation.
  • Oversampling changes predicted probabilities; recalibrate if you need real probabilities.
  • Stratify every split so each fold contains positives.

Good enough to move on when you can compare class weights, SMOTE and threshold tuning fairly within a pipeline and explain which you would deploy.

Key concepts

  • Metrics for rare classes
  • Threshold tuning
  • Class weights
  • Under- and oversampling
  • SMOTE with imbalanced-learn
  • Cost-sensitive evaluation

Mini project

On the Kaggle Credit Card Fraud dataset, compare no treatment, class weights, SMOTE and threshold tuning inside stratified CV, reporting PR AUC and recall at 90% precision.

Check yourself

Why must SMOTE be applied only to the training portion of each fold?

Free resources