Implement Expected Calibration Error with Equal-Width Bins and Per-Bin Statistics

Quick Overview

Implement expected calibration error in Python for binary or multiclass probabilities, returning the score with the bin edges and the per-bin mean confidence and accuracy. Tests top-label confidence, right-closed equal-width binning, empty-bin handling and input validation.

Implement Expected Calibration Error with Equal-Width Bins and Per-Bin Statistics

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given labels `y_true` and probabilities `y_probs` (1-D means P(class 1); 2-D means `(n, k)` class probabilities), compute the Expected Calibration Error over `n_bins` equal-width bins on [0, 1]. Confidence is the max class probability and the prediction is its `argmax` (ties go to the lowest index, so a binary 0.5 predicts class 0). ```python def expected_calibration_error(y_true, y_probs, n_bins=10): """Return (ece, bin_edges, bin_confidence, bin_accuracy).""" ``` Return `(ece, bin_edges, bin_confidence, bin_accuracy)`: `ece` as a Python `float`, the `n_bins + 1` bin edges, and per-bin mean confidence and accuracy arrays, where $$ \text{ECE} = \sum_{b} \frac{n_b}{n} \left| \text{acc}_b - \text{conf}_b \right| $$ Requirements: - Bins are right-closed `(lo, hi]`, and the first bin also includes 0. - Empty bins report `nan` confidence and accuracy and contribute nothing to `ece`. - Raise `ValueError` when `n_bins` is not a positive integer, when the lengths of `y_true` and `y_probs` differ, or when the input is empty. Example: ```python y_true = [1, 1, 0, 0, 1, 1] y_probs = [0.9, 0.8, 0.6, 0.3, 0.1, 0.55] ece, edges, conf, acc = expected_calibration_error(y_true, y_probs, n_bins=4) # ece ≈ 0.125 # edges = [0.0, 0.25, 0.5, 0.75, 1.0] # conf = [nan, nan, 1.85/3, 2.6/3] # acc = [nan, nan, 2/3, 2/3] ``` ```hint One pair per sample Before binning, reduce every sample to two numbers. Decide how a 1-D probability vector should be reshaped so that a single max and argmax handle both input shapes and the tie rule. ``` ```hint Bin boundaries Work out by hand where confidences of exactly 0.5, 0.75 and 1.0 should land with `n_bins=4`, then check that your binning call follows the right-closed convention at those points. ``` ### Constraints & Assumptions - `y_probs` is either 1-D of length n or 2-D of shape `(n, k)`; 1-D input is the binary case with k = 2. - Labels are integers in `[0, k)` and probabilities lie in [0, 1]. ### What a Strong Answer Covers - Turning each sample into a (confidence, correct) pair, including the 1-D binary case and the lowest-index tie rule. - Assigning confidences to right-closed equal-width bins, with 0 and 1 landing in the first and last bins. - Per-bin mean confidence and accuracy, with empty bins reported as `nan` and kept out of the weighted sum. - Input validation that matches the spec. - A vectorized implementation and its time and space cost. ### Follow-up Questions - How would you implement adaptive (equal-mass) binning instead? - What are the limitations of top-label ECE for multiclass models? - How would you use this metric to fix a miscalibrated classifier?

Overview: Implement expected calibration error in Python for binary or multiclass probabilities, returning the score with the bin edges and the per-bin mean confidence and accuracy. Tests top-label confidence, right-closed equal-width binning, empty-bin handling and input validation.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given labels y_true and probabilities y_probs (1-D means P(class 1); 2-D means (n, k) class probabilities), compute the Expected Calibration Error over n_bins equal-width bins on [0, 1]. Confidence is the max class probability and the prediction is its argmax (ties go to the lowest index, so a binary 0.5 predicts class 0).

def expected_calibration_error(y_true, y_probs, n_bins=10):
    """Return (ece, bin_edges, bin_confidence, bin_accuracy)."""

Return (ece, bin_edges, bin_confidence, bin_accuracy): ece as a Python float, the n_bins + 1 bin edges, and per-bin mean confidence and accuracy arrays, where

ECE=∑bnbn∣accb−confb∣\text{ECE} = \sum_{b} \frac{n_b}{n} \left| \text{acc}_b - \text{conf}_b \right|

Requirements:

  • Bins are right-closed (lo, hi] , and the first bin also includes 0.
  • Empty bins report nan confidence and accuracy and contribute nothing to ece .
  • Raise ValueError when n_bins is not a positive integer, when the lengths of y_true and y_probs differ, or when the input is empty.

Example:

y_true  = [1, 1, 0, 0, 1, 1]
y_probs = [0.9, 0.8, 0.6, 0.3, 0.1, 0.55]

ece, edges, conf, acc = expected_calibration_error(y_true, y_probs, n_bins=4)
# ece   ≈ 0.125
# edges = [0.0, 0.25, 0.5, 0.75, 1.0]
# conf  = [nan, nan, 1.85/3, 2.6/3]
# acc   = [nan, nan, 2/3, 2/3]

Constraints & Assumptions

  • y_probs is either 1-D of length n or 2-D of shape (n, k) ; 1-D input is the binary case with k = 2.
  • Labels are integers in [0, k) and probabilities lie in [0, 1].

What a Strong Answer Covers Guidance

  • Turning each sample into a (confidence, correct) pair, including the 1-D binary case and the lowest-index tie rule.
  • Assigning confidences to right-closed equal-width bins, with 0 and 1 landing in the first and last bins.
  • Per-bin mean confidence and accuracy, with empty bins reported as nan and kept out of the weighted sum.
  • Input validation that matches the spec.
  • A vectorized implementation and its time and space cost.

Follow-up Questions Guidance

  • How would you implement adaptive (equal-mass) binning instead?
  • What are the limitations of top-label ECE for multiclass models?
  • How would you use this metric to fix a miscalibrated classifier?