Sub topic 16
Handling imbalanced classes
This chapter assumes you know how to fit a logistic regression in scikit-learn, and that you understand precision, recall, and decision thresholds from earlier chapters.
Why imbalance causes trouble
A dataset is imbalanced when one class is much rarer than the other. Fraud, disease, and equipment failure are typical examples. Suppose only 2% of transactions are fraud. A model that always predicts "not fraud" scores 98% accuracy and catches no fraud at all.
Log loss adds up the error over every example. The majority class contributes most of the terms, so the fitted weights favor it. The model's probabilities for the rare class tend to be low, and few examples cross the 0.5 threshold.
Step 1: Measure the right thing
Accuracy hides the problem. Use these instead:
- Recall and precision for the rare (positive) class.
- Precision-recall (PR) curves and average precision. ROC AUC can look good even when precision is poor, because the false positive rate divides by the large negative count.
- A stratified split, so the train and test sets keep the same class ratio.
Step 2: Reweight the loss
The simplest fix is class_weight. It multiplies each example's loss term by a weight that depends on its class. With class_weight="balanced", scikit-learn uses n / (k * count_c), where n is the number of examples, k is the number of classes, and count_c is the size of class c. Rare-class errors then cost more during training.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, average_precision_score
X, y = make_classification(
n_samples=5000, n_features=10, n_informative=4,
weights=[0.97, 0.03], random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
for cw in [None, "balanced"]:
model = make_pipeline(
StandardScaler(),
LogisticRegression(class_weight=cw, max_iter=1000),
)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print("class_weight =", cw)
print("average precision:", round(average_precision_score(y_test, proba), 3))
print(classification_report(y_test, model.predict(X_test)))With balanced, recall for the rare class usually rises and precision falls. This is the same trade-off you get from lowering the threshold.
Step 3: Consider the alternatives
- Change the threshold. Train normally, then pick a threshold on a validation set that fits your costs. This leaves the probabilities calibrated.
- Resample. Oversample the rare class or undersample the common one. Do this only on the training data, and never before the split. Otherwise copies of the same example land in both sets and inflate your scores.
- Collect more rare examples. This often helps more than any technique above.
Common errors
- Reporting accuracy on an imbalanced test set.
- Resampling before the train/test split.
- Reading
balancedprobabilities as real-world risk. - Tuning the threshold on the test set instead of a validation set.
Exercise
A model trained with class_weight="balanced" reports a 0.40 probability for a transaction. In the real data, 2% of transactions are fraud. Why shouldn't you tell a customer "there is a 40% chance this is fraud"?
Show answer
Balanced weighting makes rare-class errors count more during training, so the model's probabilities are inflated relative to true frequencies. The 0.40 is a score useful for ranking and thresholding, not a calibrated probability. To get real probabilities, train without class weights or recalibrate the outputs.