Sub topic 4
Why classifiers end up miscalibrated
This chapter assumes you know how logistic regression produces a probability with the sigmoid function. It also assumes you can train and evaluate a scikit-learn classifier on a held-out split. Earlier chapters defined calibration: among cases predicted at 0.8, about 80% should be positive. This chapter explains why many models miss that target and which direction they usually miss in.
The working model: a score is only a probability by construction
A model's output becomes a trustworthy probability only if three things hold:
- The training objective rewards honest probabilities. Log loss does, because it is a proper scoring rule. Hinge loss and the exponential loss do not.
- The model family can represent the true probability function, and the fitting procedure does not distort it.
- The data seen at prediction time look like the data seen at training time, including the class balance.
Most miscalibration comes from breaking one of these. The sections below go through them. Each cause also tends to push probabilities in a predictable direction, which tells you what to look for in a reliability diagram.
- Overconfident means predictions sit closer to 0 or 1 than the observed frequencies justify.
- Underconfident means predictions are pulled toward the middle.
Model families and their typical bias
| Model | Typical pattern | Main reason |
|---|---|---|
| Logistic regression | Close to calibrated | Trained on log loss, and the sigmoid matches the model form |
| Naive Bayes | Overconfident, outputs near 0 and 1 | Correlated features are counted as independent evidence |
| Random forest | Underconfident near 0 and 1 | Averaging trees rarely gives exactly 0 or 1 |
| AdaBoost | Sigmoid-shaped distortion away from 0 and 1 | Exponential loss focuses on margins, not probabilities |
| Linear SVM | No probabilities at all | Hinge loss produces margins, not probabilities |
| Deep neural network | Overconfident | High capacity, and training continues after accuracy stops improving |
These are tendencies, not guarantees. Data and hyperparameters can change them, so measure before assuming.
Broken independence assumptions
Naive Bayes multiplies per-feature likelihoods as if the features were independent. If ten features carry the same information, the model counts that evidence ten times. The posterior is pushed toward 0 or 1 even though the true uncertainty has not changed. The dataset used throughout this tutorial has 10 redundant features out of 20, which is the situation that hurts naive Bayes most.
Averaging pulls probabilities inward
A random forest averages the votes of many trees. For a prediction to reach 0.99, nearly every tree must agree. Trees trained on bootstrap samples have variance, so a few usually disagree even on easy cases. The averaged probability stays away from the extremes, which gives an S-shaped reliability curve that is underconfident at both ends. Boosting with exponential loss has a related effect. Gradient boosting with log loss is usually better behaved, though not perfect.
Overfitting makes the model too sure
A model that memorizes its training set assigns near-certain probabilities to training points. On new data it keeps a similar confidence, but its error rate is higher. Deep networks show this clearly. Accuracy on validation data can stop improving while training log loss keeps falling. During that phase the logits grow larger and softmax outputs become more extreme. Large capacity, little weight decay, and long training all increase the effect.
Regularization pushes the other way
Strong L2 or L1 penalties shrink coefficients. Smaller coefficients mean logits closer to zero, so the probabilities cluster near the prior. A heavily regularized logistic regression (small C in scikit-learn) is often underconfident. Regularization is not wrong, because it helps generalization. But it trades some calibration for lower variance.
Class weights and resampling change the prior
If you train with class_weight="balanced", oversample the minority class, or undersample the majority class, the model learns probabilities for the modified class balance. On the real data, which has the original balance, those probabilities are too high for the minority class. The ranking of examples can stay the same while the probabilities become wrong. This is one of the most common calibration errors in practice, because the resampling step looks harmless.
Seeing the patterns
This script trains three models on the same data and prints a five-bin reliability summary for each. Bins are quantile-based, so each holds the same number of test samples.
from sklearn.calibration import calibration_curve
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
models = {
"logistic": LogisticRegression(max_iter=1000),
"naive Bayes": GaussianNB(),
"random forest": RandomForestClassifier(n_estimators=200, random_state=0),
}
for name, model in models.items():
model.fit(X_train, y_train)
p = model.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(
y_test, p, n_bins=5, strategy="quantile"
)
print(name)
for m, f in zip(mean_pred, frac_pos):
print(f" predicted {m:.2f} observed {f:.2f}")Read each model from the lowest bin to the highest:
- Logistic regression should have predicted and observed values close together.
- Naive Bayes should show a lowest bin with predicted values near 0 and observed values higher, and a highest bin with predicted values near 1 and observed values lower. That is overconfidence at both ends.
- The random forest should show the reverse. Its lowest bin is predicted too high and its highest bin too low. If the results differ from this description, trust your output and check that you ran the script as written.
The exact numbers depend on the library version. The shape is what matters.
Reweighting and the prior shift
You can undo a known change in class balance without training a calibrator. If the model was trained with an effective positive rate pi_s and the real rate is pi, multiply the model's odds by the ratio of prior odds. With class_weight="balanced", the effective rate is 0.5, so the correction simplifies.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=40000,
n_features=10,
n_informative=5,
weights=[0.95, 0.05],
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0, stratify=y
)
plain = LogisticRegression(max_iter=1000).fit(X_train, y_train)
weighted = LogisticRegression(max_iter=1000, class_weight="balanced").fit(
X_train, y_train
)
pi = y_train.mean()
p_w = np.clip(weighted.predict_proba(X_test)[:, 1], 1e-12, 1 - 1e-12)
odds = p_w / (1 - p_w) * pi / (1 - pi)
p_corrected = odds / (1 + odds)
print("observed positive rate:", y_test.mean())
print("plain mean prediction :", plain.predict_proba(X_test)[:, 1].mean())
print("weighted mean :", p_w.mean())
print("weighted, corrected :", p_corrected.mean())The plain model's mean prediction should be close to the observed rate. The weighted model's mean should be far above it. The corrected mean should land back near the observed rate. Matching the mean does not prove calibration, but a large gap in the mean always signals a problem.
Common errors when diagnosing miscalibration
- Checking calibration on training data. Fully grown trees and overfit networks look nearly perfect there. Always evaluate on data the model did not train on.
- Blaming the model when the cause is resampling. If you changed class balance, apply or learn a correction before concluding the model is bad.
- Treating
decision_functionor a raw SVM score as a probability. These scores have no probability scale. Use a calibrator, covered in later chapters. - Assuming good AUC implies good calibration. A model can rank perfectly and still output bad probabilities. The earlier chapter on calibration versus discrimination explains why.
- Assuming one direction of error. The same model can be overconfident in one score range and underconfident in another. Look at the whole reliability curve, not only one summary number.
Exercise
A team trains a fraud classifier with 1% positives. To help the model learn, they undersample legitimate transactions until the training set is 50% fraud. The model ranks transactions well (AUC 0.97), but it outputs a mean predicted fraud probability of 0.45 on the real data, where fraud is 1%. Name the cause, state whether it is a ranking or a calibration problem, and give the correction for the predicted odds.
Show answer
The cause is a prior shift introduced by resampling. The model learned probabilities for a 50% fraud rate, so its outputs are too high on real data. The ranking (AUC) is unaffected, so this is a calibration problem. To correct it, multiply the model's odds by (0.01 / 0.99) / (0.50 / 0.50) = 0.01 / 0.99, then convert the corrected odds back to a probability with odds / (1 + odds). A calibrator fitted on held-out, unsampled data would also work.