Sub topic 16
Handling imbalanced classes
This chapter assumes you can fit a logistic regression in scikit-learn, you know the log loss, and you know precision, recall, ROC AUC and threshold selection from earlier chapters. It covers what goes wrong when one class is rare, and which fixes help.
Why imbalance causes trouble
A class is imbalanced when one label is much rarer than the other. Fraud, disease screening and equipment failure are typical cases, with a positive rate of 0.1% to 5%.
Three things go wrong with logistic regression:
- Accuracy misleads. If 95% of examples are negative, a model that always predicts negative scores 95% accuracy and finds no positives.
- The loss favors the majority. Log loss sums over examples. With few positives, the fit reduces the average loss mostly by getting the negatives right. The intercept absorbs the base rate, and the learned probabilities for positives stay low.
- The 0.5 threshold rarely fires. Even a decent model may give its true positives probabilities of 0.1 to 0.4. At a threshold of 0.5, recall for the positive class is poor.
The model itself is often fine. The probabilities may even be well calibrated, because they reflect the true base rate. What fails is the decision rule and the metrics you use to judge it.
Measure the right thing first
Before changing the model, pick metrics that expose the problem.
| Metric | Behavior under imbalance |
|---|---|
| Accuracy | Dominated by the majority class. Avoid it as the main metric. |
| Precision and recall for the positive class | Directly show the trade-off you care about. |
| F1 | One number combining precision and recall at a fixed threshold. |
| ROC AUC | Threshold-free, but the false positive rate uses the huge negative count, so it can look good while precision is poor. |
| PR AUC (average precision) | Threshold-free and sensitive to the positive class. Its no-skill baseline equals the positive rate. |
Always split with stratify=y, so the test set contains enough positives. With 5 positives in a test set, every metric is noise.
Option 1: class weights
Class weights change the loss so that each positive example counts more. With weights w_0 and w_1, the objective becomes:
L = -(1/n) Σ w_{y_i} [ y_i log p_i + (1 - y_i) log(1 - p_i) ]
The gradient with respect to the weights changes in the same way:
∇_w L = Xᵀ (w_y ∘ (p − y)) / n
Each example's error is multiplied by its class weight. Scikit-learn's class_weight="balanced" sets w_c = n / (k · n_c), where k is the number of classes and n_c is the count of class c. With 5% positives and k = 2, a positive gets a weight of 10 and a negative gets about 0.53.
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 average_precision_score, classification_report, roc_auc_score
X, y = make_classification(
n_samples=5000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=1.0, 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("ROC AUC:", round(roc_auc_score(y_test, proba), 3))
print("PR AUC: ", round(average_precision_score(y_test, proba), 3))
print(classification_report(y_test, model.predict(X_test), digits=3))When you run this, expect the weighted model to show much higher recall and much lower precision for class 1 at the default threshold. The ranking metrics, ROC AUC and PR AUC, should change little. Weighting mostly moves the operating point. It does not teach the model a better ordering of examples.
Weights distort probabilities
Class weights act as if the data had a different base rate. With "balanced", the model behaves as if the classes were 50/50. Its predict_proba outputs are then too high for the real population. The shift is roughly an added constant in the log-odds, about log(n_1 / n_0) to recover the original scale. If you need trustworthy probabilities, for example to compute expected cost, do one of the following:
- Skip weighting and tune the threshold instead.
- Recalibrate after weighting, as covered in the calibration chapter.
Option 2: tune the threshold
Instead of changing the training objective, keep the model and move the cutoff. This keeps the probabilities calibrated and lets you pick the trade-off explicitly. Choose the threshold on data the model did not train on. Out-of-fold predictions from the training set work well, and the test set stays untouched.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, f1_score
X, y = make_classification(
n_samples=5000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=1.0, 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
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
oof = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
precision, recall, thresholds = precision_recall_curve(y_train, oof)
f1 = 2 * precision[:-1] * recall[:-1] / (precision[:-1] + recall[:-1] + 1e-12)
best = thresholds[np.argmax(f1)]
print("chosen threshold:", round(float(best), 3))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print("F1 at 0.5: ", round(f1_score(y_test, proba >= 0.5), 3))
print("F1 at chosen:", round(f1_score(y_test, proba >= best), 3))Maximizing F1 is only one choice. If a missed positive costs ten times a false alarm, pick the threshold that minimizes expected cost, as in the threshold selection chapter.
Option 3: resampling
You can also change the data instead of the loss:
- Undersampling drops majority examples. It is fast, but it discards information.
- Oversampling duplicates minority examples. Duplication behaves much like class weighting, with more compute.
- Synthetic oversampling (SMOTE) interpolates new minority points. It needs the separate
imbalanced-learnpackage. It can create unrealistic points and often helps little with a linear model.
Resample only the training data, and do it inside each cross-validation fold. Resampling before the split leaks duplicated or interpolated points into validation folds and inflates every score.
Choosing an approach
Common mistakes
- Reporting accuracy and calling a 97% score good.
- Tuning the threshold on the test set, then reporting test metrics from that same set.
- Applying
class_weight="balanced"and then using the probabilities as real-world risk. - Resampling before cross-validation splits.
- Comparing ROC AUC across datasets with different base rates and reading it as precision.
Summary of trade-offs
- Class weights change the fit and shift probabilities. They are one argument in scikit-learn.
- Threshold tuning keeps probabilities calibrated and costs one extra validation step.
- Resampling adds a leakage risk and, for a linear model, rarely beats the first two.
- Better features usually help more than any of these.
Exercise
A logistic regression trained with class_weight="balanced" on data with 2% positives gives a patient a predicted probability of 0.60. A colleague says the patient has a 60% chance of the condition. Why is that wrong, and what are two ways to get a trustworthy probability?
Show answer
Balanced weighting makes the model behave as if the classes were 50/50, so its probabilities are inflated relative to the real 2% base rate. The true risk is much lower than 0.60. Two fixes: train without class weights and tune the decision threshold separately, so the probabilities stay on the true scale; or keep the weighted model and recalibrate it on unweighted held-out data, for example with Platt scaling or isotonic regression. Shifting the log-odds by about log(n1/n0) also approximately restores the original scale.