scikit-learn mixture sklearn mixture gmm Gaussian mixture models

Answer:
.. _mixture:

.. _gmm:

=======================
Gaussian mixture models
=======================

.. currentmodule:: sklearn.mixture

``sklearn.mixture`` is a package which enables one to learn
Gaussian Mixture Models (diagonal, spherical, tied and full covariance
matrices supported), sample them, and estimate them from
data. Facilities to help determine the appropriate number of
components are also provided.

.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_pdf_001.png
  :target: ../auto_examples/mixture/plot_gmm_pdf.html
  :align: center
  :scale: 50%

  **Two-component Gaussian mixture model:** *data points, and equi-probability
  surfaces of the model.*

A Gaussian mixture model is a probabilistic model that assumes all the
data points are generated from a mixture of a finite number of
Gaussian distributions with unknown parameters. One can think of
mixture models as generalizing k-means clustering to incorporate
information about the covariance structure of the data as well as the
centers of the latent Gaussians.

Scikit-learn implements different classes to estimate Gaussian
mixture models, that correspond to different estimation strategies,
detailed below.

Gaussian Mixture
================

The :class:`GaussianMixture` object implements the
:ref:`expectation-maximization <expectation_maximization>` (EM)
algorithm for fitting mixture-of-Gaussian models. It can also draw
confidence ellipsoids for multivariate models, and compute the
Bayesian Information Criterion to assess the number of clusters in the
data. A :meth:`GaussianMixture.fit` method is provided that learns a Gaussian
Mixture Model from train data. Given test data, it can assign to each
sample the Gaussian it most probably belongs to using
the :meth:`GaussianMixture.predict` method.

..
    Alternatively, the probability of each
    sample belonging to the various Gaussians may be retrieved using the
    :meth:`GaussianMixture.predict_proba` method.

The :class:`GaussianMixture` comes with different options to constrain the
covariance of the difference classes estimated: spherical, diagonal, tied or
full covariance.

.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_covariances_001.png
   :target: ../auto_examples/mixture/plot_gmm_covariances.html
   :align: center
   :scale: 75%

.. rubric:: Examples

* See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_covariances.py` for an example of
  using the Gaussian mixture as clustering on the iris dataset.

* See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_pdf.py` for an example on plotting the
  density estimation.

.. dropdown:: Pros and cons of class GaussianMixture

  .. rubric:: Pros

  :Speed: It is the fastest algorithm for learning mixture models

  :Agnostic: As this algorithm maximizes only the likelihood, it
    will not bias the means towards zero, or bias the cluster sizes to
    have specific structures that might or might not apply.

  .. rubric:: Cons

  :Singularities: When one has insufficiently many points per
    mixture, estimating the covariance matrices becomes difficult,
    and the algorithm is known to diverge and find solutions with
    infinite likelihood unless one regularizes the covariances artificially.

  :Number of components: This algorithm will always use all the
    components it has access to, needing held-out data
    or information theoretical criteria to decide how many components to use
    in the absence of external cues.

.. dropdown:: Selecting the number of components in a classical Gaussian Mixture model

  The BIC criterion can be used to select the number of components in a Gaussian
  Mixture in an efficient way. In theory, it recovers the true number of
  components only in the asymptotic regime (i.e. if much data is available and
  assuming that the data was actually generated i.i.d. from a mixture of Gaussian
  distribution). Note that using a :ref:`Variational Bayesian Gaussian mixture <bgmm>`
  avoids the specification of the number of components for a Gaussian mixture
  model.

  .. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_selection_002.png
    :target: ../auto_examples/mixture/plot_gmm_selection.html
    :align: center
    :scale: 50%

  .. rubric:: Examples

  * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_selection.py` for an example
    of model selection performed with classical Gaussian mixture.

.. _expectation_maximization:

.. dropdown:: Estimation algorithm expectation-maximization

  The main difficulty in learning Gaussian mixture models from unlabeled
  data is that one usually doesn't know which points came from
  which latent component (if one has access to this information it gets
  very easy to fit a separate Gaussian distribution to each set of
  points). `Expectation-maximization
  <https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm>`_
  is a well-founded statistical
  algorithm to get around this problem by an iterative process. First
  one assumes random components (randomly centered on data points,
  learned from k-means, or even just normally distributed around the
  origin) and computes for each point a probability of being generated by
  each component of the model. Then, one tweaks the
  parameters to maximize the likelihood of the data given those
  assignments. Repeating this process is guaranteed to always converge
  to a local optimum.

.. dropdown:: Choice of the Initialization method

  There is a choice of four initialization methods (as well as inputting user defined
  initial means) to generate the initial centers for the model components:

  k-means (default)
    This applies a traditional k-means clustering algorithm.
    This can be computationally expensive compared to other initialization methods.

  k-means++
    This uses the initialization method of k-means clustering: k-means++.
    This will pick the first center at random from the data. Subsequent centers will be
    chosen from a weighted distribution of the data favouring points further away from
    existing centers. k-means++ is the default initialization for k-means so will be
    quicker than running a full k-means but can still take a significant amount of
    time for large data sets with many components.

  random_from_data
    This will pick random data points from the input data as the initial
    centers. This is a very fast method of initialization but can produce non-convergent
    results if the chosen points are too close to each other.

  random
    Centers are chosen as a small perturbation away from the mean of all data.
    This method is simple but can lead to the model taking longer to converge.

  .. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_init_001.png
    :target: ../auto_examples/mixture/plot_gmm_init.html
    :align: center
    :scale: 50%

  .. rubric:: Examples

  * See :ref:`sphx_glr_auto_examples_mixture_plot_gmm_init.py` for an example of
    using different initializations in Gaussian Mixture.

.. _bgmm:

Variational Bayesian Gaussian Mixture
=====================================

The :class:`BayesianGaussianMixture` object implements a variant of the
Gaussian mixture model with variational inference algorithms. The API is
similar to the one defined by :class:`GaussianMixture`.

.. _variational_inference:

**Estimation algorithm: variational inference**

Variational inference is an extension of expectation-maximization that
maximizes a lower bound on model evidence (including
priors) instead of data likelihood. The principle behind
variational methods is the same as expectation-maximization (that is
both are iterative algorithms that alternate between finding the
probabilities for each point to be generated by each mixture and
fitting the mixture to these assigned points), but variational
methods add regularization by integrating information from prior
distributions. This avoids the singularities often found in
expectation-maximization solutions but introduces some subtle biases
to the model. Inference is often notably slower, but not usually as
much so as to render usage unpractical.

Due to its Bayesian nature, the variational algorithm needs more hyperparameters
than expectation-maximization, the most important of these being the
concentration parameter ``weight_concentration_prior``. Specifying a low value
for the concentration prior will make the model put most of the weight on a few
components and set the remaining components' weights very close to zero. High
values of the concentration prior will allow a larger number of components to
be active in the mixture.

The parameters implementation of the :class:`BayesianGaussianMixture` class
proposes two types of prior for the weights distribution: a finite mixture model
with Dirichlet distribution and an infinite mixture model with the Dirichlet
Process. In practice Dirichlet Process inference algorithm is approximated and
uses a truncated distribution with a fixed maximum number of components (called
the Stick-breaking representation). The number of components actually used
almost always depends on the data.

The next figure compares the results obtained for the different type of the
weight concentration prior (parameter ``weight_concentration_prior_type``)
for different values of ``weight_concentration_prior``.
Here, we can see the value of the ``weight_concentration_prior`` parameter
has a strong impact on the effective number of active components obtained. We
can also notice that large values for the concentration weight prior lead to
more uniform weights when the type of prior is 'dirichlet_distribution' while
this is not necessarily the case for the 'dirichlet_process' type (used by
default).

.. |plot_bgmm| image:: ../auto_examples/mixture/images/sphx_glr_plot_concentration_prior_001.png
   :target: ../auto_examples/mixture/plot_concentration_prior.html
   :scale: 48%

.. |plot_dpgmm| image:: ../auto_examples/mixture/images/sphx_glr_plot_concentration_prior_002.png
   :target: ../auto_examples/mixture/plot_concentration_prior.html
   :scale: 48%

.. centered:: |plot_bgmm| |plot_dpgmm|

The examples below compare Gaussian mixture models with a fixed number of
components, to the variational Gaussian mixture models with a Dirichlet process
prior. Here, a classical Gaussian mixture is fitted with 5 components on a
dataset composed of 2 clusters. We can see that the variational Gaussian mixture
with a Dirichlet process prior is able to limit itself to only 2 components
whereas the Gaussian mixture fits the data with a fixed number of components
that has to be set a priori by the user. In this case the user has selected
``n_components=5`` which does not match the true generative distribution of this
toy dataset. Note that with very little observations, the variational Gaussian
mixture models with a Dirichlet process prior can take a conservative stand, and
fit only one component.

.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_001.png
   :target: ../auto_examples/mixture/plot_gmm.html
   :align: center
   :scale: 70%

On the following figure we are fitting a dataset not well-depicted by a
Gaussian mixture. Adjusting the ``weight_concentration_prior``, parameter of the
:class:`BayesianGaussianMixture` controls the number of components used to fit
this data. We also present on the last two plots a random sampling generated
from the two resulting mixtures.

.. figure:: ../auto_examples/mixture/images/sphx_glr_plot_gmm_sin_001.png
   :target: ../auto_examples/mixture/plot_gmm_sin.html
   :align: center
   :scale: 65%

.. rubric:: Examples

* See :ref:`sphx_glr_auto_examples_mixture_plot_gmm.py` for an example on
  plotting the confidence ellipsoids for both :class:`GaussianMixture`
  and :class:`BayesianGaussianMixture`.

* :ref:`sphx_glr_auto_examples_mixture_plot_gmm_sin.py` shows using
  :class:`GaussianMixture` and :class:`BayesianGaussianMixture` to fit a
  sine wave.

* See :ref:`sphx_glr_auto_examples_mixture_plot_concentration_prior.py`
  for an example plotting the confidence ellipsoids for the
  :class:`BayesianGaussianMixture` with different
  ``weight_concentration_prior_type`` for different values of the parameter
  ``weight_concentration_prior``.

.. dropdown:: Pros and cons of variational inference with BayesianGaussianMixture

  .. rubric:: Pros

  :Automatic selection: When ``weight_concentration_prior`` is small enough and
    ``n_components`` is larger than what is found necessary by the model, the
    Variational Bayesian mixture model has a natural tendency to set some mixture
    weights values close to zero. This makes it possible to let the model choose
    a suitable number of effective components automatically. Only an upper bound
    of this number needs to be provided. Note however that the "ideal" number of
    active components is very application specific and is typically ill-defined
    in a data exploration setting.

  :Less sensitivity to the number of parameters: Unlike finite models, which will
    almost always use all components as much as they can, and hence will produce
    wildly different solutions for different numbers of components, the
    variational inference with a Dirichlet process prior
    (``weight_concentration_prior_type='dirichlet_process'``) won't change much
    with changes to the parameters, leading to more stability and less tuning.

  :Regularization: Due to the incorporation of prior information,
    variational solutions have less pathological special cases than
    expectation-maximization solutions.

  .. rubric:: Cons

  :Speed: The extra parametrization necessary for variational inference makes
    inference slower, although not by much.

  :Hyperparameters: This algorithm needs an extra hyperparameter
    that might need experimental tuning via cross-validation.

  :Bias: There are many implicit biases in the inference algorithms (and also in
    the Dirichlet process if used), and whenever there is a mismatch between
    these biases and the data it might be possible to fit better models using a
    finite mixture.

.. _dirichlet_process:

The Dirichlet Process
---------------------

Here we describe variational inference algorithms on Dirichlet process
mixture. The Dirichlet process is a prior probability distribution on
*clusterings with an infinite, unbounded, number of partitions*.
Variational techniques let us incorporate this prior structure on
Gaussian mixture models at almost no penalty in inference time, comparing
with a finite Gaussian mixture model.

An important question is how can the Dirichlet process use an infinite,
unbounded number of clusters and still be consistent. While a full explanation
doesn't fit this manual, one can think of its `stick breaking process
<https://en.wikipedia.org/wiki/Dirichlet_process#The_stick-breaking_process>`_
analogy to help understanding it. The stick breaking process is a generative
story for the Dirichlet process. We start with a unit-length stick and in each
step we break off a portion of the remaining stick. Each time, we associate the
length of the piece of the stick to the proportion of points that falls into a
group of the mixture. At the end, to represent the infinite mixture, we
associate the last remaining piece of the stick to the proportion of points
that don't fall into all the other groups. The length of each piece is a random
variable with probability proportional to the concentration parameter. Smaller
values of the concentration will divide the unit-length into larger pieces of
the stick (defining more concentrated distribution). Larger concentration
values will create smaller pieces of the stick (increasing the number of
components with non zero weights).

Variational inference techniques for the Dirichlet process still work
with a finite approximation to this infinite mixture model, but
instead of having to specify a priori how many components one wants to
use, one just specifies the concentration parameter and an upper bound
on the number of mixture components (this upper bound, assuming it is
higher than the "true" number of components, affects only algorithmic
complexity, not the actual number of components used).

mixture       gmm                           Gaussian mixture models                             currentmodule   sklearn mixture    sklearn mixture   is a package which enables one to learn Gaussian Mixture Models  diagonal  spherical  tied and full covariance matrices supported   sample them  and estimate them from data  Facilities to help determine the appropriate number of components are also provided      figure      auto examples mixture images sphx glr plot gmm pdf 001 png    target     auto examples mixture plot gmm pdf html    align  center    scale  50       Two component Gaussian mixture model     data points  and equi probability   surfaces of the model    A Gaussian mixture model is a probabilistic model that assumes all the data points are generated from a mixture of a finite number of Gaussian distributions with unknown parameters  One can think of mixture models as generalizing k means clustering to incorporate information about the covariance structure of the data as well as the centers of the latent Gaussians   Scikit learn implements different classes to estimate Gaussian mixture models  that correspond to different estimation strategies  detailed below   Gaussian Mixture                   The  class  GaussianMixture  object implements the  ref  expectation maximization  expectation maximization    EM  algorithm for fitting mixture of Gaussian models  It can also draw confidence ellipsoids for multivariate models  and compute the Bayesian Information Criterion to assess the number of clusters in the data  A  meth  GaussianMixture fit  method is provided that learns a Gaussian Mixture Model from train data  Given test data  it can assign to each sample the Gaussian it most probably belongs to using the  meth  GaussianMixture predict  method          Alternatively  the probability of each     sample belonging to the various Gaussians may be retrieved using the      meth  GaussianMixture predict proba  method   The  class  GaussianMixture  comes with different options to constrain the covariance of the difference classes estimated  spherical  diagonal  tied or full covariance      figure      auto examples mixture images sphx glr plot gmm covariances 001 png     target     auto examples mixture plot gmm covariances html     align  center     scale  75      rubric   Examples    See  ref  sphx glr auto examples mixture plot gmm covariances py  for an example of   using the Gaussian mixture as clustering on the iris dataset     See  ref  sphx glr auto examples mixture plot gmm pdf py  for an example on plotting the   density estimation      dropdown   Pros and cons of class GaussianMixture       rubric   Pros     Speed  It is the fastest algorithm for learning mixture models     Agnostic  As this algorithm maximizes only the likelihood  it     will not bias the means towards zero  or bias the cluster sizes to     have specific structures that might or might not apply        rubric   Cons     Singularities  When one has insufficiently many points per     mixture  estimating the covariance matrices becomes difficult      and the algorithm is known to diverge and find solutions with     infinite likelihood unless one regularizes the covariances artificially      Number of components  This algorithm will always use all the     components it has access to  needing held out data     or information theoretical criteria to decide how many components to use     in the absence of external cues      dropdown   Selecting the number of components in a classical Gaussian Mixture model    The BIC criterion can be used to select the number of components in a Gaussian   Mixture in an efficient way  In theory  it recovers the true number of   components only in the asymptotic regime  i e  if much data is available and   assuming that the data was actually generated i i d  from a mixture of Gaussian   distribution   Note that using a  ref  Variational Bayesian Gaussian mixture  bgmm     avoids the specification of the number of components for a Gaussian mixture   model        figure      auto examples mixture images sphx glr plot gmm selection 002 png      target     auto examples mixture plot gmm selection html      align  center      scale  50        rubric   Examples      See  ref  sphx glr auto examples mixture plot gmm selection py  for an example     of model selection performed with classical Gaussian mixture       expectation maximization      dropdown   Estimation algorithm expectation maximization    The main difficulty in learning Gaussian mixture models from unlabeled   data is that one usually doesn t know which points came from   which latent component  if one has access to this information it gets   very easy to fit a separate Gaussian distribution to each set of   points    Expectation maximization    https   en wikipedia org wiki Expectation E2 80 93maximization algorithm      is a well founded statistical   algorithm to get around this problem by an iterative process  First   one assumes random components  randomly centered on data points    learned from k means  or even just normally distributed around the   origin  and computes for each point a probability of being generated by   each component of the model  Then  one tweaks the   parameters to maximize the likelihood of the data given those   assignments  Repeating this process is guaranteed to always converge   to a local optimum      dropdown   Choice of the Initialization method    There is a choice of four initialization methods  as well as inputting user defined   initial means  to generate the initial centers for the model components     k means  default      This applies a traditional k means clustering algorithm      This can be computationally expensive compared to other initialization methods     k means       This uses the initialization method of k means clustering  k means        This will pick the first center at random from the data  Subsequent centers will be     chosen from a weighted distribution of the data favouring points further away from     existing centers  k means   is the default initialization for k means so will be     quicker than running a full k means but can still take a significant amount of     time for large data sets with many components     random from data     This will pick random data points from the input data as the initial     centers  This is a very fast method of initialization but can produce non convergent     results if the chosen points are too close to each other     random     Centers are chosen as a small perturbation away from the mean of all data      This method is simple but can lead to the model taking longer to converge        figure      auto examples mixture images sphx glr plot gmm init 001 png      target     auto examples mixture plot gmm init html      align  center      scale  50        rubric   Examples      See  ref  sphx glr auto examples mixture plot gmm init py  for an example of     using different initializations in Gaussian Mixture       bgmm   Variational Bayesian Gaussian Mixture                                        The  class  BayesianGaussianMixture  object implements a variant of the Gaussian mixture model with variational inference algorithms  The API is similar to the one defined by  class  GaussianMixture        variational inference     Estimation algorithm  variational inference    Variational inference is an extension of expectation maximization that maximizes a lower bound on model evidence  including priors  instead of data likelihood  The principle behind variational methods is the same as expectation maximization  that is both are iterative algorithms that alternate between finding the probabilities for each point to be generated by each mixture and fitting the mixture to these assigned points   but variational methods add regularization by integrating information from prior distributions  This avoids the singularities often found in expectation maximization solutions but introduces some subtle biases to the model  Inference is often notably slower  but not usually as much so as to render usage unpractical   Due to its Bayesian nature  the variational algorithm needs more hyperparameters than expectation maximization  the most important of these being the concentration parameter   weight concentration prior    Specifying a low value for the concentration prior will make the model put most of the weight on a few components and set the remaining components  weights very close to zero  High values of the concentration prior will allow a larger number of components to be active in the mixture   The parameters implementation of the  class  BayesianGaussianMixture  class proposes two types of prior for the weights distribution  a finite mixture model with Dirichlet distribution and an infinite mixture model with the Dirichlet Process  In practice Dirichlet Process inference algorithm is approximated and uses a truncated distribution with a fixed maximum number of components  called the Stick breaking representation   The number of components actually used almost always depends on the data   The next figure compares the results obtained for the different type of the weight concentration prior  parameter   weight concentration prior type    for different values of   weight concentration prior    Here  we can see the value of the   weight concentration prior   parameter has a strong impact on the effective number of active components obtained  We can also notice that large values for the concentration weight prior lead to more uniform weights when the type of prior is  dirichlet distribution  while this is not necessarily the case for the  dirichlet process  type  used by default        plot bgmm  image      auto examples mixture images sphx glr plot concentration prior 001 png     target     auto examples mixture plot concentration prior html     scale  48       plot dpgmm  image      auto examples mixture images sphx glr plot concentration prior 002 png     target     auto examples mixture plot concentration prior html     scale  48      centered    plot bgmm   plot dpgmm   The examples below compare Gaussian mixture models with a fixed number of components  to the variational Gaussian mixture models with a Dirichlet process prior  Here  a classical Gaussian mixture is fitted with 5 components on a dataset composed of 2 clusters  We can see that the variational Gaussian mixture with a Dirichlet process prior is able to limit itself to only 2 components whereas the Gaussian mixture fits the data with a fixed number of components that has to be set a priori by the user  In this case the user has selected   n components 5   which does not match the true generative distribution of this toy dataset  Note that with very little observations  the variational Gaussian mixture models with a Dirichlet process prior can take a conservative stand  and fit only one component      figure      auto examples mixture images sphx glr plot gmm 001 png     target     auto examples mixture plot gmm html     align  center     scale  70    On the following figure we are fitting a dataset not well depicted by a Gaussian mixture  Adjusting the   weight concentration prior    parameter of the  class  BayesianGaussianMixture  controls the number of components used to fit this data  We also present on the last two plots a random sampling generated from the two resulting mixtures      figure      auto examples mixture images sphx glr plot gmm sin 001 png     target     auto examples mixture plot gmm sin html     align  center     scale  65        rubric   Examples    See  ref  sphx glr auto examples mixture plot gmm py  for an example on   plotting the confidence ellipsoids for both  class  GaussianMixture    and  class  BayesianGaussianMixture       ref  sphx glr auto examples mixture plot gmm sin py  shows using    class  GaussianMixture  and  class  BayesianGaussianMixture  to fit a   sine wave     See  ref  sphx glr auto examples mixture plot concentration prior py    for an example plotting the confidence ellipsoids for the    class  BayesianGaussianMixture  with different     weight concentration prior type   for different values of the parameter     weight concentration prior        dropdown   Pros and cons of variational inference with BayesianGaussianMixture       rubric   Pros     Automatic selection  When   weight concentration prior   is small enough and       n components   is larger than what is found necessary by the model  the     Variational Bayesian mixture model has a natural tendency to set some mixture     weights values close to zero  This makes it possible to let the model choose     a suitable number of effective components automatically  Only an upper bound     of this number needs to be provided  Note however that the  ideal  number of     active components is very application specific and is typically ill defined     in a data exploration setting      Less sensitivity to the number of parameters  Unlike finite models  which will     almost always use all components as much as they can  and hence will produce     wildly different solutions for different numbers of components  the     variational inference with a Dirichlet process prior        weight concentration prior type  dirichlet process     won t change much     with changes to the parameters  leading to more stability and less tuning      Regularization  Due to the incorporation of prior information      variational solutions have less pathological special cases than     expectation maximization solutions        rubric   Cons     Speed  The extra parametrization necessary for variational inference makes     inference slower  although not by much      Hyperparameters  This algorithm needs an extra hyperparameter     that might need experimental tuning via cross validation      Bias  There are many implicit biases in the inference algorithms  and also in     the Dirichlet process if used   and whenever there is a mismatch between     these biases and the data it might be possible to fit better models using a     finite mixture       dirichlet process   The Dirichlet Process                        Here we describe variational inference algorithms on Dirichlet process mixture  The Dirichlet process is a prior probability distribution on  clusterings with an infinite  unbounded  number of partitions   Variational techniques let us incorporate this prior structure on Gaussian mixture models at almost no penalty in inference time  comparing with a finite Gaussian mixture model   An important question is how can the Dirichlet process use an infinite  unbounded number of clusters and still be consistent  While a full explanation doesn t fit this manual  one can think of its  stick breaking process  https   en wikipedia org wiki Dirichlet process The stick breaking process    analogy to help understanding it  The stick breaking process is a generative story for the Dirichlet process  We start with a unit length stick and in each step we break off a portion of the remaining stick  Each time  we associate the length of the piece of the stick to the proportion of points that falls into a group of the mixture  At the end  to represent the infinite mixture  we associate the last remaining piece of the stick to the proportion of points that don t fall into all the other groups  The length of each piece is a random variable with probability proportional to the concentration parameter  Smaller values of the concentration will divide the unit length into larger pieces of the stick  defining more concentrated distribution   Larger concentration values will create smaller pieces of the stick  increasing the number of components with non zero weights    Variational inference techniques for the Dirichlet process still work with a finite approximation to this infinite mixture model  but instead of having to specify a priori how many components one wants to use  one just specifies the concentration parameter and an upper bound on the number of mixture components  this upper bound  assuming it is higher than the  true  number of components  affects only algorithmic complexity  not the actual number of components used


scikit-learn When performing classification you often want not only to predict the class sklearn calibration calibration Probability calibration

Answer:
.. _calibration:

=======================
Probability calibration
=======================

.. currentmodule:: sklearn.calibration

When performing classification you often want not only to predict the class
label, but also obtain a probability of the respective label. This probability
gives you some kind of confidence on the prediction. Some models can give you
poor estimates of the class probabilities and some even do not support
probability prediction (e.g., some instances of
:class:`~sklearn.linear_model.SGDClassifier`).
The calibration module allows you to better calibrate
the probabilities of a given model, or to add support for probability
prediction.

Well calibrated classifiers are probabilistic classifiers for which the output
of the :term:`predict_proba` method can be directly interpreted as a confidence
level.
For instance, a well calibrated (binary) classifier should classify the samples such
that among the samples to which it gave a :term:`predict_proba` value close to, say,
0.8, approximately 80% actually belong to the positive class.

Before we show how to re-calibrate a classifier, we first need a way to detect how
good a classifier is calibrated.

.. note::
    Strictly proper scoring rules for probabilistic predictions like
    :func:`sklearn.metrics.brier_score_loss` and
    :func:`sklearn.metrics.log_loss` assess calibration (reliability) and
    discriminative power (resolution) of a model, as well as the randomness of the data
    (uncertainty) at the same time. This follows from the well-known Brier score
    decomposition of Murphy [1]_. As it is not clear which term dominates, the score is
    of limited use for assessing calibration alone (unless one computes each term of
    the decomposition). A lower Brier loss, for instance, does not necessarily
    mean a better calibrated model, it could also mean a worse calibrated model with much
    more discriminatory power, e.g. using many more features.

.. _calibration_curve:

Calibration curves
------------------

Calibration curves, also referred to as *reliability diagrams* (Wilks 1995 [2]_),
compare how well the probabilistic predictions of a binary classifier are calibrated.
It plots the frequency of the positive label (to be more precise, an estimation of the
*conditional event probability* :math:`P(Y=1|\text{predict_proba})`) on the y-axis
against the predicted probability :term:`predict_proba` of a model on the x-axis.
The tricky part is to get values for the y-axis.
In scikit-learn, this is accomplished by binning the predictions such that the x-axis
represents the average predicted probability in each bin.
The y-axis is then the *fraction of positives* given the predictions of that bin, i.e.
the proportion of samples whose class is the positive class (in each bin).

The top calibration curve plot is created with
:func:`CalibrationDisplay.from_estimator`, which uses :func:`calibration_curve` to
calculate the per bin average predicted probabilities and fraction of positives.
:func:`CalibrationDisplay.from_estimator`
takes as input a fitted classifier, which is used to calculate the predicted
probabilities. The classifier thus must have :term:`predict_proba` method. For
the few classifiers that do not have a :term:`predict_proba` method, it is
possible to use :class:`CalibratedClassifierCV` to calibrate the classifier
outputs to probabilities.

The bottom histogram gives some insight into the behavior of each classifier
by showing the number of samples in each predicted probability bin.

.. figure:: ../auto_examples/calibration/images/sphx_glr_plot_compare_calibration_001.png
   :target: ../auto_examples/calibration/plot_compare_calibration.html
   :align: center

.. currentmodule:: sklearn.linear_model

:class:`LogisticRegression` is more likely to return well calibrated predictions by itself as it has a
canonical link function for its loss, i.e. the logit-link for the :ref:`log_loss`.
In the unpenalized case, this leads to the so-called **balance property**, see [8]_ and :ref:`Logistic_regression`.
In the plot above, data is generated according to a linear mechanism, which is
consistent with the :class:`LogisticRegression` model (the model is 'well specified'),
and the value of the regularization parameter `C` is tuned to be
appropriate (neither too strong nor too low). As a consequence, this model returns
accurate predictions from its `predict_proba` method.
In contrast to that, the other shown models return biased probabilities; with
different biases per model.

.. currentmodule:: sklearn.naive_bayes

:class:`GaussianNB` (Naive Bayes) tends to push probabilities to 0 or 1 (note the counts
in the histograms). This is mainly because it makes the assumption that
features are conditionally independent given the class, which is not the
case in this dataset which contains 2 redundant features.

.. currentmodule:: sklearn.ensemble

:class:`RandomForestClassifier` shows the opposite behavior: the histograms
show peaks at probabilities approximately 0.2 and 0.9, while probabilities
close to 0 or 1 are very rare. An explanation for this is given by
Niculescu-Mizil and Caruana [3]_: "Methods such as bagging and random
forests that average predictions from a base set of models can have
difficulty making predictions near 0 and 1 because variance in the
underlying base models will bias predictions that should be near zero or one
away from these values. Because predictions are restricted to the interval
[0,1], errors caused by variance tend to be one-sided near zero and one. For
example, if a model should predict p = 0 for a case, the only way bagging
can achieve this is if all bagged trees predict zero. If we add noise to the
trees that bagging is averaging over, this noise will cause some trees to
predict values larger than 0 for this case, thus moving the average
prediction of the bagged ensemble away from 0. We observe this effect most
strongly with random forests because the base-level trees trained with
random forests have relatively high variance due to feature subsetting." As
a result, the calibration curve shows a characteristic sigmoid shape, indicating that
the classifier could trust its "intuition" more and return probabilities closer
to 0 or 1 typically.

.. currentmodule:: sklearn.svm

:class:`LinearSVC` (SVC) shows an even more sigmoid curve than the random forest, which
is typical for maximum-margin methods (compare Niculescu-Mizil and Caruana [3]_), which
focus on difficult to classify samples that are close to the decision boundary (the
support vectors).

Calibrating a classifier
------------------------

.. currentmodule:: sklearn.calibration

Calibrating a classifier consists of fitting a regressor (called a
*calibrator*) that maps the output of the classifier (as given by
:term:`decision_function` or :term:`predict_proba`) to a calibrated probability
in [0, 1]. Denoting the output of the classifier for a given sample by :math:`f_i`,
the calibrator tries to predict the conditional event probability
:math:`P(y_i = 1 | f_i)`.

Ideally, the calibrator is fit on a dataset independent of the training data used to
fit the classifier in the first place.
This is because performance of the classifier on its training data would be
better than for novel data. Using the classifier output of training data
to fit the calibrator would thus result in a biased calibrator that maps to
probabilities closer to 0 and 1 than it should.

Usage
-----

The :class:`CalibratedClassifierCV` class is used to calibrate a classifier.

:class:`CalibratedClassifierCV` uses a cross-validation approach to ensure
unbiased data is always used to fit the calibrator. The data is split into k
`(train_set, test_set)` couples (as determined by `cv`). When `ensemble=True`
(default), the following procedure is repeated independently for each
cross-validation split:

1. a clone of `base_estimator` is trained on the train subset
2. the trained `base_estimator` makes predictions on the test subset
3. the predictions are used to fit a calibrator (either a sigmoid or isotonic
   regressor) (when the data is multiclass, a calibrator is fit for every class)

This results in an
ensemble of k `(classifier, calibrator)` couples where each calibrator maps
the output of its corresponding classifier into [0, 1]. Each couple is exposed
in the `calibrated_classifiers_` attribute, where each entry is a calibrated
classifier with a :term:`predict_proba` method that outputs calibrated
probabilities. The output of :term:`predict_proba` for the main
:class:`CalibratedClassifierCV` instance corresponds to the average of the
predicted probabilities of the `k` estimators in the `calibrated_classifiers_`
list. The output of :term:`predict` is the class that has the highest
probability.

It is important to choose `cv` carefully when using `ensemble=True`.
All classes should be present in both train and test subsets for every split.
When a class is absent in the train subset, the predicted probability for that
class will default to 0 for the `(classifier, calibrator)` couple of that split.
This skews the :term:`predict_proba` as it averages across all couples.
When a class is absent in the test subset, the calibrator for that class
(within the `(classifier, calibrator)` couple of that split) is
fit on data with no positive class. This results in ineffective calibration.

When `ensemble=False`, cross-validation is used to obtain 'unbiased'
predictions for all the data, via
:func:`~sklearn.model_selection.cross_val_predict`.
These unbiased predictions are then used to train the calibrator. The attribute
`calibrated_classifiers_` consists of only one `(classifier, calibrator)`
couple where the classifier is the `base_estimator` trained on all the data.
In this case the output of :term:`predict_proba` for
:class:`CalibratedClassifierCV` is the predicted probabilities obtained
from the single `(classifier, calibrator)` couple.

The main advantage of `ensemble=True` is to benefit from the traditional
ensembling effect (similar to :ref:`bagging`). The resulting ensemble should
both be well calibrated and slightly more accurate than with `ensemble=False`.
The main advantage of using `ensemble=False` is computational: it reduces the
overall fit time by training only a single base classifier and calibrator
pair, decreases the final model size and increases prediction speed.

Alternatively an already fitted classifier can be calibrated by using a
:class:`~sklearn.frozen.FrozenEstimator` as
``CalibratedClassifierCV(estimator=FrozenEstimator(estimator))``.
It is up to the user to make sure that the data used for fitting the classifier
is disjoint from the data used for fitting the regressor.
data used for fitting the regressor.

:class:`CalibratedClassifierCV` supports the use of two regression techniques
for calibration via the `method` parameter: `"sigmoid"` and `"isotonic"`.

.. _sigmoid_regressor:

Sigmoid
^^^^^^^

The sigmoid regressor, `method="sigmoid"` is based on Platt's logistic model [4]_:

.. math::
       p(y_i = 1 | f_i) = \frac{1}{1 + \exp(A f_i + B)} \,,

where :math:`y_i` is the true label of sample :math:`i` and :math:`f_i`
is the output of the un-calibrated classifier for sample :math:`i`. :math:`A`
and :math:`B` are real numbers to be determined when fitting the regressor via
maximum likelihood.

The sigmoid method assumes the :ref:`calibration curve <calibration_curve>`
can be corrected by applying a sigmoid function to the raw predictions. This
assumption has been empirically justified in the case of :ref:`svm` with
common kernel functions on various benchmark datasets in section 2.1 of Platt
1999 [4]_ but does not necessarily hold in general. Additionally, the
logistic model works best if the calibration error is symmetrical, meaning
the classifier output for each binary class is normally distributed with
the same variance [7]_. This can be a problem for highly imbalanced
classification problems, where outputs do not have equal variance.

In general this method is most effective for small sample sizes or when the
un-calibrated model is under-confident and has similar calibration errors for both
high and low outputs.

Isotonic
^^^^^^^^

The `method="isotonic"` fits a non-parametric isotonic regressor, which outputs
a step-wise non-decreasing function, see :mod:`sklearn.isotonic`. It minimizes:

.. math::
       \sum_{i=1}^{n} (y_i - \hat{f}_i)^2

subject to :math:`\hat{f}_i \geq \hat{f}_j` whenever
:math:`f_i \geq f_j`. :math:`y_i` is the true
label of sample :math:`i` and :math:`\hat{f}_i` is the output of the
calibrated classifier for sample :math:`i` (i.e., the calibrated probability).
This method is more general when compared to 'sigmoid' as the only restriction
is that the mapping function is monotonically increasing. It is thus more
powerful as it can correct any monotonic distortion of the un-calibrated model.
However, it is more prone to overfitting, especially on small datasets [6]_.

Overall, 'isotonic' will perform as well as or better than 'sigmoid' when
there is enough data (greater than ~ 1000 samples) to avoid overfitting [3]_.

.. note:: Impact on ranking metrics like AUC

    It is generally expected that calibration does not affect ranking metrics such as
    ROC-AUC. However, these metrics might differ after calibration when using
    `method="isotonic"` since isotonic regression introduces ties in the predicted
    probabilities. This can be seen as within the uncertainty of the model predictions.
    In case, you strictly want to keep the ranking and thus AUC scores, use
    `method="sigmoid"` which is a strictly monotonic transformation and thus keeps
    the ranking.

Multiclass support
^^^^^^^^^^^^^^^^^^

Both isotonic and sigmoid regressors only
support 1-dimensional data (e.g., binary classification output) but are
extended for multiclass classification if the `base_estimator` supports
multiclass predictions. For multiclass predictions,
:class:`CalibratedClassifierCV` calibrates for
each class separately in a :ref:`ovr_classification` fashion [5]_. When
predicting
probabilities, the calibrated probabilities for each class
are predicted separately. As those probabilities do not necessarily sum to
one, a postprocessing is performed to normalize them.

.. rubric:: Examples

* :ref:`sphx_glr_auto_examples_calibration_plot_calibration_curve.py`
* :ref:`sphx_glr_auto_examples_calibration_plot_calibration_multiclass.py`
* :ref:`sphx_glr_auto_examples_calibration_plot_calibration.py`
* :ref:`sphx_glr_auto_examples_calibration_plot_compare_calibration.py`

.. rubric:: References

.. [1] Allan H. Murphy (1973).
       :doi:`"A New Vector Partition of the Probability Score"
       <10.1175/1520-0450(1973)012%3C0595:ANVPOT%3E2.0.CO;2>`
       Journal of Applied Meteorology and Climatology

.. [2] `On the combination of forecast probabilities for
       consecutive precipitation periods.
       <https://journals.ametsoc.org/waf/article/5/4/640/40179>`_
       Wea. Forecasting, 5, 640–650., Wilks, D. S., 1990a

.. [3] `Predicting Good Probabilities with Supervised Learning
       <https://www.cs.cornell.edu/~alexn/papers/calibration.icml05.crc.rev3.pdf>`_,
       A. Niculescu-Mizil & R. Caruana, ICML 2005

.. [4] `Probabilistic Outputs for Support Vector Machines and Comparisons
       to Regularized Likelihood Methods.
       <https://www.cs.colorado.edu/~mozer/Teaching/syllabi/6622/papers/Platt1999.pdf>`_
       J. Platt, (1999)

.. [5] `Transforming Classifier Scores into Accurate Multiclass
       Probability Estimates.
       <https://dl.acm.org/doi/pdf/10.1145/775047.775151>`_
       B. Zadrozny & C. Elkan, (KDD 2002)

.. [6] `Predicting accurate probabilities with a ranking loss.
       <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4180410/>`_
       Menon AK, Jiang XJ, Vembu S, Elkan C, Ohno-Machado L.
       Proc Int Conf Mach Learn. 2012;2012:703-710

.. [7] `Beyond sigmoids: How to obtain well-calibrated probabilities from
       binary classifiers with beta calibration
       <https://projecteuclid.org/euclid.ejs/1513306867>`_
       Kull, M., Silva Filho, T. M., & Flach, P. (2017).

.. [8] Mario V. Wüthrich, Michael Merz (2023).
       :doi:`"Statistical Foundations of Actuarial Learning and its Applications"
       <10.1007/978-3-031-12409-9>`
       Springer Actuarial

calibration                           Probability calibration                             currentmodule   sklearn calibration   When performing classification you often want not only to predict the class label  but also obtain a probability of the respective label  This probability gives you some kind of confidence on the prediction  Some models can give you poor estimates of the class probabilities and some even do not support probability prediction  e g   some instances of  class   sklearn linear model SGDClassifier    The calibration module allows you to better calibrate the probabilities of a given model  or to add support for probability prediction   Well calibrated classifiers are probabilistic classifiers for which the output of the  term  predict proba  method can be directly interpreted as a confidence level  For instance  a well calibrated  binary  classifier should classify the samples such that among the samples to which it gave a  term  predict proba  value close to  say  0 8  approximately 80  actually belong to the positive class   Before we show how to re calibrate a classifier  we first need a way to detect how good a classifier is calibrated      note       Strictly proper scoring rules for probabilistic predictions like      func  sklearn metrics brier score loss  and      func  sklearn metrics log loss  assess calibration  reliability  and     discriminative power  resolution  of a model  as well as the randomness of the data      uncertainty  at the same time  This follows from the well known Brier score     decomposition of Murphy  1    As it is not clear which term dominates  the score is     of limited use for assessing calibration alone  unless one computes each term of     the decomposition   A lower Brier loss  for instance  does not necessarily     mean a better calibrated model  it could also mean a worse calibrated model with much     more discriminatory power  e g  using many more features       calibration curve   Calibration curves                     Calibration curves  also referred to as  reliability diagrams   Wilks 1995  2     compare how well the probabilistic predictions of a binary classifier are calibrated  It plots the frequency of the positive label  to be more precise  an estimation of the  conditional event probability   math  P Y 1  text predict proba     on the y axis against the predicted probability  term  predict proba  of a model on the x axis  The tricky part is to get values for the y axis  In scikit learn  this is accomplished by binning the predictions such that the x axis represents the average predicted probability in each bin  The y axis is then the  fraction of positives  given the predictions of that bin  i e  the proportion of samples whose class is the positive class  in each bin    The top calibration curve plot is created with  func  CalibrationDisplay from estimator   which uses  func  calibration curve  to calculate the per bin average predicted probabilities and fraction of positives   func  CalibrationDisplay from estimator  takes as input a fitted classifier  which is used to calculate the predicted probabilities  The classifier thus must have  term  predict proba  method  For the few classifiers that do not have a  term  predict proba  method  it is possible to use  class  CalibratedClassifierCV  to calibrate the classifier outputs to probabilities   The bottom histogram gives some insight into the behavior of each classifier by showing the number of samples in each predicted probability bin      figure      auto examples calibration images sphx glr plot compare calibration 001 png     target     auto examples calibration plot compare calibration html     align  center     currentmodule   sklearn linear model   class  LogisticRegression  is more likely to return well calibrated predictions by itself as it has a canonical link function for its loss  i e  the logit link for the  ref  log loss   In the unpenalized case  this leads to the so called   balance property    see  8   and  ref  Logistic regression   In the plot above  data is generated according to a linear mechanism  which is consistent with the  class  LogisticRegression  model  the model is  well specified    and the value of the regularization parameter  C  is tuned to be appropriate  neither too strong nor too low   As a consequence  this model returns accurate predictions from its  predict proba  method  In contrast to that  the other shown models return biased probabilities  with different biases per model      currentmodule   sklearn naive bayes   class  GaussianNB   Naive Bayes  tends to push probabilities to 0 or 1  note the counts in the histograms   This is mainly because it makes the assumption that features are conditionally independent given the class  which is not the case in this dataset which contains 2 redundant features      currentmodule   sklearn ensemble   class  RandomForestClassifier  shows the opposite behavior  the histograms show peaks at probabilities approximately 0 2 and 0 9  while probabilities close to 0 or 1 are very rare  An explanation for this is given by Niculescu Mizil and Caruana  3     Methods such as bagging and random forests that average predictions from a base set of models can have difficulty making predictions near 0 and 1 because variance in the underlying base models will bias predictions that should be near zero or one away from these values  Because predictions are restricted to the interval  0 1   errors caused by variance tend to be one sided near zero and one  For example  if a model should predict p   0 for a case  the only way bagging can achieve this is if all bagged trees predict zero  If we add noise to the trees that bagging is averaging over  this noise will cause some trees to predict values larger than 0 for this case  thus moving the average prediction of the bagged ensemble away from 0  We observe this effect most strongly with random forests because the base level trees trained with random forests have relatively high variance due to feature subsetting   As a result  the calibration curve shows a characteristic sigmoid shape  indicating that the classifier could trust its  intuition  more and return probabilities closer to 0 or 1 typically      currentmodule   sklearn svm   class  LinearSVC   SVC  shows an even more sigmoid curve than the random forest  which is typical for maximum margin methods  compare Niculescu Mizil and Caruana  3     which focus on difficult to classify samples that are close to the decision boundary  the support vectors    Calibrating a classifier                              currentmodule   sklearn calibration  Calibrating a classifier consists of fitting a regressor  called a  calibrator   that maps the output of the classifier  as given by  term  decision function  or  term  predict proba   to a calibrated probability in  0  1   Denoting the output of the classifier for a given sample by  math  f i   the calibrator tries to predict the conditional event probability  math  P y i   1   f i     Ideally  the calibrator is fit on a dataset independent of the training data used to fit the classifier in the first place  This is because performance of the classifier on its training data would be better than for novel data  Using the classifier output of training data to fit the calibrator would thus result in a biased calibrator that maps to probabilities closer to 0 and 1 than it should   Usage        The  class  CalibratedClassifierCV  class is used to calibrate a classifier    class  CalibratedClassifierCV  uses a cross validation approach to ensure unbiased data is always used to fit the calibrator  The data is split into k   train set  test set   couples  as determined by  cv    When  ensemble True   default   the following procedure is repeated independently for each cross validation split   1  a clone of  base estimator  is trained on the train subset 2  the trained  base estimator  makes predictions on the test subset 3  the predictions are used to fit a calibrator  either a sigmoid or isotonic    regressor   when the data is multiclass  a calibrator is fit for every class   This results in an ensemble of k   classifier  calibrator   couples where each calibrator maps the output of its corresponding classifier into  0  1   Each couple is exposed in the  calibrated classifiers   attribute  where each entry is a calibrated classifier with a  term  predict proba  method that outputs calibrated probabilities  The output of  term  predict proba  for the main  class  CalibratedClassifierCV  instance corresponds to the average of the predicted probabilities of the  k  estimators in the  calibrated classifiers   list  The output of  term  predict  is the class that has the highest probability   It is important to choose  cv  carefully when using  ensemble True   All classes should be present in both train and test subsets for every split  When a class is absent in the train subset  the predicted probability for that class will default to 0 for the   classifier  calibrator   couple of that split  This skews the  term  predict proba  as it averages across all couples  When a class is absent in the test subset  the calibrator for that class  within the   classifier  calibrator   couple of that split  is fit on data with no positive class  This results in ineffective calibration   When  ensemble False   cross validation is used to obtain  unbiased  predictions for all the data  via  func   sklearn model selection cross val predict   These unbiased predictions are then used to train the calibrator  The attribute  calibrated classifiers   consists of only one   classifier  calibrator   couple where the classifier is the  base estimator  trained on all the data  In this case the output of  term  predict proba  for  class  CalibratedClassifierCV  is the predicted probabilities obtained from the single   classifier  calibrator   couple   The main advantage of  ensemble True  is to benefit from the traditional ensembling effect  similar to  ref  bagging    The resulting ensemble should both be well calibrated and slightly more accurate than with  ensemble False   The main advantage of using  ensemble False  is computational  it reduces the overall fit time by training only a single base classifier and calibrator pair  decreases the final model size and increases prediction speed   Alternatively an already fitted classifier can be calibrated by using a  class   sklearn frozen FrozenEstimator  as   CalibratedClassifierCV estimator FrozenEstimator estimator      It is up to the user to make sure that the data used for fitting the classifier is disjoint from the data used for fitting the regressor  data used for fitting the regressor    class  CalibratedClassifierCV  supports the use of two regression techniques for calibration via the  method  parameter    sigmoid   and   isotonic         sigmoid regressor   Sigmoid          The sigmoid regressor   method  sigmoid   is based on Platt s logistic model  4        math          p y i   1   f i     frac 1  1    exp A f i   B        where  math  y i  is the true label of sample  math  i  and  math  f i  is the output of the un calibrated classifier for sample  math  i    math  A  and  math  B  are real numbers to be determined when fitting the regressor via maximum likelihood   The sigmoid method assumes the  ref  calibration curve  calibration curve   can be corrected by applying a sigmoid function to the raw predictions  This assumption has been empirically justified in the case of  ref  svm  with common kernel functions on various benchmark datasets in section 2 1 of Platt 1999  4   but does not necessarily hold in general  Additionally  the logistic model works best if the calibration error is symmetrical  meaning the classifier output for each binary class is normally distributed with the same variance  7    This can be a problem for highly imbalanced classification problems  where outputs do not have equal variance   In general this method is most effective for small sample sizes or when the un calibrated model is under confident and has similar calibration errors for both high and low outputs   Isotonic           The  method  isotonic   fits a non parametric isotonic regressor  which outputs a step wise non decreasing function  see  mod  sklearn isotonic   It minimizes      math           sum  i 1   n   y i    hat f  i  2  subject to  math   hat f  i  geq  hat f  j  whenever  math  f i  geq f j    math  y i  is the true label of sample  math  i  and  math   hat f  i  is the output of the calibrated classifier for sample  math  i   i e   the calibrated probability   This method is more general when compared to  sigmoid  as the only restriction is that the mapping function is monotonically increasing  It is thus more powerful as it can correct any monotonic distortion of the un calibrated model  However  it is more prone to overfitting  especially on small datasets  6     Overall   isotonic  will perform as well as or better than  sigmoid  when there is enough data  greater than   1000 samples  to avoid overfitting  3        note   Impact on ranking metrics like AUC      It is generally expected that calibration does not affect ranking metrics such as     ROC AUC  However  these metrics might differ after calibration when using      method  isotonic   since isotonic regression introduces ties in the predicted     probabilities  This can be seen as within the uncertainty of the model predictions      In case  you strictly want to keep the ranking and thus AUC scores  use      method  sigmoid   which is a strictly monotonic transformation and thus keeps     the ranking   Multiclass support                     Both isotonic and sigmoid regressors only support 1 dimensional data  e g   binary classification output  but are extended for multiclass classification if the  base estimator  supports multiclass predictions  For multiclass predictions   class  CalibratedClassifierCV  calibrates for each class separately in a  ref  ovr classification  fashion  5    When predicting probabilities  the calibrated probabilities for each class are predicted separately  As those probabilities do not necessarily sum to one  a postprocessing is performed to normalize them      rubric   Examples     ref  sphx glr auto examples calibration plot calibration curve py     ref  sphx glr auto examples calibration plot calibration multiclass py     ref  sphx glr auto examples calibration plot calibration py     ref  sphx glr auto examples calibration plot compare calibration py      rubric   References      1  Allan H  Murphy  1973           doi   A New Vector Partition of the Probability Score          10 1175 1520 0450 1973 012 3C0595 ANVPOT 3E2 0 CO 2          Journal of Applied Meteorology and Climatology      2   On the combination of forecast probabilities for        consecutive precipitation periods          https   journals ametsoc org waf article 5 4 640 40179           Wea  Forecasting  5  640 650   Wilks  D  S   1990a      3   Predicting Good Probabilities with Supervised Learning         https   www cs cornell edu  alexn papers calibration icml05 crc rev3 pdf            A  Niculescu Mizil   R  Caruana  ICML 2005       4   Probabilistic Outputs for Support Vector Machines and Comparisons        to Regularized Likelihood Methods          https   www cs colorado edu  mozer Teaching syllabi 6622 papers Platt1999 pdf           J  Platt   1999       5   Transforming Classifier Scores into Accurate Multiclass        Probability Estimates          https   dl acm org doi pdf 10 1145 775047 775151           B  Zadrozny   C  Elkan   KDD 2002       6   Predicting accurate probabilities with a ranking loss          https   www ncbi nlm nih gov pmc articles PMC4180410            Menon AK  Jiang XJ  Vembu S  Elkan C  Ohno Machado L         Proc Int Conf Mach Learn  2012 2012 703 710      7   Beyond sigmoids  How to obtain well calibrated probabilities from        binary classifiers with beta calibration         https   projecteuclid org euclid ejs 1513306867           Kull  M   Silva Filho  T  M     Flach  P   2017        8  Mario V  W thrich  Michael Merz  2023           doi   Statistical Foundations of Actuarial Learning and its Applications          10 1007 978 3 031 12409 9          Springer Actuarial