Repository navigation
FEA Add strategy isotonic to calibration curve - #23824
lorentzenchr wants to merge 7 commits into
Conversation
ResultsFrom the example of Detailsimport 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. Detailsimport 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() |
aa0e0d6 to
34f77b7
Compare
|
@ogrisel @glemaitre You might be interested. |
thomasjpfan
left a comment
There was a problem hiding this comment.
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_predThen we can update a calibration example to showcase passing a callable and using the CORP strategy.
|
@thomasjpfan The point is that isotonic regression is already included in scikit-learn, so why not use it? In particular, |
|
To give it more citation counts:
|
antoinebaker
left a comment
There was a problem hiding this comment.
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
| Use isotonic regression to select bins automatically. This corresponds to | ||
| the CORP approach of [2]_. `n_bins` is ignored. | ||
|
|
||
| .. versionadded:: 1.2 |
| - |Enhancement| :func:`calibration_curve` and :class:`CalibrationDisplay` have the new | ||
| option `strategy="isotonic"`. | ||
| :pr:`23824` by :user:`Christian Lorentzen <lorentzenchr>`. |
There was a problem hiding this comment.
To format as an entry upcoming_changes/sklearn.calibration/23865.enhancement.rst
There was a problem hiding this comment.
| "Invalid entry to 'strategy' input. Strategy " | |
| "must be 'quantile', 'uniform' or 'isotonic'." |
| - `'isotonic'`: Use isotonic regression to select bins automatically. This | ||
| corresponds to the CORP approach of [1]_. `n_bins` is ignored. |
There was a problem hiding this comment.
I guess we also need a .. versionadded directive here.
| 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 |
There was a problem hiding this comment.
ndarray of shape (n_samples,) with the "isotonic" option.
Idem for prob_pred.
|
@antoinebaker Thanks for your review. I will only invest in this PR if core contributors agree on inclusion. |
|
Do we have your go @ogrisel ? |
|
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 |
|
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. 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. |
|
@ogrisel In your notebook, 2 remarks:
|
|
In this notebook we investigate the different estimates for the calibration error: 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 NOTE: the Plotly plots are not rendered in the gist viewer, but if you download the notebook it should be okay. For example the 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. |
Yes but we know the data generating process and we know that increasing both calibration set size EDIT: I added a third column with the "true" reliability diagram with the 50 000 000 calibration points.
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:
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 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.
If we use the cube-root rule by default in |
|
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. |
|
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 |
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:
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. |
|
Shall I than finally close? |
|
I think for the visual application (here for WDYT @ogrisel ? |






Reference Issues/PRs
Fixes #23132.
What does this implement/fix? Explain your changes.
This PR adds
strategy="isotonic"tocalibration_curveandCalibrationDisplay.Any other comments?
Reliability diagrams with (PAV algorithm) isotonic regression is the CORP approach of (https://doi.org/10.1073/pnas.2016191118).