Sub topic 2
Log Loss and Brier Score
Assume you know binary classification, train/validation/test splits, and basic scikit-learn. This chapter focuses on evaluating and fitting probability calibration.
Log loss and Brier score
A calibrated probability describes event frequency. Among predictions near 0.8, about 80% of cases should be positive. Two proper scoring rules reward accurate probabilities and penalize confident mistakes.
For binary labels \(y \in \{0,1\}\) and predicted probability \(p\):
- Log loss is \(-[y\log(p)+(1-y)\log(1-p)]\). It heavily penalizes assigning near-zero probability to the outcome that occurs.
- Brier score is \((p-y)^2\). It measures squared probability error and ranges from 0, best, to 1.
from sklearn.metrics import brier_score_loss, log_loss
y_true = [1, 0, 1, 1]
p = [0.8, 0.2, 0.4, 0.9]
print("Brier:", brier_score_loss(y_true, p))
print("Log loss:", log_loss(y_true, p))Log loss is especially sensitive to dangerous overconfidence. Brier score is easier to interpret, but its value mixes calibration, discrimination, and class prevalence.
Expected calibration error and its pitfalls
Expected calibration error (ECE) groups predictions into probability bins. It averages the absolute gap between each bin's mean predicted probability and its observed positive rate.
import numpy as np
def ece(y_true, y_prob, n_bins=10):
edges = np.linspace(0, 1, n_bins + 1)
ids = np.digitize(y_prob, edges[1:-1])
return sum(
(ids == b).mean() *
abs(y_true[ids == b].mean() - y_prob[ids == b].mean())
for b in range(n_bins) if (ids == b).any()
)ECE depends on bin count, bin boundaries, and sample size. Empty or tiny bins make estimates unstable. Report it with a reliability diagram and a proper scoring rule, rather than treating it as a definitive measurement.
Fitting a calibrator without leaking data
Fit the base model on training data. Fit the calibrator on separate validation predictions. Use the untouched test set only for final evaluation.
flowchart LR
A[Training data] --> B[Fit base classifier]
C[Validation data] --> D[Fit calibrator on base predictions]
B --> D
E[Test data] --> F[Final calibrated evaluation]
D --> FPlatt scaling
Platt scaling fits a sigmoid to the model's scores. It has low variance and works well when calibration error is smooth. In scikit-learn, method="sigmoid" implements this approach.
Isotonic regression
Isotonic regression learns a nondecreasing, piecewise-constant mapping from scores to probabilities. It can model irregular calibration, but needs more calibration examples and can overfit small datasets.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.naive_bayes import GaussianNB
calibrated = CalibratedClassifierCV(
GaussianNB(), method="sigmoid", cv=5
)
calibrated.fit(X_train, y_train)
probabilities = calibrated.predict_proba(X_test)[:, 1]Use sigmoid calibration for limited data or smooth errors. Consider isotonic calibration with a large validation set and enough observations across the score range.
Exercise
Why must calibration data be separate from the data used to fit the base classifier?
Show answer
Reusing training predictions lets the calibrator learn overly optimistic errors, producing leakage and misleadingly good calibration.