Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 08 / Topic 2 of 7

Class imbalance

With 5% positives, accuracy is a trap (95% for predicting "no" always). Two practical levers:

# examples/01_class_imbalance_class_weight_raises_recall.py (abridged)
X, y = make_classification(n_samples=5000, weights=[0.95, 0.05], flip_y=0.01, random_state=3)
for cw in [None, "balanced"]:
    pred = LogisticRegression(class_weight=cw, max_iter=1000).fit(X_tr, y_tr).predict(X_te)
    print(cw, precision_score(y_te, pred), recall_score(y_te, pred))
# class_weight=None precision=1.000 recall=0.761
# class_weight=balanced precision=0.733 recall=0.821

class_weight="balanced" makes rare-class mistakes cost more during training: recall rose from 0.761 to 0.821, and precision paid for it, falling from 1.000 to 0.733. The other lever is Part 6's threshold. Both are trades along the same curve — pick by the cost of each mistake, score with PR-AUC or F1, never bare accuracy.

🧪 Quick quiz

  1. With 5% positives, what did class_weight='balanced' change?
Show the answer

Recall went up (from 0.761 to 0.821) and precision went down (from 1.000 to 0.733) — measured on the course's 95/5 dataset.

Done here? The practice set for Part 8 — 4 exercises with solutions — is on the part page.

Search the guide