Skip to content

Implement temperature scaling for (multi-class) calibration #28574

Closed

Description

@dholzmueller

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 using log(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

  1. adrinjalali commented on Mar 4, 2024

    @adrinjalali
    Member
  2. ogrisel commented on Mar 4, 2024

    @ogrisel
    Member

    This sounds like a simple yet strong and very popular baseline.

    Note: the _get_logits trick 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 leverage predict_log_proba when it exists but I am not 100% sure if it's always equivalent. For some estimators, such as random forests, we do provide predict_log_proba but it's just calling np.log on predict_proba which is likely to be less stable than the _get_logit trick suggested here.

  3. removed
    Needs Triage
    on Mar 5, 2024
  4. virchan commented on Mar 10, 2024

    @virchan
    Member

    It appears that the temperature scaling neural network is defined by the function:

    $$\left[ y_1, \cdots, y_n \right] \mapsto \mathrm{softmax}\left( \left[ \frac{y_1}{T}, \cdots, \frac{y_n}{T} \right] \right),$$

    where $\displaystyle \sum_{i=1}^n y_i = 1$; and $T$ is the temperature parameter.

    So:

    1. "Training the model" means "optimising the loss with respect to $T$".
    2. The trained model needs to remember $T$, and possibly the input dimension $n$.

    Did I understand it correctly?

  5. dholzmueller commented on Mar 10, 2024

    @dholzmueller
    Author

    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)$
    if the $y_i$ are probabilities (actually, they don't need to be normalized for this to work).

    1. Indeed, and one could support different loss functions like log-loss and Brier loss. What I did above is to optimize $\beta = 1/T$ instead so a division by zero cannot occur.
    2. It needs to remember $T$, but not $n$.
  6. lorentzenchr commented on Mar 10, 2024

    @lorentzenchr
    Member

    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.

  7. virchan commented on Mar 12, 2024

    @virchan
    Member

    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.

  8. dholzmueller commented on Mar 13, 2024

    @dholzmueller
    Author

    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?

  9. lorentzenchr commented on Mar 13, 2024

    @lorentzenchr
    Member

    In this sense, post-hoc calibration of multiclass classification is an unsolved problem in the same sense that classification itself is an unsolved problem

    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.

  10. virchan commented on Mar 13, 2024

    @virchan
    Member

    Thank you for the replies; they are really helpful!

    I see there are two points of interest:

    1. Decide if the calibration methods improve the original predictions in a generic data project.
    2. Include (at least some) post-hoc calibration methods in 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 MLPClassifier module to create the "matrix scaling" calibration method, and I don't mind working on it at all.

    Would it be acceptable?

  11. dholzmueller commented on Mar 14, 2024

    @dholzmueller
    Author

    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.

    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?

  12. dholzmueller commented on Mar 14, 2024

    @dholzmueller
    Author

    @virchan

    1. has been evaluated at least in the original paper I mentioned, and probably in many others as well.
    2. The "matrix scaling" method mostly performed much worse than temperature scaling in the original paper, so I think temperature scaling should have higher priority.
  13. lorentzenchr commented on Mar 14, 2024

    @lorentzenchr
    Member

    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?

    Note that CalibratedClassifierCV has 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.

  14. 22 remaining items

  15. dholzmueller commented on Feb 3, 2025

    @dholzmueller
    Author

    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:

    Image

  16. ogrisel commented on Feb 5, 2025

    @ogrisel
    Member

    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?

  17. dholzmueller commented on Feb 5, 2025

    @dholzmueller
    Author
    • Isotonic regression is more competitive on binary than multiclass, but still worse than temperature scaling on the binary part of this benchmark. But I remember that when testing it on another benchmark with another model, it was comparable (with IVAP being the best of the binary methods I've tested). Maybe it is because the benchmark in the paper has more small datasets than the other one I've tried.
    • without Laplace smoothing isotonic regression is arbitrarily bad for logloss because it can predict zero probabilities (the score entirely depends on how your logloss implementation handles these). For Brier score there is practically no difference between the two versions. In practice I guess IVAP is better suited to handle this than Laplace smoothing, at least in the binary case, but it's also much slower.
  18. adrinjalali commented on Feb 18, 2025

    @adrinjalali
    Member

    I find comments about the wide use of a method quite a poor argument for inclusion. Just because everybody does X, does not imply I should do X. Otherwise stated, "Why don't you do X?" is the wrong question (and might create pressure). Instead, I should ask how to deal with the underlying subject, obviously it seems relevant. Maybe, I adopt X, maybe I have a better solution, maybe I just don't do anything about it.

    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?

  19. dholzmueller commented on Feb 18, 2025

    @dholzmueller
    Author

    @adrinjalali am I the one who should proceed here? I think we

    • need an agreement that this should be added (maybe @lorentzenchr can comment if he's okay with proceeding or if there should be a vote)
    • need someone to implement it. I am not familiar with the standards for a scikit-learn implementation, but I linked my (quite compact) implementation of it above. I can also condense it to a short numpy-only implementation here if that helps for someone to add the necessary checks/array-compatibility etc. for scikit-learn.
  20. lorentzenchr commented on Feb 18, 2025

    @lorentzenchr
    Member

    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:

  21. dholzmueller commented on Feb 18, 2025

    @dholzmueller
    Author

    Ah, great.

    • Is there any reason to use scipy.optimize over bisection search (as proposed by me above)? Bisection is fast, short (~5 lines), and robust (e.g., doesn't overshoot zero and can't have convergence issues).
    • The logits are trivial, just take 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).
  22. dholzmueller commented on Feb 18, 2025

    @dholzmueller
    Author

    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).

  23. virchan commented on Feb 18, 2025

    @virchan
    Member

    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.

  24. lorentzenchr commented on Feb 18, 2025

    @lorentzenchr
    Member

    Is there any reason to use scipy.optimize over bisection search (as proposed by me above)?

    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 via raw_predict added to the general API. But we can start with applying the link function.

  25. lorentzenchr commented on Aug 2, 2025

    @lorentzenchr
    Member

    Thanks to @virchan 🚀, this will land in our next release 1.8 (late autumn 2025).

  26. GaelVaroquaux commented on Aug 2, 2025

    @GaelVaroquaux
    Member

    Woo-hoo!!

    Thank you so much to everyone involved, in particular @virchan

  27. dholzmueller commented on Aug 2, 2025

    @dholzmueller
    Author

    Amazing! Thanks everyone and especially @virchan !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ModerateNew Featurehelp wantedmodule:calibration

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions