Skip to content

UX CalibrationDisplay's naive use can lead to very confusing results #30664

Open

Description

@ogrisel

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":

Image

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=15 by default but also introduce min_samples_per_bins=50 to 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 implement CalibratedDisplayCV.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).

Activity

  1. added
    Needs Triage
    on Jan 17, 2025
  2. changed the title [-]UX `CalibrationDisplay` naive use can lead to very confusing results[/-] [+]UX `CalibrationDisplay`'s naive use can lead to very confusing results[/+] on Jan 17, 2025
  3. ogrisel commented on Jan 20, 2025

    @ogrisel
    MemberAuthor

    We might also want to change the default from strategy="uniform" to strategy="quantile" which leads to more informative curves in my opinion, in particular on classification problems with class imbalance.

  4. added and removed
    Needs Triage
    on Jan 20, 2025
  5. ogrisel commented on Jan 20, 2025

    @ogrisel
    MemberAuthor

    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.

  6. GaelVaroquaux commented on Jan 20, 2025

    @GaelVaroquaux
    Member

    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)

    from scipy import stats
    distrib = stats.binom(n=n_in_bin, p=average_in_bin)
    bottom_ci = distrib.isf(.25)
    top_ci = distrib.isf(.75)
  7. ogrisel commented on Jan 20, 2025

    @ogrisel
    MemberAuthor

    Shouldn't it rather be?

    from scipy import stats
    distrib = stats.binom(n=n_in_bin, p=average_in_bin)
    bottom_ci = distrib.ppf(.25) / n_in_bin
    top_ci = distrib.ppf(.75) / n_in_bin

    But I am afraid it yields collapsed CIs for n_in_bins == 1 or 2. It starts to yield intuitively useful uncertainty estimates only for n_in_bins >= 3:

    >>> from scipy import stats
    ... y_obs = [0]
    ... n = len(y_obs)
    ... distrib = stats.binom(n=n, p=sum(y_obs)/n)
    ... distrib.ppf(.25) / n, distrib.ppf(.75) / n
    (np.float64(0.0), np.float64(0.0))
    >>> y_obs = [1]
    ... n = len(y_obs)
    ... distrib = stats.binom(n=n, p=sum(y_obs)/n)
    ... distrib.ppf(.25) / n, distrib.ppf(.75) / n
    (np.float64(1.0), np.float64(1.0))
    >>> y_obs = [0, 1]
    ... n = len(y_obs)
    ... distrib = stats.binom(n=n, p=sum(y_obs)/n)
    ... distrib.ppf(.25) / n, distrib.ppf(.75) / n
    (np.float64(0.0), np.float64(0.5))
    >>> y_obs = [0, 1, 0]
    ... n = len(y_obs)
    ... distrib = stats.binom(n=n, p=sum(y_obs)/n)
    ... distrib.ppf(.25) / n, distrib.ppf(.75) / n
    (np.float64(0.0), np.float64(0.6666666666666666))
    >>> y_obs = [0, 1, 1]
    ... n = len(y_obs)
    ... distrib = stats.binom(n=n, p=sum(y_obs)/n)
    ... distrib.ppf(.25) / n, distrib.ppf(.75) / n
    (np.float64(0.3333333333333333), np.float64(1.0))
  8. ogrisel commented on Jan 20, 2025

    @ogrisel
    MemberAuthor

    I found that scipy.stats.binomtest implements various methods to estimate CI intervals for binomial trials:

    >>> for y_obs in [[0], [1], [0, 1], [0, 0, 1], [0, 1, 1]]:
    ...     print(f"{y_obs=}")
    ...     for method in ["exact", "wilson", "wilsoncc"]:
    ...         print(method.rjust(10), binomtest(sum(y_obs), len(y_obs)).proportion_ci(confidence_level=0.5, method=method))
    ...     print()
    y_obs=[0]
         exact ConfidenceInterval(low=0.0, high=0.75)
        wilson ConfidenceInterval(low=0.0, high=np.float64(0.3126847440825833))
      wilsoncc ConfidenceInterval(low=0.0, high=np.float64(0.7795911050456467))
    
    y_obs=[1]
         exact ConfidenceInterval(low=0.25, high=1.0)
        wilson ConfidenceInterval(low=np.float64(0.6873152559174167), high=1.0)
      wilsoncc ConfidenceInterval(low=np.float64(0.22040889495435334), high=1.0)
    
    y_obs=[0, 1]
         exact ConfidenceInterval(low=0.13397459621556132, high=0.8660254037844387)
        wilson ConfidenceInterval(low=np.float64(0.2847588845819623), high=np.float64(0.7152411154180377))
      wilsoncc ConfidenceInterval(low=np.float64(0.10425347838136545), high=np.float64(0.8957465216186346))
    
    y_obs=[0, 0, 1]
         exact ConfidenceInterval(low=0.0914397035839695, high=0.6736481776669304)
        wilson ConfidenceInterval(low=np.float64(0.18281725015861316), high=np.float64(0.5277418231406089))
      wilsoncc ConfidenceInterval(low=np.float64(0.06837944703876814), high=np.float64(0.681436779552594))
    
    y_obs=[0, 1, 1]
         exact ConfidenceInterval(low=0.32635182233306964, high=0.9085602964160305)
        wilson ConfidenceInterval(low=np.float64(0.47225817685939114), high=np.float64(0.8171827498413868))
      wilsoncc ConfidenceInterval(low=np.float64(0.3185632204474061), high=np.float64(0.9316205529612319))

    The "wilsoncc" method seems to be the most conservative for small sample sizes followed by the "exact" method.

  9. ogrisel commented on Jan 21, 2025

    @ogrisel
    MemberAuthor

    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:

    • it's the default choice of scipy,
    • in addition to being a frequentist confidence interval with coverage guarantees, it can also be interpreted as a Bayesian credible interval with a non-informative prior.

    All methods are cheap enough to compute for various values of sum(y_obs) and len(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).

  10. ogrisel commented on Jan 21, 2025

    @ogrisel
    MemberAuthor

    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

  11. GaelVaroquaux commented on Jan 21, 2025

    @GaelVaroquaux
    Member
  12. ogrisel commented on Jan 21, 2025

    @ogrisel
    MemberAuthor

    I would not use them for this, but to illustrate the uncertainty.

    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.

  13. ogrisel commented on Jan 23, 2025

    @ogrisel
    MemberAuthor

    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

    Image

    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

  14. moved this to Discussion in Front-end UI/UXon Jan 23, 2025
  15. ogrisel commented on Jan 23, 2025

    @ogrisel
    MemberAuthor

    The width of the Clopper-Pearson uncertainty interval might make it possible to trigger the warning about "too large n_bins / too few observations / recommend use of strategy="quantile" instead of strategy="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.

  16. GaelVaroquaux commented on Jan 23, 2025

    @GaelVaroquaux
    Member

    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?

  17. ogrisel commented on Jan 23, 2025

    @ogrisel
    MemberAuthor

    The parametric (Clopper-Pearson and Wilson) CI seem surprising large to me on the left of the graph: they go very high up.

    Note that Windsurf IDE decided to set confidence_level=0.90 as the default value for the uncertainty band. Using confidence_level=0.50 can 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.90 as the default as most people would expect this level by default I think.

    Why is that? Are those bins almost empty?

    I believe so, but I will check.

    EDIT: yes this was the main reason.

  18. ogrisel commented on Jan 24, 2025

    @ogrisel
    MemberAuthor

    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:

    Image

    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:

    Image

    I think using min_samples_per_bins=30 or 50and n_bins=10 or 15 by default would be a great usability improvement. The choice of the binning strategy is less impacting in that case. We could probably even stick to strategy="uniform" by default if we really wanted.

  19. ogrisel commented on Jan 24, 2025

    @ogrisel
    MemberAuthor

    I also reran the benchmark notebook with the latest version of the prototype code:

    Image

    Image

    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 < 1000 and n_bins >> 20 is 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.

  20. ogrisel commented on Jan 24, 2025

    @ogrisel
    MemberAuthor

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

  21. ogrisel commented on Jan 24, 2025

    @ogrisel
    MemberAuthor

    Would love to hear about @lorentzenchr's take as well ;)

  22. glemaitre commented on Jan 24, 2025

    @glemaitre
    Member

    Ping @lucyleeow and @glemaitre since this is in the scope of the CZI grant.

    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?

  23. GaelVaroquaux commented on Jan 24, 2025

    @GaelVaroquaux
    Member

    With the updated code, the parametric CI look right to me. I would go with them. Thanks!

  24. ogrisel commented on Jan 24, 2025

    @ogrisel
    MemberAuthor

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

    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_estimator for 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.

    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?

    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.

  25. lorentzenchr commented on Jan 24, 2025

    @lorentzenchr
    Member

    For me, it is important 2 distinguish between 2 separate subjects:

    1. Improve UX of CalibrationDisplay for bad choices of number of bins. I would first advocate for a
    2. Uncertainties/Confidence intervals:
  26. ogrisel commented on Jan 26, 2025

    @ogrisel
    MemberAuthor

    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 conservatives means making the bands smaller => you say sooner that your predictions are outside the band (or the diagonal is outside) => judge model as not well calibrated.

    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.

  27. lorentzenchr commented on Jan 28, 2025

    @lorentzenchr
    Member

    Being conservative (at estimating uncertainty) means wider bands

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions