Repository navigation
Description
The naive use of CalibrationDisplay parameter silently leads to degenerate, noisy results when some bins have with a few data points.
For instance, look at the variability obtained by displaying for calibration curve of a fitted model evaluated on various resampling with 50 data points in total using the uniform strategy when using n_bins=10 and the default strategy="uniform":
Details
# %%
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibrationDisplay
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=10_000, n_features=200, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# %%
clf = LogisticRegression(C=10).fit(X_train, y_train)
# %%
fig, ax = plt.subplots()
for seed in range(5):
# resample the test set
rng = np.random.RandomState(seed)
indices = rng.choice(X_test.shape[0], size=50, replace=True)
X_test_sample = X_test[indices]
y_test_sample = y_test[indices]
CalibrationDisplay.from_estimator(clf, X_test_sample, y_test_sample, n_bins=10, ax=ax, label=None)This problem can easily happen with the default strategy="uniform" if the test data is not large enough. I think this class should warn the user whenever it generates bins with lower than 10 data points per bin.
A typical user will only get one of the curves above and not suspect that it's just noise without manually plotting the others by random resampling. Note that I chose a minimal test set to make the problem catastrophic above, but it can happen with larger sample sizes, in particular with the uniform strategy, in particular on imbalanced datasets.
Updated recommendations
EDIT: based on the discussion below, here are my recommendations to address this issue:
- display a confidence interval by default to reflect our uncertainty on the calibration curve estimate (using the Clopper-Pearson analytical CI from scipy looks both reliable and cheap to compute)
- we set
n_bins=15by default but also introducemin_samples_per_bins=50to automatically merge the smallest pair of neighboring bins until that constraint it met. - we would not warn, unless the resulting merging leads to less than 3 bins for instance,
- we could keep
strategy="uniform"if we like, but I wouldn't mind switching to"quantile"either.
Original description and suggestion
In such cases, this warning could recommend to:
- use
strategy="quantile"(which is a bit less likely to generate near empty, unstable bins); - decrease the number of bins;
- increase the number of data points in the test set.
Beyond warnings, we could also offer the user extra-options to assess the stability of the calibration curve.
There are two cases:
- for a fixed trained estimator, we could estimate the uncertainty in the estimation of its calibration curve induced by the finite size of the evaluation set (irrespective of whether the training procedure is stable or not) by resampling the test set (with replacement):
fig, ax = plt.subplots()
for seed in range(10):
rng = np.random.RandomState(seed)
indices = rng.choice(X_test.shape[0], size=X_test.shape[0], replace=True)
X_test_resampled = X_test[indices]
y_test_resampled = y_test[indices]
CalibrationDisplay.from_estimator(
clf,
X_test_resampled,
y_test_resampled,
strategy="quantile",
n_bins=10,
ax=ax,
label=None,
)We could optionally offer an option to aggregate those curves by displaying a shaded region derived from the vertical quantiles (e.g. 0.05-0.95) of the interpolated y-curve values at a fine grid of x values. See also the related issue on sampling uncertainties in performance curves: #25856.
- to assess the uncertainty of the calibration of a full fitting procedure (uncertainty induced by both the finite training set size, the training algorithm itself (impacted by the choice of hyperparams) and the finite evaluation set size), we could also offer to plot calibration curves from CV results (see ENH implement
CalibrationCurveDisplay.from_cv_results#21211 to implementCalibratedDisplayCV.from_cv_results).
On the opposite, if all the bins have more than 1000 data points and n_bins <= 10, we could suggest the user to increase n_bins to 10 or more to get a finer estimation of the calibration curve. Maybe this recommendation is better to be set in a docstring rather than a warning.
I think we could start simple by opening a first PR to issue warnings for the nearly empty bin problem (with an option to silence them).
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDiscussion

Activity
[-]UX `CalibrationDisplay` naive use can lead to very confusing results[/-][+]UX `CalibrationDisplay`'s naive use can lead to very confusing results[/+]ogrisel commentedon Jan 20, 2025
We might also want to change the default from
strategy="uniform"tostrategy="quantile"which leads to more informative curves in my opinion, in particular on classification problems with class imbalance.ogrisel commentedon Jan 20, 2025
Another potential fix would be to find a cheap way to estimate the uncertainty in the curve induced by the finite evaluation set size (bootstraping comes to mind). This is related to #25856 that suggests ways to do that for ROC / PR curves.
GaelVaroquaux commentedon Jan 20, 2025
A simple solution for confidence intervals (imperfect but still useful IMHO) would be to use binomial confidence intervals.
For instance, computing the upper and lower quartile (which is a fairly optimistic CI)
ogrisel commentedon Jan 20, 2025
Shouldn't it rather be?
But I am afraid it yields collapsed CIs for
n_in_bins == 1or2. It starts to yield intuitively useful uncertainty estimates only forn_in_bins >= 3:ogrisel commentedon Jan 20, 2025
I found that
scipy.stats.binomtestimplements various methods to estimate CI intervals for binomial trials:The
"wilsoncc"method seems to be the most conservative for small sample sizes followed by the"exact"method.ogrisel commentedon Jan 21, 2025
The
"exact"method is actually https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Clopper%E2%80%93Pearson_interval (I checked that it matches the values returned by the code snippet on Wikipedia).I like this method the most because:
All methods are cheap enough to compute for various values of
sum(y_obs)andlen(y_obs): I measured below 2 ms per CI on my machine, so even for a plot with 30 bins, adding uncertainty estimates to this plot should be cheap enough (and much cheaper than boostrapping).ogrisel commentedon Jan 21, 2025
Note that per-bins confidence intervals can be misleading when combining the different intervals to reject the null hypothesis that the model is well calibrated (at least one interval does not overlap with the diagonal). But adjusting the confidence level for multiple testing naively (e.g. Bonferroni) is not exact because there are dependencies between the values in each bin used to construct the chart and the resulting conclusion would be too conservative.
One way to deal with this would be to bootstrap the whole calibration curve construction process to get a distribution of calibration curves and then extra vertical quantiles of that distribution, probably with the help of interpolation on a grid of x-axis values. However, I suspect that is more costly than computing the multiple Clopper-Pearson intervals and might lead to qualitatively similar looking results.
EDIT: quantitatively => qualitatively
GaelVaroquaux commentedon Jan 21, 2025
ogrisel commentedon Jan 21, 2025
I agree, but we cannot prevent plot readers to, perhaps implicitly, doing this mentally when reading the plots (honestly, I know I will do that myself). I guess, this can be addressed by being explicit enough on how the intervals are constructed in the docstring and guiding the users better on how to read those plots in our updated examples.
ogrisel commentedon Jan 23, 2025
I went ahead and implemented a prototype (actually, I guided Windsurf IDE to code a prototype using high-level objectives to experiment with modern code assistants) to assess whether bin-wise Clopper-Pearson CIs and bootstrap-based CI recover similar uncertainty for calibration curves:
https://github.com/ogrisel/calcurve/blob/main/examples/calibration_analysis.ipynb
The linked project and notebook have more details/experiments.
Both methods mostly agree except on small bins with all negative labels or all positive labels in which case the bootstrap uncertainty width is collapsed to zero. Therefore, I think Clopper-Pearson is a better choice. The dependencies between bins does not seem to make the width of Clopper-Pearson overly conservative compared to bootstrap.
Wilson CC is very similar to Clopper-Pearson.
Both analytical methods are faster than bootstraping when the number of bins is kept to a reasonable number (<100):
https://github.com/ogrisel/calcurve/blob/main/examples/uncertainty_methods_benchmark.ipynb
ogrisel commentedon Jan 23, 2025
The width of the
Clopper-Pearsonuncertainty interval might make it possible to trigger the warning about "too large n_bins / too few observations / recommend use ofstrategy="quantile"instead ofstrategy="uniform"" in a more principled way. As soon as the 50% CI is wider than 0.5, the curve is pretty much useless and adjusting the settings as suggested is required.GaelVaroquaux commentedon Jan 23, 2025
Thanks for doing this!
The parametric (Clopper-Pearson and Wilson) CI seem surprising large to me on the left of the graph: they go very high up. Why is that? Are those bins almost empty?
ogrisel commentedon Jan 23, 2025
Note that Windsurf IDE decided to set
confidence_level=0.90as the default value for the uncertainty band. Usingconfidence_level=0.50can probably avoid such dramatic spikes.EDIT: the spikes went away if I trim empty bins (by merging them with their least populated neighbor). So I think we can keep
confidence_level=0.90as the default as most people would expect this level by default I think.I believe so, but I will check.
EDIT: yes this was the main reason.
ogrisel commentedon Jan 24, 2025
I refactored the code significantly to simplify it (and also reuse scipy's implementation of the analytical CIs instead of using a custom reimplementation from scratch by the LLM).
Note for later: relying too much on LLM automation without reviewing every change can lead to sloppy code. I am not sure if I am that productive when instructing the Cascade agent of Windsurf IDE to write the code instead of writing what I want myself and only leverage boilerplate code completion.
The results are mostly the same, but I also implemented a strategy to automatically iteratively merge empty bins with their neighbors by default. Here is the result:
The spikes are now gone.
Note that the bootstrap CI can still be overconfident if a given bin has all 0 or all 1 values while the analytical CIs do not have this problem.
We can push the iterative merging forward to a minimum of 50 data points per bin (arbitrary value) and it would make the calibration curve quite robust to bad choices of n_bins on low sample size evaluation sets:
I think using
min_samples_per_bins=30or50andn_bins=10or15by default would be a great usability improvement. The choice of the binning strategy is less impacting in that case. We could probably even stick tostrategy="uniform"by default if we really wanted.ogrisel commentedon Jan 24, 2025
I also reran the benchmark notebook with the latest version of the prototype code:
So on small datasets with very large n_bins, bootstrapping could be more efficient, but otherwise the analytical formula is always best. As
n_samples < 1000andn_bins >> 20is not a useful setting, I think the Clopper Pearson method (or similarly the Wilson CC method) are more favorable than the bootstrap method given all of the above.ogrisel commentedon Jan 24, 2025
@GaelVaroquaux I updated the descriptions with a possible implementation plan. Please let me know if you are aligned with my conclusions.
Ping @lucyleeow and @glemaitre since this is in the scope of the CZI grant.
ogrisel commentedon Jan 24, 2025
Would love to hear about @lorentzenchr's take as well ;)
glemaitre commentedon Jan 24, 2025
Also pinging @DeaMariaLeon
I have an additional question regarding the API: here, if I understand, we will display some confidence interval using a single model. If I extrapolate to other display, we could have similar wishes (not that we should do it straightway). For instance, a naive thought would be to implement some bootstrapping and have a confidence interval in a ROC or PR curve to display such interval (note here that bootstrapping might not be the thing to do).
My question is more strictly about API: do we foresee a common API to activate by default some sort of confidence interval across the display?
GaelVaroquaux commentedon Jan 24, 2025
With the updated code, the parametric CI look right to me. I would go with them. Thanks!
ogrisel commentedon Jan 24, 2025
Summarizing the calibration curves of a group of related models from CV results is another matter. What I propose here is only about
from_predictions/from_estimatorfor a single model. And we could (should) provide an option to disable the uncertainty area if users want but I would display it by default.Computing summary confidence intervals for groups of related models is methodologically trickier. I am not sure if we want to do it or not. One option would be to display all the curves + uncertainties of each models in each CV folds and let the visual cortex of the human brain do the CV uncertainty summarization by themselves in the case of calibration curves. At least that would be a reasonable default. We could always explore uncertainty summarization of CV results later (e.g. aggregate over CV folds + bootstrap with test point of a given folds), but I would rather not anticipate the API implications too much.
lorentzenchr commentedon Jan 24, 2025
For me, it is important 2 distinguish between 2 separate subjects:
CalibrationDisplayfor bad choices of number of bins. I would first advocate for aogrisel commentedon Jan 26, 2025
Thanks for the feedback, I will empirically compare all your suggestions in the POC repo notebooks to have a clearer via at what should be implemented in scikit-learn and what would work as foolproof default settings.
Being conservative (at estimating uncertainty) means wider bands, meaning one cannot tell whether the model is miscalibrated or not (if the band overlaps with the diagonal everywhere) and more evaluation data would be required. For mean predicted values around 0.05 in #30664 (comment), the bootstrap method can lead to a collapsed band because of all the observations in those bins with just a few data points are negative. The bootstrap method is probably misleading compared to the analytical methods that yield a non-zero width for the uncertainty band in those bins.
lorentzenchr commentedon Jan 28, 2025
No, the exact opposite. It's a band around the estimation of$E[Y|m(X)]$ , not around $m(X)$ . A wider band means that it is more likely that my model is within the band. This is interpreted as "my model is well (auto-)calibrated". Therefore, smaller bands are more conservative in this case. Because that is unintuitive at first, I mentioned it above.