Skip to content

FEA Add strategy isotonic to calibration curve - #23824

Open
lorentzenchr wants to merge 7 commits into
scikit-learn:mainfrom
lorentzenchr:calibration_isotonic
Open

lorentzenchr wants to merge 7 commits into
scikit-learn:mainfrom
lorentzenchr:calibration_isotonic

Conversation

@lorentzenchr

Copy link
Copy Markdown
Member

Reference Issues/PRs

Fixes #23132.

What does this implement/fix? Explain your changes.

This PR adds strategy="isotonic" to calibration_curve and CalibrationDisplay.

Any other comments?

Reliability diagrams with (PAV algorithm) isotonic regression is the CORP approach of (https://doi.org/10.1073/pnas.2016191118).

@lorentzenchr

Copy link
Copy Markdown
Member Author

Results

From the example of CalibrationDisplay.
image

Details
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibrationDisplay


X, y = make_classification(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, random_state=0)
clf = LogisticRegression(random_state=0)
clf.fit(X_train, y_train)
LogisticRegression(random_state=0)
fig, ax = plt.subplots()
CalibrationDisplay.from_estimator(clf, X_test, y_test, ax=ax)
CalibrationDisplay.from_estimator(clf, X_test, y_test, ax=ax, strategy="isotonic")
ax.get_legend().get_texts()[1].set_text('LogisticRegression uniform')
ax.get_legend().get_texts()[2].set_text('LogisticRegression isotonic')

From https://scikit-learn.org/stable/auto_examples/calibration/plot_compare_calibration.html#calibration-curves.
image

Details
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
from sklearn.calibration import CalibrationDisplay
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import LinearSVC


X, y = make_classification(
    n_samples=100_000, n_features=20, n_informative=2, n_redundant=2, random_state=42
)

train_samples = 100  # Samples used for training the models
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    shuffle=False,
    test_size=100_000 - train_samples,
)


class NaivelyCalibratedLinearSVC(LinearSVC):
    """LinearSVC with `predict_proba` method that naively scales
    `decision_function` output."""

    def fit(self, X, y):
        super().fit(X, y)
        df = self.decision_function(X)
        self.df_min_ = df.min()
        self.df_max_ = df.max()

    def predict_proba(self, X):
        """Min-max scale output of `decision_function` to [0,1]."""
        df = self.decision_function(X)
        calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_)
        proba_pos_class = np.clip(calibrated_df, 0, 1)
        proba_neg_class = 1 - proba_pos_class
        proba = np.c_[proba_neg_class, proba_pos_class]
        return proba


# Create classifiers
lr = LogisticRegression()
gnb = GaussianNB()
svc = NaivelyCalibratedLinearSVC(C=1.0)
rfc = RandomForestClassifier()

clf_list = [
    (lr, "Logistic"),
    (gnb, "Naive Bayes"),
    (svc, "SVC"),
    (rfc, "Random forest"),
]


fig = plt.figure(figsize=(10, 10))
gs = GridSpec(4, 2)
colors = plt.cm.get_cmap("Dark2")

ax_calibration_curve = fig.add_subplot(gs[:2, :2])
calibration_displays = {}
for i, (clf, name) in enumerate(clf_list):
    clf.fit(X_train, y_train)
    display = CalibrationDisplay.from_estimator(
        clf,
        X_test,
        y_test,
        n_bins=10,
        strategy="isotonic",
        name=name,
        ax=ax_calibration_curve,
        color=colors(i),
    )
    calibration_displays[name] = display

ax_calibration_curve.grid()
ax_calibration_curve.set_title("Calibration plots")
plt.show()

Comment thread sklearn/calibration.py Resolved
@lorentzenchr

Copy link
Copy Markdown
Member Author

@ogrisel @glemaitre You might be interested.

@thomasjpfan thomasjpfan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you noted in #23132 (comment), the CORP paper does not meet our inclusion criterion. According to google scholar it has been cited 13 times.

If we can not include the method based on inclusion, then an alternative is to accept a callable here so it is simple to implement CORP:

def calibration_curve(...):
    ...
    elif callable(strategy):
        # n_bins to be flexible
        return strategy(y_prob, y_true, n_bins)

and strategy is:

def strategy(y_prob, y_true, n_bins):
    iso = IsotonicRegression(y_min=0, y_max=1).fit(y_prob, y_true)
    prob_true = iso.y_thresholds_
    prob_pred = iso.X_thresholds_
    return prob_true, prob_pred

Then we can update a calibration example to showcase passing a callable and using the CORP strategy.

@lorentzenchr

Copy link
Copy Markdown
Member Author

@thomasjpfan The point is that isotonic regression is already included in scikit-learn, so why not use it? In particular, CalibratedClassifierCV is using it and is related to the same topic:
Another way of putting it: Plot CalibratedClassifierCV(clf, method="isotonic", cv="prefit").fit(X, y).predict(X) vs clf.prefit(X).
I see the paper more as a theoretical foundation as to why isotonic regression is good to use in reliability diagrams.

@lorentzenchr

lorentzenchr commented Sep 5, 2022 •

Copy link
Copy Markdown
Member Author

To give it more citation counts:

@antoinebaker antoinebaker left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for the PR @lorentzenchr !

This looks good to me and I'm in favor of adding this option, both for visual display (for a statistically accurate calibration curve, but at the risk of being too crowded if $n >> 1$) and for the implementation of calibration metrics.

Comment thread sklearn/calibration.py
Use isotonic regression to select bins automatically. This corresponds to
the CORP approach of [2]_. `n_bins` is ignored.

.. versionadded:: 1.2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To update.

Comment thread doc/whats_new/v1.2.rst
Comment on lines +112 to +114
- |Enhancement| :func:`calibration_curve` and :class:`CalibrationDisplay` have the new
option `strategy="isotonic"`.
:pr:`23824` by :user:`Christian Lorentzen <lorentzenchr>`.

@antoinebaker antoinebaker Apr 29, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To format as an entry upcoming_changes/sklearn.calibration/23865.enhancement.rst

Comment thread sklearn/calibration.py
Comment on lines 1028 to 1029

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"Invalid entry to 'strategy' input. Strategy "
"must be 'quantile', 'uniform' or 'isotonic'."

Comment thread sklearn/calibration.py
Comment on lines +1372 to +1373
- `'isotonic'`: Use isotonic regression to select bins automatically. This
corresponds to the CORP approach of [1]_. `n_bins` is ignored.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we also need a .. versionadded directive here.

Comment thread sklearn/calibration.py
Use isotonic regression to select bins automatically. This corresponds to
the CORP approach of [2]_. `n_bins` is ignored.

.. versionadded:: 1.2

Returns
-------
prob_true : ndarray of shape (n_bins,) or smaller

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ndarray of shape (n_samples,) with the "isotonic" option.

Idem for prob_pred.

@lorentzenchr

Copy link
Copy Markdown
Member Author

@antoinebaker Thanks for your review. I will only invest in this PR if core contributors agree on inclusion.

@antoinebaker

Copy link
Copy Markdown
Member

Do we have your go @ogrisel ?

@ogrisel ogrisel added this to Labs May 18, 2026
@ogrisel ogrisel moved this to In progress in Labs May 18, 2026
@ogrisel
ogrisel self-requested a review May 18, 2026 12:50
@ogrisel

ogrisel commented May 18, 2026 •

Copy link
Copy Markdown
Member

The paper nowadays has 129 citations (https://scholar.google.com/scholar?hl=en&as_sdt=0%2C31&q=Stable+reliability+diagrams+for+probabilistic+classifiers&btnG=), so while not exactly meeting our expectations, it's getting much closer.

I will try to find the time to give this PR another look.

Meanwhile, I would be curious to see how strategy="quantile" with cube-root adaptive setting for n_bins (and optionally bias correction, see also this paper) fairs against CORP when using it to estimate the reliability term of the Brier decomposition from a finite sample on various choices of sample size, miscalibrated/misspecified classifiers and data generating process combinations. I would like to see understand better if some method can be blind / more sensitive to calibration problems in various settings.

@ogrisel

ogrisel commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

I conducted some experiments to highlight a problem with the isotonic / binless strategy of the CORP methodology.

It assumes that the true monotonic curve (e.g. as estimated from an infinite calibration set) is monotonic. But this is not always the case. Here is an example of a misspecified model (linear model fitted on data sampled from a non-linear data generating process). In this case the binned estimation of the calibration curve (with the cube root) are less biased (compared to the CORP/isotonic estimator). This is particularly visible for medium to large calibration sets.

https://gist.github.com/ogrisel/705f2c6d77b55fd10f774489e69a5a5a

Note that mis-specified linear models are not the only way to get models with non-monotonic calibration curves. Figure 6 of https://arxiv.org/pdf/2210.16315 also show some significant non-monotonicity for a large neural network model (although, this figure is in a multiclass setting so max-class calibration curves have a different meaning than in the binary case).

EDIT: I mistakenly deleted the previous version of the gist but updated the comment with a link to a new version of the notebook.

@lorentzenchr

Copy link
Copy Markdown
Member Author

@ogrisel In your notebook, $P(Y|m(X))$ is unkown (at least I don’t know or I don’t get it). So your claim about monotonicity does not hold (but sure, there are examples where it is not monotone).

2 remarks:

  • Often, calibration is done on a smaller (than train) dataset. Asymptotic results are then of limited value.
  • What I like about the isotonic regression:
    • a long horizontal line in a reliability diagram is a strong sign for high uncertainty.
    • no free parameter

@antoinebaker

antoinebaker commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

In this notebook we investigate the different estimates for the calibration error:
https://gist.github.com/antoinebaker/c49a5ccb761d96aa98bf05ff2f9c62fc

For a given setting (known true calibration curve and distribution of the predicted probability) we compare the estimated calibration error on data vs the true calibration error, and report the MSE of the estimate.

It seems that the binning strategy with a debiasing term (debiased_CAL) and n_bins=(n_samples)**(1/3) is the best overall, and the CORP estimate (MCB isotonic) the worse.

NOTE: the Plotly plots are not rendered in the gist viewer, but if you download the notebook it should be okay. For example the overconfident, stats.beta(a=3, b=2) case looks like this:
newplot

EDIT: the MSE on the y label of this plot is the squared difference between the true Brier calibration term (as defined in the notebook) and the various estimates labeled in the legend.

@ogrisel

ogrisel commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

@ogrisel In your notebook, P ( Y | m ( X ) ) is unkown (at least I don’t know or I don’t get it)

Yes but we know the data generating process and we know that increasing both calibration set size n_cal and number of bins at a rate proportional to n_cal ** (1/3) converge to it. Hence, when n_cal=int(5e7), the binned calibration curve is visually very close to the true calibration curve. And indeed plotting the calibration curve of the DGP mean function (which we know by construction in this notebook) recovers a line very close to the diagonal for n_cal ** (1/3).

EDIT: I added a third column with the "true" reliability diagram with the 50 000 000 calibration points.

Often, calibration is done on a smaller (than train) dataset. Asymptotic results are then of limited value.

I agree. This is why I also plot the curves for smaller calibrations set sizes. On medium-sized calibration sets (n_cal == 5e3), the non-monotonicity problem of the calibration curve is already visible when using the bin-based estimator:

image

For the isotonic estimator, this results in a suspiciously horizontal segment, but I would argue that it's harder for readers to deduct from that plots that the true curve is probably decreasing in that horizontal segment. The binned based histogram is more intuitive to read in that respect.

a long horizontal line in a reliability diagram is a strong sign for high uncertainty.

A long horizontal line in the isotonic estimator could be caused be uncertainty (and will disappear if we have access to a larger calibration sets) or by non-monoticity of the true curve: in that case the isotonic estimator will keep a long horizontal segment with infinite number of calibration points as shown in the notebook.

no free parameter

If we use the cube-root rule by default in CalibrationDisplay, the n_bins parameter is set automatically in practice.

@ogrisel

ogrisel commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

I also found a new natural way to trigger non-monotonic calibration curves: overfitted classifier trees with a very large number of leaves. I updated the notebook to add such a case.

One could argue that the calibration issues of such models are also better represented by binned calibration curves (compared to CORP diagrams) for medium-sized calibration sets, but this is more debatable.

@lorentzenchr

Copy link
Copy Markdown
Member Author

I find both ways valuable, CORPS and bins. I could also cite literature that argue against using bins, but let's not get into that.

The key question for scikit-learn is: Isotonic regression is good enough for CalibratedClassifierCV, why should it not be good enough for calibration_curve?

@ogrisel

ogrisel commented Jun 9, 2026

Copy link
Copy Markdown
Member

The key question for scikit-learn is: Isotonic regression is good enough for CalibratedClassifierCV, why should it not be good enough for calibration_curve?

One argument could be the following: while isotonic calibration is an asymptotically optimal way to reduce the calibration error of a classifier, it is not an asymptotically optimal way to estimate the calibration curve and calibration error. The CORP estimate can only see the fraction of the miscalibration that is fixable by a monotonic transform. It therefore underestimate the calibration error whenever the true calibration curve is not monotonic (which can happen in practice, both with deep tree based models that overfit and for linear models that underfit due to lack of sufficient feature engineering for instance). This is clearly visible on the study notebook linked by @antoinebaker above. Unfortunately the plotly plots do not render on github. Here are screenshots of the estimation error of all the compared estimators of the calibration error in a case where the true calibration curve is non monotonic:

image image

One can clearly see that the isotonic-based estimators of the calibration error are only upper bounds and similarly biased in this case.

For a fixed choice of sub-optimal classifier, the fact that a fraction its calibration error cannot be fixed by post-hoc recalibration does not mean that this fraction of the calibration error does not exist in the first place.

@lorentzenchr

Copy link
Copy Markdown
Member Author

Shall I than finally close?

@antoinebaker

Copy link
Copy Markdown
Member

I think for the visual application (here for calibration_curve and CalibrationDisplay) it doesn't hurt to have an additional strategy="isotonic", it could be a useful option for visualizing the calibration curve on a smallish calibration dataset. We just need to mention in the docstring that the curve will be increasing by construction.

WDYT @ogrisel ?

@antoinebaker antoinebaker moved this from In progress to Todo in Labs Jul 29, 2026
@antoinebaker antoinebaker moved this from Todo to PR Stalled in Labs Jul 29, 2026

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add PAV algorithm for calibration_curve/reliability diagrams

5 participants