Sub topic 9
Checking Confidence and Calibration
What confidence means
Assume you know basic Python, NumPy, and the precision, recall, and F1 metrics. You also know how a text classifier produces predictions on a held-out test set.
A model's confidence is its stated probability for its chosen prediction. For a three-class sentiment model, an output such as [0.05, 0.10, 0.85] means the model chooses the class with probability 0.85. Confidence is useful for deciding which predictions to review, reject, or send to a human.
Confidence is not automatically a reliable probability. A model can be very confident and still be wrong. Calibration measures whether confidence matches observed accuracy.
A model is well calibrated when predictions made with 0.8 confidence are correct about 80% of the time. Calibration is different from discrimination. A model can rank correct predictions above incorrect ones while still reporting probabilities that are too high or too low.
Comparing confidence with accuracy
To inspect calibration, group predictions into confidence bins. For every bin, calculate:
- Mean confidence: the average confidence reported by the model.
- Accuracy: the fraction of predictions that were correct.
- Count: the number of examples in the bin.
Compare mean confidence with accuracy. A large gap indicates miscalibration.
import numpy as np
def calibration_table(confidence, correct, n_bins=10):
confidence = np.asarray(confidence, dtype=float)
correct = np.asarray(correct, dtype=float)
edges = np.linspace(0.0, 1.0, n_bins + 1)
rows = []
for lower, upper in zip(edges[:-1], edges[1:]):
mask = (
(confidence >= lower)
& (confidence < upper)
if upper < 1.0
else (confidence >= lower) & (confidence <= upper)
)
if mask.any():
rows.append({
"lower": lower,
"upper": upper,
"count": int(mask.sum()),
"mean_confidence": confidence[mask].mean(),
"accuracy": correct[mask].mean(),
})
return rows
confidence = [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]
for row in calibration_table(confidence, correct):
print(row)In a reliability diagram, plot mean confidence on the horizontal axis and accuracy on the vertical axis. The diagonal represents perfect calibration. Points below the diagonal show overconfidence. Points above it show underconfidence.
Expected calibration error
Expected calibration error, or ECE, summarizes the weighted absolute gap between confidence and accuracy across bins:
def expected_calibration_error(confidence, correct, n_bins=10):
confidence = np.asarray(confidence, dtype=float)
correct = np.asarray(correct, dtype=float)
bins = np.minimum((confidence * n_bins).astype(int), n_bins - 1)
ece = 0.0
for bin_id in range(n_bins):
mask = bins == bin_id
if mask.any():
gap = abs(correct[mask].mean() - confidence[mask].mean())
ece += mask.mean() * gap
return ece
print(f"ECE: {expected_calibration_error(confidence, correct):.3f}")ECE is easy to compare, but it depends on the number and boundaries of the bins. It can also hide severe errors inside a bin. Always inspect the table or reliability diagram and report the count for each bin.
Using calibration in decisions
Calibration matters when probabilities drive actions. For example, you might auto-accept predictions above 0.95 and route the rest to review. Before choosing that threshold, measure precision and coverage at the threshold:
- Coverage is the fraction of examples accepted automatically.
- Precision is the fraction of accepted predictions that are correct.
Calibration can change after domain shift, fine-tuning, or class balancing. Recheck it on data that resembles deployment data. If the model is consistently overconfident, a separate calibration method such as temperature scaling can adjust its scores using validation data. Do not fit that adjustment on the test set.
Exercise
A confidence bin contains 200 predictions with mean confidence 0.90 and observed accuracy 0.78. Is the model overconfident or underconfident in this bin, and what is the absolute calibration gap?
Show answer
It is overconfident because confidence is higher than accuracy. The absolute gap is 0.12, or 12 percentage points.