Sub topic 16
Why the probabilities are poorly calibrated, and how to fix it
This chapter assumes you know the naive Bayes decision rule, the conditional independence assumption, and the basics of scikit-learn classifiers and train/test splits. It covers why predict_proba from naive Bayes is often unreliable as a probability, how to measure that, and how to repair it.
What calibration means
A classifier is calibrated if its stated confidence matches how often it is right. Among all test examples where the model says "spam with probability 0.8", about 80% should really be spam.
Calibration is separate from accuracy. A model can rank examples well and pick the right class most of the time, yet report probabilities that are far too extreme. Naive Bayes often behaves this way. Its class labels and its ranking of examples are good, but its probabilities pile up near 0 and 1.
Where the overconfidence comes from
The decision rule multiplies one likelihood per feature. In log space, it adds them:
log P(y | x) ∝ log P(y) + Σ log P(x_j | y)Each term counts as independent evidence. If features are actually correlated, the same evidence is counted several times.
Take a two-class problem with equal priors. Suppose the word "free" is three times more likely in spam than in ham, so the likelihood ratio is 3. One occurrence gives posterior odds of 3:1, which is a probability of 0.75. That may be a fair estimate.
Now suppose five words in the message always appear together, such as "free", "prize", "winner", "claim", and "now". Naive Bayes treats them as five independent pieces of evidence, each with ratio 3. The odds become 3^5 = 243, which is a probability of about 0.996. The real evidence is closer to one cluster of words than five, so 0.75 is closer to the truth. The model's ranking is still sensible, since this message looks more spammy than one with a single such word. The probability value is badly inflated.
This is why long documents tend to get extreme probabilities. Each extra correlated word multiplies the odds again, and the posterior moves toward 0 or 1 regardless of how strong the combined evidence really is.
Other factors add to the problem:
- Smoothing choices change likelihoods. A small
alphamakes rare words produce very large ratios. - Features unseen at training time are skipped, so the score is based on whatever words remain.
- Scores for different documents are not comparable in absolute terms, because they depend on document length.
Why classification can still be good
The decision only needs the correct class to have the highest score. Overcounting evidence inflates all classes' scores in a similar way, so the argmax often stays the same. That is why naive Bayes can have good accuracy and poor probabilities at once. The two properties are measured by different things.
Measuring calibration
Two tools are standard.
A reliability curve (or calibration curve) groups predictions into bins by predicted probability. For each bin, it plots the average predicted probability against the observed fraction of positives. A calibrated model lies on the diagonal. An overconfident model has a curve shaped like a flattened S: predictions near 0 have a higher real positive rate than claimed, and predictions near 1 have a lower one.
A proper scoring rule gives one number. The Brier score is the mean squared difference between the predicted probability and the 0/1 outcome. Log loss is the negative mean log probability assigned to the true class. Lower is better for both. Accuracy cannot show calibration problems, but these scores can, because they penalize confident mistakes heavily.
The code below builds a dataset with many redundant (correlated) features, fits GaussianNB, and compares raw and calibrated probabilities.
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score, brier_score_loss, log_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(
n_samples=6000,
n_features=20,
n_informative=4,
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, stratify=y
)
raw = GaussianNB().fit(X_train, y_train)
calibrated = CalibratedClassifierCV(
GaussianNB(), method="isotonic", cv=5
).fit(X_train, y_train)
for name, model in [("raw", raw), ("isotonic", calibrated)]:
proba = model.predict_proba(X_test)[:, 1]
pred = model.predict(X_test)
print(
name,
"accuracy:", round(accuracy_score(y_test, pred), 3),
"brier:", round(brier_score_loss(y_test, proba), 4),
"log loss:", round(log_loss(y_test, proba), 4),
)
proba_raw = raw.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(y_test, proba_raw, n_bins=10)
for predicted, observed in zip(mean_pred, frac_pos):
print(f"predicted {predicted:.2f} -> observed {observed:.2f}")The 10 redundant features are linear combinations of the 4 informative ones, so they violate independence on purpose. Expect the raw model's bins to disagree with the diagonal at the extremes, and expect the calibrated model's Brier score and log loss to be lower. Accuracy should change little. Exact numbers depend on your scikit-learn version.
Fixing it with post-hoc calibration
The standard repair leaves the naive Bayes model alone. It learns a second, small mapping from the model's score to a better probability. The mapping must be fitted on data the base model did not train on, or it will learn the model's training-set overconfidence.
CalibratedClassifierCV handles this with cross-validation. For each fold, it trains the base model on the training part and fits the calibrator on the held-out part. At prediction time, it averages the calibrated outputs of the fold models.
There are two calibration methods:
| Method | Mapping | Needs | Risk |
|---|---|---|---|
| `"sigmoid"` (Platt scaling) | Logistic curve with two parameters | Little data | Too rigid if the distortion is not S-shaped |
| `"isotonic"` | Free-form, monotonic step function | Often 1000 or more calibration examples | Overfits on small data |
A reasonable default is sigmoid for small datasets and isotonic when you have plenty of data. Check the choice with the reliability curve on a separate test set.
Details to keep in mind:
- For multiclass problems, scikit-learn calibrates each class one-vs-rest and then renormalizes so the probabilities sum to 1.
- A monotonic mapping preserves ranking in the binary case, so ROC AUC stays almost the same. Accuracy at the 0.5 threshold can shift slightly, because the point that maps to 0.5 moves.
- Calibration costs extra training time, since it fits several base models.
- Calibration repairs the average match between score and outcome. It does not fix a model whose ranking is poor.
Reducing the cause
Calibration treats the symptom. You can also reduce the correlation that causes it:
- Drop or merge redundant features before fitting, for example with feature selection.
- Use a higher
alphato damp rare-feature ratios, and tune it with a proper scoring rule such as log loss. - Cap or normalize document length effects, for example by using binary or sublinear term counts.
- Consider a discriminative model such as logistic regression if you need accurate probabilities. It learns weights that adjust for correlated features, so it does not double count them.
When calibration matters
If you only need the predicted label, or a ranking with a threshold chosen on validation data, raw naive Bayes is usually fine. Calibrate when you use the probability itself: combining it with costs in a decision, setting a threshold from a business requirement, showing confidence to users, or feeding it into another model.
Exercise
A naive Bayes spam filter has equal class priors. Three words in a message are perfectly correlated, and each has a spam-to-ham likelihood ratio of 2. What posterior spam probability does naive Bayes report, and what would it report if the three words were treated as a single piece of evidence?
Show answer
Naive Bayes multiplies the three ratios: 2 × 2 × 2 = 8, so the odds are 8:1 and the probability is 8/9, about 0.89. Treating the words as one piece of evidence gives odds of 2:1, a probability of 2/3, about 0.67. The model overstates its confidence because it counts the same evidence three times.
Exercise
After calibrating a naive Bayes model with isotonic regression, accuracy is about the same but log loss has dropped. Why is this expected, and why must the calibrator be fitted on data the base model did not train on?
Show answer
Calibration applies a monotonic mapping to the scores, so it changes how confident the probabilities are without much changing which class wins. Log loss penalizes confident mistakes, so correcting overconfidence lowers it. The calibrator needs held-out data because on the base model's own training data the scores look more reliable than they are, and the calibrator would learn that false picture instead of the model's real behavior on new data.