Sub topic 17
Checking whether probabilities can be trusted, and beyond two classes
This chapter assumes you can fit a logistic regression in scikit-learn and read log loss, precision and recall. It covers two things. First, how to test whether a predicted 0.8 really means 80%. Second, how the model extends to more than two classes.
Are the probabilities calibrated?
A model is calibrated if, among all examples given a probability near p, about a fraction p are actually positive. Ranking metrics such as ROC AUC cannot tell you this. A model can order examples perfectly and still report 0.99 for cases that are right only 80% of the time.
This matters when you use the probability itself, for example to compute an expected cost or to set a threshold from a business rule. Logistic regression is often reasonably calibrated because log loss rewards honest probabilities. Strong regularization, class weights and heavy imbalance can all distort them.
A reliability curve checks this. You sort predictions into bins, then compare the mean predicted probability in each bin with the observed fraction of positives.
from sklearn.calibration import calibration_curve
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(y_test, proba, n_bins=5)
for p, f in zip(mean_pred, frac_pos):
print(f"predicted {p:.2f} observed {f:.2f}")Points near the diagonal (predicted equals observed) indicate good calibration. With a small test set, bins hold few examples, so expect noise.
If the curve is off, wrap the model in CalibratedClassifierCV, which fits a correction on cross-validated predictions. The "sigmoid" method suits small datasets, and "isotonic" needs more data.
Beyond two classes
With K classes there are two common strategies.
- One-vs-rest (OvR): train K binary models, each separating one class from all the others. Predict the class with the highest score. The K probabilities do not sum to 1 unless you normalize them.
- Softmax (multinomial) regression: compute one linear score zk per class, then convert all scores at once with softmax: P(class k) = exp(zk) / Σj exp(zj). The probabilities are positive and sum to 1.
Softmax with K = 2 reduces to the sigmoid. Training minimizes categorical cross-entropy, which is the log of the probability assigned to the true class, averaged and negated. The gradient has the same form as before: the error (p − y) with y one-hot encoded.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
clf.fit(X, y)
probs = clf.predict_proba(X[:2])
print(probs.round(3))
print(probs.sum(axis=1))Recent scikit-learn versions use the multinomial formulation by default for this solver. The coefficient matrix has one row per class.
Common errors
- Reading AUC as evidence of calibration.
- Calibrating and evaluating on the same data.
- Assuming OvR probabilities sum to 1.
Exercise
A model ranks examples perfectly (ROC AUC of 1.0), but its reliability curve shows that examples predicted at 0.9 are positive only 60% of the time. Is this possible, and what would you do?
Show answer
Yes. AUC depends only on the ordering of scores, not their values, so a model can be badly calibrated and still rank perfectly. Fix it by fitting a calibration step, such as CalibratedClassifierCV with the sigmoid or isotonic method, and recheck the reliability curve on held-out data.
Exercise
For three classes, the scores are z = (2.0, 1.0, 0.0). Which class does softmax favor, and do the probabilities sum to 1?
Show answer
Class 1, the one with the largest score. exp values are about 7.39, 2.72 and 1.00, which sum to about 11.11, so the probabilities are about 0.665, 0.245 and 0.090. They sum to 1 by construction.