Sub topic 9
Checking confidence and calibration
This chapter assumes you can train a classifier and read its probability output, and that you know pandas, NumPy, accuracy and the train/validation/test split. Earlier chapters showed how to find errors by reading them. This chapter asks a different question: when the model is wrong, did it know?
Why confidence matters
Most NLP classifiers output a probability for each class. The highest one is the model's confidence. A model is calibrated when its confidence matches how often it is right. Among all predictions made with 80% confidence, about 80% should be correct.
Calibration matters whenever someone uses the score for a decision:
- Routing low-confidence predictions to a human reviewer.
- Rejecting an input instead of guessing.
- Setting a threshold for automatic action.
- Combining model scores with other signals.
Two models can have identical accuracy and very different calibration. A model that is 90% accurate and always says "99% sure" gives you no way to find its mistakes. A model that is 90% accurate and honest about its uncertainty lets you send the doubtful 20% of cases to a person.
Modern neural text classifiers, especially fine-tuned transformers trained with cross-entropy for many epochs, tend to be overconfident. Their confidence is higher than their accuracy. Measure this instead of assuming it.
Confidence as an error-analysis tool
You already sorted errors by confidence when you built the error table. Three groups of errors behave differently:
| Group | What it looks like | Typical cause | What to do |
|---|---|---|---|
| Confident errors | High confidence, wrong label | Label noise, systematic shortcut, distribution shift | Read each one. Check the gold label first. |
| Uncertain errors | Low confidence, wrong label | Ambiguous text, rare phrasing, too little data | Collect more examples of this kind, or route to review. |
| Uncertain correct predictions | Low confidence, right label | Normal for hard cases | Usually leave alone. |
Confident errors deserve the most reading time. If the model is sure and wrong, either the label is wrong or the model learned something that does not generalize. Both are findable, and both are worth fixing.
Reliability tables
A reliability table groups predictions into confidence bins and compares the average confidence in each bin to the actual accuracy in that bin. Plotted, it is a reliability diagram. A table is often enough.
import numpy as np
import pandas as pd
conf = [0.95, 0.90, 0.85, 0.99, 0.60, 0.55, 0.70, 0.98]
correct = [1, 0, 1, 1, 0, 1, 1, 0]
df = pd.DataFrame({"conf": conf, "correct": correct})
df["bin"] = np.minimum((df["conf"] * 10).astype(int), 9)
table = df.groupby("bin").agg(
n=("correct", "size"),
mean_conf=("conf", "mean"),
accuracy=("correct", "mean"),
)
table["gap"] = table["mean_conf"] - table["accuracy"]
print(table.round(3))Read the gap column. A positive gap means the model claims more certainty than it earns (overconfidence). A negative gap means it is underconfident. Look at n before trusting any row. In this toy data the top bin holds four predictions, so even a large gap is weak evidence. Real evaluations need hundreds or thousands of predictions, and the sparse bins near the extremes are the usual problem.
Expected calibration error
Expected calibration error (ECE) summarizes the table in one number. It is the weighted average of the absolute gap across bins, where each bin's weight is the fraction of all predictions that fall in it.
import numpy as np
def expected_calibration_error(conf, correct, n_bins=10):
conf = np.asarray(conf, dtype=float)
correct = np.asarray(correct, dtype=float)
bins = np.minimum((conf * n_bins).astype(int), n_bins - 1)
ece = 0.0
for b in range(n_bins):
mask = bins == b
if mask.any():
gap = abs(correct[mask].mean() - conf[mask].mean())
ece += mask.mean() * gap
return ece
conf = [0.95, 0.90, 0.85, 0.99, 0.60, 0.55, 0.70, 0.98]
correct = [1, 0, 1, 1, 0, 1, 1, 0]
print(round(expected_calibration_error(conf, correct), 3))This prints 0.415. The np.minimum call keeps a confidence of exactly 1.0 in the last bin instead of creating an eleventh one.
Lower is better, and 0 is perfect. Keep these limits in mind:
- ECE depends on the number of bins. Ten is common. Report the bin count with the number.
- With few examples, ECE is noisy and biased. Use a bootstrap interval, as you did for slice accuracy.
- ECE only measures the match between confidence and accuracy. A model that always predicts the majority-class rate as its confidence can have low ECE and be useless. Always report accuracy and ECE together.
- For multiclass models, this version uses only the top-class confidence. That is the usual choice. It says nothing about whether the second-ranked probabilities are meaningful.
Calibration across slices
A model can look calibrated overall and be badly calibrated on a slice. Short texts, out-of-domain texts, or a minority dialect may all get confident wrong answers while easy slices stay well behaved. The overall number averages these together.
Compute ECE and mean confidence minus accuracy for each slice you built in the slicing chapter. Report the count with each row. If a slice has high error and high confidence, it is a strong candidate for the next fix. The model has no internal signal that it is struggling there, so thresholds will not help.
A common pattern is that confidence stays high on out-of-domain inputs. Compare the confidence distributions of in-domain and out-of-domain data. If they look the same, confidence alone cannot detect the shift.
Fixing miscalibration
Start with the simplest method that works.
Temperature scaling divides the logits by a single number T before the softmax. T greater than 1 softens the probabilities and T less than 1 sharpens them. It does not change the predicted class, so accuracy stays the same. You fit T by minimizing negative log-likelihood on a held-out validation set.
import numpy as np
def softmax(z):
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
def nll(logits, y, T):
p = softmax(logits / T)
return -np.log(p[np.arange(len(y)), y] + 1e-12).mean()
rng = np.random.default_rng(0)
logits = rng.normal(size=(500, 3)) * 3
true_probs = softmax(logits / 2.0) # labels come from a softer distribution
y = np.array([rng.choice(3, p=p) for p in true_probs])
grid = np.linspace(0.5, 5.0, 91)
best_T = grid[np.argmin([nll(logits, y, T) for T in grid])]
print(f"fitted temperature: {best_T:.2f}") # should land near 2Because the labels were drawn using a temperature of 2, the fitted value should land close to 2. A fitted T well above 1 on real data confirms overconfidence.
Other options exist. Label smoothing during training reduces overconfidence. Ensembling several models usually improves calibration. Isotonic regression and Platt scaling fit a more flexible mapping but need more validation data. Temperature scaling is the default because one parameter rarely overfits.
None of these fix the underlying errors. They only make the confidence honest. If the goal is fewer mistakes, calibration is not the tool.
Using calibrated confidence for decisions
Once confidence is trustworthy, you can plot a coverage and accuracy curve. Sort predictions by confidence, keep only the most confident fraction, and compute accuracy on that part. If you answer the top 70% of cases automatically and the accuracy there is 97%, you have a concrete operating point. The remaining 30% go to review.
Check this on slices too. A global threshold may reject nearly all short texts and accept nearly all long ones, which changes who gets automated treatment.
Common mistakes
- Reporting ECE without a bin count or sample size.
- Fitting temperature on the test set.
- Treating softmax output as a true probability for inputs unlike the training data.
- Concluding the model is calibrated because ECE is low on a data set that is mostly easy examples.
- Ignoring confident errors because the average gap looks small. A handful of confident errors can be the whole story for a high-stakes class.
Exercise
A sentiment model has 88% accuracy and an ECE of 0.02 on the validation set. On the slice of texts under four tokens it has 70% accuracy, a mean confidence of 0.93, and 40 examples. Is the model well calibrated, and what do you do next?
Show answer
Overall calibration looks good, but the short-text slice shows a gap of 0.23 (0.93 confidence against 0.70 accuracy), which means strong overconfidence there. With only 40 examples, first compute a bootstrap interval for the slice accuracy to confirm the gap is not noise. If it holds, read the confident errors in that slice for label noise or a shortcut, and consider adding short examples to the training data. A global temperature fit will not fix it, because the overall ECE is already low.
Exercise
Why does temperature scaling leave accuracy unchanged, and why must the temperature be fitted on data the model was not evaluated on?
Show answer
Dividing all logits by one positive number does not change which logit is largest, so the predicted class stays the same and only the probabilities change. The temperature is a fitted parameter, so fitting it on the test set would tune the model to that set and make the reported ECE too optimistic. Fit it on the validation set and report on the test set.