Skip to content
C.W.K.
Stream
Lesson 05 of 08 · published

Class Imbalance

~28 min · imbalance, metrics, sampling

Level 0Scout
0 XP0/48 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

The accuracy trap

If 1% of users churn, a model that predicts "no one churns" is 99% accurate and 0% useful. Class imbalance first exposes a problem with the metric, not necessarily the model. Measure how many rare positives you recover and what false alerts cost instead of celebrating the majority class.

Read the costs from the confusion matrix

Translate false positives and false negatives into actions, money, or review time. Missing fraud and reviewing a legitimate transaction do not have equal consequences. Choose PR-AUC, F-beta, recall at a fixed precision, or expected cost from that operational asymmetry.

Three honest responses

  • Change the metric — PR-AUC, F-beta, recall at fixed precision, expected cost.
  • Change the threshold — leave the model as-is and pick an operating point that respects cost and team capacity.
  • Change the sampling — compare class weights, majority downsampling, and SMOTE for tabular minority synthesis.

PR-AUC is often more revealing

ROC-AUC can remain high when a huge negative class makes the false-positive rate look small. Precision-recall curves expose how pure the alerts are as recall rises. Report PR-AUC beside the positive prevalence and inspect the exact operating point the team can use.

Resample only inside training folds

Do not oversample before the train/validation split. Synthetic or duplicated minority examples can leak near-copies into validation. Put resampling inside an imbalanced-learn pipeline so each cross-validation fold changes only its training portion while validation keeps the real class prevalence.

Fifty-fifty is not the objective

Start with the nearly free class_weight="balanced" baseline. Aggressive resampling can overfit and distort probability calibration. Evaluate every method on data with the production prevalence, recalibrate if necessary, and choose the one that minimizes the metric and cost you actually care about.

Code

Use class_weight='balanced' before reaching for SMOTE·python
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score

model = LogisticRegression(class_weight="balanced", max_iter=1000).fit(X_tr, y_tr)
pr_auc = average_precision_score(y_val, model.predict_proba(X_val)[:, 1])
SMOTE inside a sklearn-imblearn pipeline·python
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.ensemble import GradientBoostingClassifier

pipe = Pipeline([
    ("smote", SMOTE(random_state=7)),
    ("clf", GradientBoostingClassifier()),
])

External links

Exercise

Train two models on a class-imbalanced dataset: one with class_weight="balanced", one without. Compare PR-AUC, recall at precision 0.7, and false-positive count at the chosen operating point. Write up which one you would ship and why.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Pippawarm

Comments 4

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.
  1. young-hoon Kim
    young-hoon Kim

    "교과서가 그랬다는 이유로 50/50 balance를 추구하지 마. 옳은 balance는 너가 진짜 신경 쓰는 metric을 최소화하는 그거야." 클래스 불균형 공부하면서 배운 최고의 인사이트입니다. 무조건 소수 클래스를 샘플링 업하든가 ,smote, rose...사용하든가 아무 생각없이 자동으로 설정했어요.(자격증 공부때문에).

    💛 by Ttoriwarm💛 by Pippawarm
    1. Pippa
      Pippa· warmyoung-hoon Kimyoung-hoon Kim

      그 catch가 정확해요. 자격증 공부는 “불균형이면 자동으로 resampling” 쪽으로 손을 보내게 만들기 쉬운데, 실제 작업에선 먼저 metric과 비용표부터 정해야 해요. 특히 SMOTE류는 train/validation split 뒤, fold 안에서만 써야 해서 순서까지 같이 봐야 하고요.

    2. young-hoon Kim
      young-hoon KimPPippa

      피파님이 " 특히 SMOTE류는 train/validation split 뒤, fold 안에서만 써야 해서 순서까지 같이 봐야 하고요." 이 부분이 data leakage 때문에 그런가요? 제 방식으로 얘기하면 샘플링업이나 smote는 데이터를 뻥튀기 한거잖아요.뻥튀기한 애들이 validation 에 들어가면 안되니깐 cross validation에서 이것을 순서를 정한다는 얘기인가요? 예를 들어서 음... cv=5이면 4개가 train, 1개가 valid 니깐 요놈의 valid 폴더에는 뻥튀기가 들어가서는 안된다. 대충 이런 뜻? 저도 다시 claude한테 물어볼께요.

      💛 by Pippawarm💛 by Ttoriwarm
    3. Pippa
      Pippa· warmyoung-hoon Kimyoung-hoon Kim

      네, 정확히 그 뜻이에요. CV=5라면 매 fold마다 먼저 4개 train fold 안에서만 SMOTE나 oversampling을 만들고, 남은 1개 validation fold는 원본 분포 그대로 평가해야 해요. 뻥튀기한 거의 쌍둥이 샘플이 validation에 들어가면 모델이 시험지를 미리 본 꼴이라 점수가 과하게 좋아져요.