In fraud detection, disease screening and equipment failure prediction, the case you care about is rare: perhaps 3 transactions in 100. A model that simply says “not fraud” every time is 97% accurate and completely useless. This is the imbalanced data problem. Solving it means measuring the right thing, telling the model that rare mistakes matter more, and choosing a decision threshold that fits the real costs.
In this lesson you will learn
- Why accuracy misleads on imbalanced data
- Reading precision and recall for the rare class
- Using
class_weight="balanced" - Moving the decision threshold
- ROC AUC versus precision-recall AUC
Review precision, recall and the confusion matrix first.
The Accuracy Trap and Class Weights
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
# Fraud-like data: only about 3% of transactions are positive
X, y = make_classification(n_samples=4000, n_features=8, n_informative=4,
weights=[0.97, 0.03], class_sep=0.8, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=7)
print("Positive share in training data:", round(y_train.mean(), 3))
always_no = np.zeros_like(y_test)
print("Accuracy of always predicting 'not fraud':", round((always_no == y_test).mean(), 3))
plain = LogisticRegression(max_iter=1000).fit(X_train, y_train)
weighted = LogisticRegression(max_iter=1000, class_weight="balanced").fit(X_train, y_train)
for name, model in [("Plain", plain), ("class_weight='balanced'", weighted)]:
pred = model.predict(X_test)
print(f"\n{name}")
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, digits=2, target_names=["normal", "fraud"]))
Output
Positive share in training data: 0.033
Accuracy of always predicting 'not fraud': 0.967
Plain
[[1159 1]
[ 33 7]]
precision recall f1-score support
normal 0.97 1.00 0.99 1160
fraud 0.88 0.17 0.29 40
accuracy 0.97 1200
macro avg 0.92 0.59 0.64 1200
weighted avg 0.97 0.97 0.96 1200
class_weight='balanced'
[[904 256]
[ 9 31]]
precision recall f1-score support
normal 0.99 0.78 0.87 1160
fraud 0.11 0.78 0.19 40
accuracy 0.78 1200
macro avg 0.55 0.78 0.53 1200
weighted avg 0.96 0.78 0.85 1200
- Only 3.3% of the samples are fraud. Always predicting “normal” scores 96.7% accuracy while catching no fraud at all.
stratify=ykeeps the same fraud share in the training and test sets, which matters when positives are scarce.- The plain logistic regression also looks accurate, but its fraud recall is 0.17: it catches only 7 of 40 frauds.
class_weight="balanced"makes each fraud example count about 30 times more in the loss, in proportion to how rare it is. Recall jumps to 0.78 (31 of 40 caught). The price is many more false alarms: precision falls to 0.11, and accuracy falls to 78%.- Which model is better depends on costs. Missing a fraud may cost far more than checking a false alarm.
Choosing the Threshold
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=4000, n_features=8, n_informative=4,
weights=[0.97, 0.03], class_sep=0.8, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=7)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print(f"ROC AUC: {roc_auc_score(y_test, proba):.3f} PR AUC: {average_precision_score(y_test, proba):.3f}")
print("threshold precision recall")
for t in [0.5, 0.3, 0.15, 0.05]:
pred = (proba >= t).astype(int)
print(f" {t:4.2f} {precision_score(y_test, pred, zero_division=0):.2f} "
f"{recall_score(y_test, pred):.2f}")
Output
ROC AUC: 0.840 PR AUC: 0.417
threshold precision recall
0.50 0.88 0.17
0.30 0.65 0.28
0.15 0.38 0.40
0.05 0.15 0.72
predictuses a probability threshold of 0.5. With rare positives, the model’s probabilities for fraud are usually lower than that, so few cases cross it.- Lowering the threshold trades precision for recall. At 0.15, precision and recall are balanced at around 0.4; at 0.05, the model catches 72% of fraud, but only 15% of its alerts are real.
- ROC AUC (0.84) measures how well the model ranks positives above negatives overall, but it can look good even when the rare class is hard to find.
- PR AUC (average precision, 0.42) focuses on the positive class and is the more honest summary for heavy imbalance. A random model’s PR AUC equals the positive rate, about 0.03 here.
Imbalance Toolbox
| Technique | How | Notes |
|---|---|---|
| Better metrics | Recall, precision, F1, PR AUC | Always the first step |
| Class weights | class_weight="balanced" | Supported by most scikit-learn classifiers |
| Threshold tuning | Compare predict_proba with a custom cut-off | Choose it on validation data, not the test set |
| Resampling | Undersample the majority or oversample the minority (e.g. SMOTE in the imbalanced-learn library) | Resample only the training data, inside CV |
| More positive data | Collect or label more rare cases | Often the most effective fix |
Common Mistakes
- Reporting accuracy on heavily imbalanced data.
- Oversampling before splitting, so copies of the same positive appear in both training and test sets.
- Tuning the threshold on the test set, which inflates the final score.
- Forgetting
stratify, leaving some folds with almost no positives.
Practice Exercises
Exercise 1. Find the threshold that gives the highest F1 score for the plain model.
Show answer
import numpy as np
from sklearn.metrics import f1_score
thresholds = np.arange(0.02, 0.6, 0.01)
scores = [f1_score(y_test, (proba >= t).astype(int)) for t in thresholds]
best = thresholds[int(np.argmax(scores))]
print(round(best, 2), round(max(scores), 3))
In a real project, choose the threshold on a separate validation set.
Exercise 2. A screening test must find at least 90% of sick patients. Which metric do you constrain, and what do you optimise?
Show answer
Constrain recall to be at least 0.90, then choose the threshold (or model) with the highest precision among those that meet it, so as few healthy people as possible are sent for follow-up tests.
Frequently Asked Questions
Should I always balance the classes to 50/50?
No. Balancing changes the model’s probabilities so they no longer match reality. Use class weights or resampling to help the model learn the rare class, then pick a threshold based on the actual costs of each type of error.
When is ROC AUC still useful?
For comparing how well models rank cases when classes are only mildly imbalanced, or when both classes matter equally. With very rare positives, also report PR AUC.
Summary
- Accuracy hides failure on rare classes; use recall, precision and PR AUC.
class_weight="balanced"makes rare mistakes count more.- Lowering the threshold raises recall and lowers precision.
- Choose weights, resampling and thresholds on training or validation data only.
Next: Neural Network Basics.
