Measure how overconfident a classifier is with expected calibration error

A model that says 90 percent should be right about 90 percent of the time. Expected calibration error (ECE) measures the gap between confidence and accuracy, which matters when you threshold or route on a model's probabilities.

Write ece(probs, labels, n_bins). probs has shape (n, C) with rows that sum to 1, labels has shape (n,). For each sample, the prediction is argmax of its row (lowest class index on ties) and the confidence is that maximum probability.

Put each sample in bin b = min(int(conf * n_bins), n_bins - 1). For every non-empty bin compute acc_b (fraction of correct predictions) and conf_b (mean confidence). Return the float sum over bins of (count_b / n) * |acc_b - conf_b|.

Signaturedef ece(probs, labels, n_bins)

Example

probs = [[0.9, 0.1], [0.8, 0.2], [0.3, 0.7]], labels = [0, 1, 1], n_bins = 2. All three go to bin 1, mean confidence 0.8, accuracy 2/3, so ECE = |0.6667 - 0.8| = 0.1333.

Understand the idea

A calibrated model that says 80% should be right about 80% of the time. Expected calibration error groups predictions by confidence and, in each group, compares the average confidence with the actual accuracy, weighting each group by its share of samples. Like checking a weather app: on days it said 70% rain, did it rain on about 70% of them? Worked example: probs [[0.6, 0.4], [0.95, 0.05], [0.2, 0.8]], labels [0, 1, 1], n_bins = 4. Predictions and confidences: class 0 at 0.6 (correct), class 0 at 0.95 (wrong), class 1 at 0.8 (correct). Bins: int(0.6 x 4) = 2, int(0.95 x 4) = 3, int(0.8 x 4) = 3. Bin 2: accuracy 1, confidence 0.6, gap 0.4, weight 1/3. Bin 3: accuracy 0.5, confidence 0.875, gap 0.375, weight 2/3. ECE = 0.133 + 0.25 = 0.383. Rule: bin = min(int(conf x n_bins), n_bins - 1); ECE = sum over non-empty bins of (count / n) x |acc - conf|. It matters when routing or thresholding on LLM or classifier confidence.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleece([[0.9, 0.1], [0.8, 0.2], [0.3, 0.7]], [0, 1, 1], 2)
  • Sample 2: random 10 binsece(_P, _y, 10)
  • Test 3: random 5 binsece(_P, _y, 5)
  • Test 4: perfect one-hotece([[1.0, 0.0], [0.0, 1.0]], [0, 1], 10)