Source code for rank_preserving_calibration._temperature
"""Scalar temperature scaling for decoupled KL calibration."""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
from scipy.optimize import minimize_scalar
from ._metrics import nll_score
from ._types import CalibrationError
from ._validation import validate_labels, validate_probs
if TYPE_CHECKING:
from numpy.typing import ArrayLike
[docs]
def apply_temperature(probs: ArrayLike, temperature: float) -> np.ndarray:
"""Rescale predicted probabilities by a positive scalar temperature.
Computes ``softmax(log(probs) / temperature)`` row-wise. Temperatures
greater than 1 soften overconfident predictions; values below 1 sharpen
underconfident predictions.
Args:
probs: Input probability matrix of shape ``(N, J)``.
temperature: Strictly positive scalar temperature.
Returns:
Temperature-scaled probability matrix of shape ``(N, J)``.
Raises:
CalibrationError: If ``probs`` is invalid or ``temperature <= 0``.
"""
P = validate_probs(probs)
if not np.isfinite(temperature) or temperature <= 0:
raise CalibrationError(
f"temperature must be finite and strictly positive, got {temperature}"
)
logits = np.log(np.clip(P, 1e-12, 1.0)) / float(temperature)
logits -= logits.max(axis=1, keepdims=True)
exp_logits = np.exp(logits)
return exp_logits / exp_logits.sum(axis=1, keepdims=True)
[docs]
def fit_temperature(
probs: ArrayLike,
y: ArrayLike,
*,
bounds: tuple[float, float] = (0.05, 20.0),
) -> float:
"""Fit a scalar temperature minimizing multiclass negative log-likelihood.
Use this on a source validation split to obtain ``reference =
apply_temperature(probs_test, tau)`` while keeping ``anchor = probs_test``
in :func:`~rank_preserving_calibration.calibrate`.
Args:
probs: Validation probability matrix of shape ``(N, J)``.
y: Integer class labels of shape ``(N,)`` in ``{0, ..., J - 1}``.
bounds: Lower and upper search bounds ``(low, high)`` with
``0 < low < high``.
Returns:
Optimal scalar temperature ``tau > 0``.
Raises:
CalibrationError: If ``probs``, ``y``, or ``bounds`` are invalid.
"""
P = validate_probs(probs)
y_arr = validate_labels(y, P.shape[0], P.shape[1])
lo, hi = float(bounds[0]), float(bounds[1])
if not (np.isfinite(lo) and np.isfinite(hi) and 0 < lo < hi):
raise CalibrationError(f"bounds must satisfy 0 < low < high, got {bounds}")
log_p = np.log(np.clip(P, 1e-12, 1.0))
def objective(tau: float) -> float:
logits = log_p / tau
logits -= logits.max(axis=1, keepdims=True)
ex = np.exp(logits)
Q = ex / ex.sum(axis=1, keepdims=True)
return nll_score(Q, y_arr)
res = minimize_scalar(objective, bounds=(lo, hi), method="bounded")
return float(res.x)