Repository navigation
Description
Describe the workflow you want to enable
It would be great to have temperature scaling available as a post-hoc calibration method for binary and multi-class classifiers, for example in CalibratedClassifierCV.
Describe your proposed solution
Temperature scaling is a simple, efficient, and very popular post-hoc calibration method that also naturally supports the multi-class classification setting. It has been proposed in Guo et al. (2017) with >5000 citations, so it meets the inclusion criterion: http://proceedings.mlr.press/v70/guo17a.html
It also does not affect rank-based metrics (if the temperature is restricted to positive values) unlike isotonic regression (#16321). Moreover, it avoids the infinite-log-loss problems of isotonic regression.
Temperature scaling has been discussed in #21785
I experimented with different post-hoc calibration methods on 71 medium-sized (2K-50K samples) tabular classification data sets. For NNs and XGBoost, temperature scaling is competitive with isotonic regression and considerably better than Platt scaling (if Platt scaling is applied to probabilities, as implemented in scikit-learn, and not logits). For AUC, it is considerably better than isotonic regression.
Here is a simple implementation using PyTorch (can be adapted to numpy). It is derived from the popular but no longer maintained implementation at https://github.com/gpleiss/temperature_scaling/blob/master/temperature_scaling.py
with the following changes:
- using inverse temperatures to prevent division by zero errors
- using 50 optimizer steps instead of a single one (seemingly an error in the mentioned repo). (The original paper mentions that 10 CG iterations should be enough, here it is 50 L-BFGS iterations.)
- accepting probabilities as provided by many scikit-learn estimators using
predict_proba(). The code converts probabilities to logits usinglog(probs + 1e-10). While the logits are only determined up to a constant shift, the choice of the constant does not affect the result of temperature scaling.
import torch
import torch.nn as nn
import numpy as np
from sklearn.base import BaseEstimator
class InverseTemperatureScalingCalibrator(BaseEstimator):
# following https://github.com/gpleiss/temperature_scaling/blob/master/temperature_scaling.py
def _get_logits(self, X):
X = X + 1e-10
X /= np.sum(X, axis=-1, keepdims=True)
return torch.as_tensor(np.log(X), dtype=torch.float32)
def fit(self, X, y):
# X should be the probabilities as output by predict_proba()
logits = self._get_logits(X)
labels = torch.as_tensor(y)
self.inv_temperature_ = nn.Parameter(torch.ones(1) / 1.5)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.LBFGS([self.inv_temperature_], lr=0.01, max_iter=50)
def eval():
optimizer.zero_grad()
y_pred = logits * self.inv_temperature_[:, None]
loss = criterion(y_pred, labels)
loss.backward()
return loss
for i in range(50):
optimizer.step(eval)
print(f'Optimal temperature: {(1./self.inv_temperature_).item():g}')
return self
def predict_proba(self, X):
# X should be the probabilities as output by predict_proba()
logits = self._get_logits(X)
with torch.no_grad():
y_pred = logits * self.inv_temperature_[:, None]
return torch.softmax(y_pred, dim=-1).detach().numpy()Describe alternatives you've considered, if relevant
Centered isotonic regression (#21454) is less popular and does not fully solve the problem of affecting rank-based metrics.
Beta-calibration (#25552) seems very similar or even partially identical but is less well-cited, and only formulated for binary classification.
Additional context
No response
Activity
adrinjalali commentedon Mar 4, 2024
@glemaitre WDYT?
ogrisel commentedon Mar 4, 2024
This sounds like a simple yet strong and very popular baseline.
Note: the
_get_logitstrick to inverse a sigmoid / softmax is a bit of a hack but scikit-learn does not provide a generic way to access raw logits in general. We could leveragepredict_log_probawhen it exists but I am not 100% sure if it's always equivalent. For some estimators, such as random forests, we do providepredict_log_probabut it's just callingnp.logonpredict_probawhich is likely to be less stable than the_get_logittrick suggested here.virchan commentedon Mar 10, 2024
It appears that the temperature scaling neural network is defined by the function:
where$\displaystyle \sum_{i=1}^n y_i = 1$ ; and $T$ is the temperature parameter.
So:
Did I understand it correctly?
dholzmueller commentedon Mar 10, 2024
Almost. It would be
$\left[ y_1, \cdots, y_n \right] \mapsto \mathrm{softmax}\left( \left[ \frac{\log(y_1)}{T}, \cdots, \frac{\log(y_n)}{T} \right] \right)$ $y_i$ are probabilities (actually, they don't need to be normalized for this to work).
if the
lorentzenchr commentedon Mar 10, 2024
In my opinion, post-hoc calibration of multiclass classification is an unsolved problem. A lot of heuristic arguments are used and it is difficult a choose one method over others. Classifier calibration: a survey on how to assess and improve predicted class probabilities gives a good overview.
virchan commentedon Mar 12, 2024
Could we make it solvable by constraining ourselves with the "matrix scaling" case (and hence the "temperature" and "vector" cases)? It also seems like we have fewer arguments to worry about. However, there might be a chance of misunderstanding on my part as well.
dholzmueller commentedon Mar 13, 2024
Post-hoc calibration is essentially about learning a classifier whose inputs are the model outputs that should be calibrated. In this sense, post-hoc calibration of multiclass classification is an unsolved problem in the same sense that classification itself is an unsolved problem, because there is no free lunch. Still, scikit-learn provides a lot of classifiers, so why not also provide the "logistic regression" of post-hoc calibration methods?
lorentzenchr commentedon Mar 13, 2024
Not the hole story. Post-hoc classification estimates$P(Y|m(X))$ with model $m$ , while the original goal is to estimate $P(Y|X)$ . Note the difference in conditioning! For binary classification, $m(X)$ is essentially 1-dimensional and therefore $P(Y|m(X))$ is amenable to estimation.
virchan commentedon Mar 13, 2024
Thank you for the replies; they are really helpful!
I see there are two points of interest:
scikit-learn's framework.(Let me know if I missed any.)
The former feels more like a hypothesis testing problem than a software development problem.
For the latter, I can mirror the
MLPClassifiermodule to create the "matrix scaling" calibration method, and I don't mind working on it at all.Would it be acceptable?
dholzmueller commentedon Mar 14, 2024
Sure, the 1-dimensional problem is "easy" and the general multi-class case is not efficiently solvable in general. But why does that justify not offering a method that is often much better than doing nothing?
dholzmueller commentedon Mar 14, 2024
@virchan
lorentzenchr commentedon Mar 14, 2024
Note that
CalibratedClassifierCVhas multiclass support via OvR, see https://scikit-learn.org/stable/modules/calibration.html#multiclass-support.If another methods shows clear improvement (best done in highly cited literature), we are open, even happy to include it.
22 remaining items
dholzmueller commentedon Feb 3, 2025
Our new paper (https://arxiv.org/abs/2501.19195) includes a small calibration benchmark for XGBoost with default parameters as well as an optimized temperature scaling implementation using bisection search that is fast and avoids L-BFGS optimization issues of some alternative implementations. I think it would serve as a good template, also because it does not rely on autodiff but only on a simple analytic form of the gradient that can also be implemented in numpy (although I noticed that the numpy version is somehow around 4x slower than the torch version, maybe because it uses a different number of threads). Here is the implementation: https://github.com/dholzmueller/probmetrics/blob/3d5f48b3e8fb9fad8bc581a7d4fa51aaecfd47a3/probmetrics/calibrators.py#L109
And here are some benchmark results for the log-loss of different methods on XGBoost with default parameters, stopped on accuracy, from Figure E.1:
ogrisel commentedon Feb 5, 2025
Thanks for sharing @dholzmueller, this paper is indeed very interesting. I agree that the bisection 1d optimizer looks good and simple to implement and maintain. We could even use scipy's Brent method or other univariate solvers (
scipy.optimize.minimize_scalar).Out of curiosity:
I assume that the benchmark above is an aggregate result about multiclass and binary classification problems. Isotonic calibration is not naturally suited for multiclass and therefore relies on an OvR reduction followed by an across-class renormalization hack. Would IC be competitive (in terms of mean normalized logloss) if you restrict the benchmark to binary classification problems only?
did you also benchmark isotonic calibration with vs without Laplacian smoothing?
dholzmueller commentedon Feb 5, 2025
adrinjalali commentedon Feb 18, 2025
Sometimes a solution in "theory" might apply to only X, but in "practice", it helps with X,Y,Z, etc, and therefore not "wrong" to use due to empirical evidence. If something is widely used, it might mean that it actually works and we shouldn't worry too much about the theoretical limitations if empirically it's useful.
@dholzmueller according to the last message of @ogrisel , is it clear to you how to proceed here?
dholzmueller commentedon Feb 18, 2025
@adrinjalali am I the one who should proceed here? I think we
lorentzenchr commentedon Feb 18, 2025
I thought I was clear in #28574 (comment). The consensus seems to be inclusion of this feature, it just needs somebody to implement it (c.f. label "help wanted").
Hints for an implementation:
minimize_scalar)I don't know how to overcome this without tackling this issue first.dholzmueller commentedon Feb 18, 2025
Ah, great.
np.log(estimator.predict_proba(...) + 1e-8)or so, where the 1e-8 is to avoid issues with zero probabilities. The logits are only uniquely determined up to a shift, but different shifts only lead to different shifts in the temperature scaling output, which doesn't affect the results after taking the softmax. In other words,softmax(beta * (logits + shift)) = softmax(beta * logits + beta * shift) = softmax(beta * logits).dholzmueller commentedon Feb 18, 2025
Of course, in the binary setting, the logits are slightly different if you only have the probabilities of one class, but then there is even a bijective mapping (or one stacks
[probs, 1-probs]and uses the same code as for multiclass).virchan commentedon Feb 18, 2025
I can work on a PR for this issue.
I previously worked on an implementation using
scipy.optimize. Now that I'm more familiar with the scikit-learn codebase, I think I can develop something that meets the project's standards. Additionally, I'd like to explore whether the Array API can be applied here.lorentzenchr commentedon Feb 18, 2025
Yes, don't reinvent the wheel.
About the multinomial "logits", one can use
sklearn._loss.link.MultinomialLogit().link(y_pred). That'll work, but I would much prefer to have direct access viaraw_predictadded to the general API. But we can start with applying the link function.lorentzenchr commentedon Aug 2, 2025
Thanks to @virchan 🚀, this will land in our next release 1.8 (late autumn 2025).
GaelVaroquaux commentedon Aug 2, 2025
Woo-hoo!!
Thank you so much to everyone involved, in particular @virchan
dholzmueller commentedon Aug 2, 2025
Amazing! Thanks everyone and especially @virchan !