Handle imbalanced classes and choose a threshold

scikit-learn 1.9.1

Use metrics that reflect decision costs and tune a threshold without using the final test set.

On this page

Choose metrics for rare outcomes

Accuracy can be high when the positive class is rare and the model predicts almost every row as negative. Inspect precision, recall, and the confusion matrix. Precision-recall curves show the trade-off as the classification threshold changes.

Turn probabilities into a decision

Lowering a threshold can detect more positive cases and produce more false alarms. Pick a threshold using validation data and explicit costs, then report performance on untouched test data.

import numpy as np
from sklearn.metrics import precision_score, recall_score

y_true = [0, 0, 1, 1]
scores = np.array([0.10, 0.55, 0.45, 0.80])
for cutoff in [0.60, 0.40]:
    flags = scores >= cutoff
    print(f"{cutoff:.2f}: precision={precision_score(y_true, flags):.2f}, "
          f"recall={recall_score(y_true, flags):.2f}")
Example output
0.60: precision=1.00, recall=0.50
0.40: precision=0.67, recall=1.00

Official references