---
title: Expected calibration error
url: https://gurkanozkan.ai/learn/coding/mle-expected-calibration-error-39/
markdown: https://gurkanozkan.ai/learn/coding/mle-expected-calibration-error-39.md
kind: coding
difficulty: Easy
topics:
  - Calibration
  - Metrics
json: https://gurkanozkan.ai/api/learn/coding/mle-expected-calibration-error-39.json
robots: noindex
---

# Expected calibration error

Use `n_bins` equal-width bins over [0, 1], with bin index `min(floor(p·n_bins), n_bins − 1)`. Return `ECE = Σ_b (|b|/N)·|accuracy_b − mean_confidence_b|` over non-empty bins, where accuracy is the mean label in the bin.

## Signature

```python
def expected_calibration_error(y_true: list[int], probs: list[float], n_bins: int = 10) -> float: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(expected_calibration_error([1, 0], [1.0, 0.0], 10), 0.0)
True

>>> close(expected_calibration_error([1, 1, 0, 0], [0.9, 0.9, 0.9, 0.9], 10), 0.4)
True
```

## Hints

1. Equal-width bins over [0, 1]; bin index = min(floor(p * n_bins), n_bins - 1).
2. ECE = sum over non-empty bins of (|b|/N) * |accuracy_b - mean_confidence_b|.
3. accuracy is the mean label in the bin; skip empty bins; bin index must not overflow.

## Reference solution

```python
from collections import defaultdict

def expected_calibration_error(y_true, probs, n_bins=10):
    N = len(y_true)
    bins = defaultdict(list)
    for y, p in zip(y_true, probs):
        b = min(int(p * n_bins), n_bins - 1)
        bins[b].append((y, p))
    e = 0.0
    for lst in bins.values():
        acc = sum(y for y, _ in lst) / len(lst)
        conf = sum(p for _, p in lst) / len(lst)
        e += abs(acc - conf) * len(lst) / N
    return e
```

## What a strong solution covers

- Bins p = 1.0 into the last bin.
- Weights bins by count; skips empty bins.
- Discusses equal-mass bins, ECE's sensitivity to binning, the Brier score, and post-hoc calibration.

## Common mistakes

- p = 1.0 indexing out of range
- unweighted averaging across bins.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
