Imbalanced Data
In many important problems the interesting class is rare: fraudulent transactions (well under 1 %), machine failures, rare diseases, customers who churn this month. Standard training and evaluation quietly break down on such data, because a model can score very well by ignoring the rare class entirely.
The accuracy trap
We generate a data set where only 5 % of the samples are positive:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score
X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=0.8, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
print("positives in training set:", int(y_tr.sum()), "of", len(y_tr))
for name, model in [("always 0", DummyClassifier(strategy="most_frequent")),
("logistic", LogisticRegression(max_iter=1000))]:
pred = model.fit(X_tr, y_tr).predict(X_te)
print(f"{name:9} accuracy={accuracy_score(y_te, pred):.3f} recall={recall_score(y_te, pred):.3f}")positives in training set: 74 of 1400
always 0 accuracy=0.947 recall=0.000
logistic accuracy=0.937 recall=0.125
The useless "always 0" model is about 95 % accurate. The logistic regression is actually slightly less accurate than that, and it misses most of the positives. Accuracy is the wrong yardstick here — use recall, precision, F1, the precision–recall curve or ROC AUC instead (see Classification Metrics).
Fix 1: class weights
Most scikit-learn classifiers accept class_weight. With "balanced", mistakes on each class are weighted inversely to its frequency, so errors on the rare class cost much more during training:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score, f1_score
X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=0.8, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
for cw in [None, "balanced"]:
pred = LogisticRegression(max_iter=1000, class_weight=cw).fit(X_tr, y_tr).predict(X_te)
print(f"class_weight={str(cw):8} precision={precision_score(y_te, pred):.3f} "
f"recall={recall_score(y_te, pred):.3f} F1={f1_score(y_te, pred):.3f}")class_weight=None precision=0.286 recall=0.125 F1=0.174
class_weight=balanced precision=0.189 recall=0.781 F1=0.305
Recall jumps: the model now catches most positives, at the cost of more false alarms (lower precision). Whether that's a good trade depends on the costs of each kind of error.
Fix 2: move the threshold
Instead of retraining, you can lower the decision threshold of an ordinary model. Here we pick the threshold that maximises F1 on a validation split — not on the test set:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, recall_score
X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=0.8, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, test_size=0.3, random_state=0, stratify=y_tr)
model = LogisticRegression(max_iter=1000).fit(X_fit, y_fit)
val_proba = model.predict_proba(X_val)[:, 1]
thresholds = np.arange(0.05, 0.55, 0.05)
f1s = [f1_score(y_val, (val_proba >= t).astype(int)) for t in thresholds]
best_t = thresholds[int(np.argmax(f1s))]
print(f"best validation threshold: {best_t:.2f}")
test_pred = (model.predict_proba(X_te)[:, 1] >= best_t).astype(int)
print(f"test F1 = {f1_score(y_te, test_pred):.3f}, recall = {recall_score(y_te, test_pred):.3f}")best validation threshold: 0.20
test F1 = 0.425, recall = 0.531
scikit-learn 1.5+ also offers TunedThresholdClassifierCV, which does this search with cross validation for you.
Fix 3: resampling
You can also change the training data itself:
- Oversampling: repeat (or synthesise) rare-class rows until the classes are balanced.
- Undersampling: drop majority-class rows.
The imbalanced-learn library offers advanced methods such as SMOTE, which creates synthetic rare samples by interpolating between neighbours. Simple random oversampling only needs NumPy:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import recall_score, precision_score
X, y = make_classification(n_samples=2000, n_features=10, n_informative=4,
weights=[0.95, 0.05], class_sep=0.8, random_state=3)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
rng = np.random.default_rng(0)
pos = np.where(y_tr == 1)[0]
neg = np.where(y_tr == 0)[0]
extra = rng.choice(pos, size=len(neg) - len(pos), replace=True) # resample ONLY the training set
idx = np.concatenate([neg, pos, extra])
X_bal, y_bal = X_tr[idx], y_tr[idx]
print("balanced training counts:", np.bincount(y_bal))
for name, (Xf, yf) in [("original", (X_tr, y_tr)), ("oversampled", (X_bal, y_bal))]:
pred = DecisionTreeClassifier(max_depth=5, random_state=0).fit(Xf, yf).predict(X_te)
print(f"{name:11} recall={recall_score(y_te, pred):.3f} precision={precision_score(y_te, pred):.3f}")balanced training counts: [1326 1326]
original recall=0.375 precision=0.571
oversampled recall=0.656 precision=0.241
Warning: Resample only the training data, never the test set — the test set must reflect the real class balance. And when cross-validating, resample inside each fold (imbalanced-learn provides a pipeline that does this), otherwise copies of the same rare row end up in both training and validation folds.
Checklist for imbalanced problems
- Use stratified splits and stratified cross validation.
- Pick a metric that reflects the rare class: recall, precision, F1, average precision, or a cost-based score.
- Compare against a
DummyClassifierbaseline. - Try
class_weight="balanced"first — it's one argument. - Tune the decision threshold on validation data.
- Consider resampling if the above isn't enough.
Go further: Class Imbalance: Training and Evaluating shows how prevalence moves the PR curve and why resampling belongs inside the folds.
Test yourself
With 99 % negatives, what accuracy does a model that always predicts 'negative' get?
- 50 %
- 1 %
- 99 %
- 0 %
What does class_weight='balanced' do?
- Removes majority samples
- Weights errors inversely to class frequency
- Duplicates the test set
- Sets the threshold to 0.5
Which data should be oversampled?
- The test set
- The whole data set before splitting
- Only the training data (inside each CV fold)
- None, oversampling is never useful