Implement Temperature Scaling and ECE for Logit Calibration
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Given validation `logits` of shape `(n, k)` from a trained classifier and integer `labels` of shape `(n,)`, implement four NumPy functions:
- `softmax_with_temperature(logits, temperature)` returns the numerically stable row-wise softmax of `logits / T`.
- `negative_log_likelihood(logits, labels, temperature=1.0)` returns the mean natural-log negative log-likelihood (NLL) of the labels under that softmax.
- `fit_temperature(logits, labels, t_min=0.05, t_max=20.0)` returns the $T$ in $[t_{\min}, t_{\max}]$ that minimizes the NLL.
- `expected_calibration_error(probs, labels, n_bins=15)` returns the top-label expected calibration error (ECE) of a probability matrix.
All scalars are returned as Python `float`.
Example:
```python
probs = [[0.85, 0.15], [0.75, 0.25], [0.35, 0.65], [0.45, 0.55]]
labels = [0, 1, 1, 0]
expected_calibration_error(probs, labels, n_bins=5) # 0.275
z = [[5.0, 0.0], [0.0, 5.0], [3.0, -1.0]]
fit_temperature(z, [0, 1, 0]) # 0.05 (separable: clamps to t_min)
fit_temperature(z, [1, 0, 1]) # 20.0 (all wrong: clamps to t_max)
```
```hint A better parameter
The NLL is awkward to study as a function of $T$. Rewrite it in terms of the inverse temperature and look at the sign of its second derivative.
```
```hint Stable log-probabilities
Large logits overflow `exp`, and tiny probabilities underflow to zero. Find a way to compute the NLL without ever taking the log of a softmax output.
```
```hint The clamped cases
Before any search, check which direction the objective is moving at each end of the allowed interval.
```
### Constraints & Assumptions
- Softmax and NLL must stay finite for logits with magnitude around `1e3`.
- The fitted $T$ must be precise enough that the NLL gradient there is below `1e-8`.
- If the optimum lies outside $[t_{\min}, t_{\max}]$, return the nearest bound.
- ECE uses the row maximum as the confidence and `argmax` as the prediction. Bins are equal-width intervals `(lo, hi]`, and a confidence of 0 goes to bin 0. ECE is the sum over non-empty bins of $\frac{\text{count}}{n} \cdot |\text{accuracy} - \text{mean confidence}|$. An empty input returns `0.0`.
- Raise `ValueError` when $T \le 0$, when the logits are not 2-D, when the labels do not have shape `(n,)` or fall outside $[0, k)$, or unless `0 < t_min < t_max`.
### What a Strong Answer Covers
- A softmax and an NLL that stay finite for large logits.
- An argument that the fitting problem has a single global optimum, and a search method that relies on it.
- Correct handling of the cases where the optimum lies outside the interval.
- ECE with the exact binning rule, including confidences of 0 and 1 and empty bins.
- Every listed `ValueError` case, plus the time complexity of each function.
### Follow-up Questions
- Why does temperature scaling never change accuracy, and when is a single temperature not enough?
- Why is it convenient to optimize over the inverse temperature $\beta = 1/T$?
- What are the weaknesses of binned ECE as a metric, and what would you report alongside it?
- Why must the temperature be fit on held-out data, and what happens if you fit it on the training set?
Overview: Implement temperature scaling for a multiclass classifier in NumPy: a stable softmax, mean negative log-likelihood, a bounded fit of the temperature on validation logits, and top-label expected calibration error. Tests numerical stability, convex optimization and calibration metrics.