smartyfy.mrindigi.com

Python Master Course V2 — 138. Imbalanced Learning, Calibration and Threshold Selection

Purpose and learning outcomes

When positive events are rare, predicting negative for every row can look accurate while missing every event of interest. This lesson creates a synthetic rare-event task and compares ordinary logistic regression, class weighting, and cross-validated probability calibration. We then select a threshold using an explicit validation cost and evaluate the locked policy once.

  • Evaluate imbalanced classifiers with appropriate precision-recall metrics
  • Separate probability calibration from ranking quality
  • Select a decision threshold on validation data under a stated cost model

Prerequisites: 134: classification metrics; 136: validation.

Environment and run order

Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.

Shell

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Prevalence changes metric interpretation

Prevalence is the proportion of actual positives in the evaluated population. Precision depends strongly on it: even a modest false-positive rate can produce many false alarms when negatives dominate. Average precision summarizes the precision-recall ranking curve, while recall at a specific threshold describes a particular operating point. Always include positive counts, since ten rare events provide much weaker evidence than thousands.

Weighting changes the training objective

class_weight="balanced" increases the contribution of the less common class according to training frequencies. This can improve a desired decision tradeoff, but it does not create new positive examples or guarantee better probability estimates. Weighted fitting changes the effective error emphasis. Evaluate its ranking and decision behavior rather than assuming that an imbalanced dataset requires weighting.

Calibration asks whether probabilities match frequencies

A calibrated probability of roughly 0.2 should correspond, over many comparable cases, to a positive frequency near 20%. Brier score averages squared probability errors and reflects more than calibration alone, including discrimination. A reliability diagram groups predictions and compares average prediction with observed frequency, but sparse bins are noisy. Calibration cannot rescue a model whose inputs carry no useful ranking information.

Calibration and threshold selection need protected boundaries

CalibratedClassifierCV fits the base estimator and calibration mapping using internal folds of training data. With a pipeline as its estimator, scaling is also trained within those folds. The separate validation set then supports model and threshold choices. The final test sees neither fitting nor threshold selection. We retain the calibrated fitted ensemble rather than refitting it after selecting a threshold, keeping the score distribution matched to that decision rule.

Incremental worked example

1. Build rare-event data and calibration candidates

Sigmoid calibration is a low-complexity mapping appropriate for this small teaching example; more flexible calibration may require substantially more data. ensemble=True makes the fold-based fitting behavior explicit. All candidates use only training observations.

Python

import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.metrics import (average_precision_score, brier_score_loss,
                             confusion_matrix, precision_score, recall_score)

X, y = make_classification(n_samples=1200, n_features=10, n_informative=5,
    weights=[0.92, 0.08], flip_y=0.01, random_state=38)
Xd, Xt, yd, yt = train_test_split(X, y, test_size=0.2, stratify=y, random_state=38)
Xr, Xv, yr, yv = train_test_split(Xd, yd, test_size=0.25, stratify=yd, random_state=39)
def pipeline(weight=None):
    return make_pipeline(StandardScaler(),
        LogisticRegression(max_iter=1000, class_weight=weight))
cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=38)
models = {"ordinary": pipeline(), "weighted": pipeline("balanced"),
          "calibrated": CalibratedClassifierCV(
              estimator=pipeline(), method="sigmoid", cv=cv, ensemble=True)}
for name, model in models.items():
    model.fit(Xr, yr)
    p = model.predict_proba(Xv)[:, list(model.classes_).index(1)]
    print(name, "AP", average_precision_score(yv, p),
          "Brier", brier_score_loss(yv, p))

2. Lock a cost-based policy and inspect calibration

For clarity, the calibrated candidate is prespecified for the policy exercise rather than selected after comparing test outcomes. The invented cost is eight units per missed positive and one per false alarm. Validation chooses among a modest threshold grid.

Python

model = models["calibrated"]
pv = model.predict_proba(Xv)[:, list(model.classes_).index(1)]
thresholds = np.linspace(0.05, 0.75, 15)
def cost(y_true, p, t):
    tn, fp, fn, tp = confusion_matrix(y_true, p >= t, labels=[0, 1]).ravel()
    return int(fp + 8 * fn)
threshold = min(thresholds, key=lambda t: cost(yv, pv, t))
observed, predicted = calibration_curve(yv, pv, n_bins=5, strategy="quantile")
print("validation reliability points", list(zip(predicted, observed)))
pt = model.predict_proba(Xt)[:, list(model.classes_).index(1)]
pred = pt >= threshold
print("locked threshold", threshold, "test positives", int(yt.sum()))
print("test precision", precision_score(yt, pred, zero_division=0))
print("test recall", recall_score(yt, pred, zero_division=0))
print("test cost", cost(yt, pt, threshold))
print("test Brier", brier_score_loss(yt, pt))

Expected output / interpretation

AP, Brier score, reliability points, and policy errors are measured when you run.
A lower Brier score does not by itself prove improved calibration.
A rare-event sample may have wide uncertainty even when a reported decimal looks precise.

Guided lab and acceptance criteria

  1. Calculate the always-negative classifier’s accuracy and recall. Use those two values to explain why ordinary accuracy alone would conceal the failure to find positives.
  2. Compare ordinary and weighted candidates on validation AP and Brier score. Describe the possibility that one improves a threshold-dependent result while worsening probability interpretation. Do not assert a winner before running.
  3. Create a reliability plot from the returned predicted and observed arrays. Annotate that quantile bins can contain different probability ranges and may merge tied values. Include bin counts if you implement them, rather than implying equal uncertainty everywhere.
  4. Write a decision memo with prevalence, notional costs, threshold grid, selected threshold, and locked test results. Passing work separates ranking quality from probability calibration and explains how a real prevalence shift could change precision and policy performance.

Common mistakes and repairs

  • Oversampling before splitting: duplicated or related rows can appear on both sides. If using resampling later, keep it inside each training fold.
  • Using weighted outputs as unquestioned natural probabilities: inspect calibration because the weighted objective changes how errors are emphasized.
  • Tuning calibration and threshold on test: reserve training-only calibration folds, development selection data, and one final test boundary.

Questions that test understanding

Why is high accuracy easy on rare events?

If only 8% of observations are positive, always predicting negative yields about 92% accuracy while recall is zero. The metric rewards the abundant negatives. Include prevalence, confusion counts, and a measure connected to the positive event before declaring the model useful.

Can calibration improve ROC AUC dramatically?

A monotonic mapping mainly changes probability scale, not ordering, so it generally preserves ranking for a single score function. Fold ensembles and ties can introduce differences, but calibration’s purpose is probability interpretation. Improving poor feature discrimination requires a different intervention.

Does lower Brier score prove a model is better calibrated?

Not alone. Brier score combines effects related to reliability and discrimination. Compare a reliability diagram and appropriate decomposition or additional diagnostics when calibration itself is the question. Also consider the number of positives and noise in each probability region.

Why use sigmoid rather than isotonic calibration here?

Sigmoid fitting has limited flexibility, which is helpful with a modest number of positive training examples. Isotonic regression can fit more complex monotonic relationships but may overfit with little calibration data. The choice is a validation question, not a universal superiority claim.

Would a different false-negative cost change the model’s probabilities?

Changing only the decision cost changes which threshold is attractive, not the fitted probabilities. Retraining with weights would be a separate modeling intervention. Keeping these steps distinct makes it possible to explain why a policy changed and what evidence supports it.

Why keep class prevalence in the report?

Precision, baseline AP, and expected review workload depend on the population’s positive rate. A policy evaluated on artificially balanced data may behave very differently in a rare-event deployment. Report the sampled population and whether its prevalence matches the intended use.

Exercises with worked solutions

Exercise 1: Measure the trivial classifier

Reveal the worked solution and reasoning

This calculation exposes the tradeoff hidden by accuracy. The result is based on validation only and is not a new test-set selection step.

Python

all_negative = np.zeros_like(yv)
print("always-negative accuracy", np.mean(all_negative == yv))
print("always-negative recall", recall_score(yv, all_negative, zero_division=0))
print("validation prevalence", yv.mean())

Exercise 2: Reason about doubled false-negative cost

Reveal the worked solution and reasoning

Recompute validation cost with 16 rather than 8 units per missed positive, keeping the same fitted scores. A lower threshold may become preferable, but finite samples and the grid mean the selected threshold need not strictly decrease. Evaluate this as a new policy before any new final holdout; do not select it using the already-opened test set.

Recap and next step

Rare-event evaluation needs class counts, suitable ranking metrics, calibration diagnostics, and a transparent action rule. Weighting, calibration, and threshold selection solve different problems. Next we change the data boundary again: forecasts must respect what was known at each time, even when every row looks like ordinary tabular data.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.