Skip to content

Add 'auto' option to n_bins in calibration_curve #33658

Closed

Description

@ZeyuSun

Problem

Currently, the n_bins parameter in sklearn.calibration.calibration_curve defaults to 5. This is often suboptimal for datasets of varying sizes, especially for large datasets. Users must manually tune this parameter to balance the trade-off between bias (too few bins) and variance (too many bins).

Example: for a dataset of size $n = 100,000$, the optimal number of bins is on the order of 100, far exceeding the default 5. Using the default 5 creates a calibration curve that's overly crude.

Describe your proposed solution

Specifically, research in the paper "Optimal Recalibration via Uniform-Mass Binning" provides a theoretical proof that the optimal number of bins ($B$) for recalibration via uniform-mass binning scales with the cubic root of the number of samples ($n$). (Conflict of interest: I'm an author of the paper)

The proposed implementation would be:

if n_bins == 'auto':
    n_bins = int(len(y_true) ** (1/3))

Benefits include:

  • Ease of Use: Tuning free. This is also the practice for many other sklearn implementation of algorithms, e.g.,
    • max_features of RandomForestClassifier defaults to sqrt, which uses $\sqrt{n\_features}$ for classifiers.
    • gamma of SVC has options 'scale' and 'auto'.
  • Statistical Robustness: defaulting to a theoretically optimal value improves the reliability of calibration metrics and plots across a wider range of $n$.

Describe alternatives you've considered, if relevant

Maybe 'cubic-root' or 'optimal' will be more descriptive than 'auto'?

Additional context

Here's a rough description of why $\sqrt{n}$ is the optimal bin number (under some quite general assumptions):

  • Notations: Let $Z$ be the random variable of the predicted probability to be calibrated, and $h^\star$ be the optimal calibration function $h^\star(z) := \text{E}[Y|Z=z]$.
  • Bound of bias: First, each bins has about $n/B$ samples, which contributes to $B/n$ factor in the calibration risk bound due to Hoeffding's inequality.
  • Bound of variance: Then, we note the sharpness risk $\text{E}[\text{Var}(h^\star(Z)) | h(Z))]$ is the average conditional variance of $h^\star(Z)$ in each bin. Since the variance is smaller than the squared range, and the range of $h^\star(Z)$ within each bin is bounded by $O(1/B)$, we have the average conditional variance is bounded by O(1/B^2).
  • Bound of MSE: Lastly, minimizing the sum of the two bounds $O(1/B^2 + B/n)$ yields $B \asymp n^{1/3}$.

Activity

  1. glemaitre commented on Apr 1, 2026

    @glemaitre
    Member

    @ZeyuSun I took some time to look a bit at the literature and I'm sure that you know better about it than me :)

    I stumbled upon the following paper https://arxiv.org/pdf/2405.15709 (that also cite yours) where they defined the optimal number of bins for both approach quantile and uniform case.

    I would happily take advantage of your knowledge to understand what are the difference in terms of assumptions between the both approaches and how it relates to real use case. Would you mind to shade some light on the subject?

  2. removed
    Needs Triage
    on Apr 1, 2026
  3. ogrisel commented on Apr 2, 2026

    @ogrisel
    Member

    I recently tried with the Sturges rule in the section named "Custom code to compute reliability curves for mean and quantile regressors." of this notebook https://github.com/ogrisel/notebooks/blob/master/poly_reg_array_api_vs_tabicl.ipynb, and it works quite well in my experience.

    EDIT: I make no claim that the Sturges rule (int(log2(n) + 1) is theoretically grounded for calibration/reliability curves. It's probably better to implement one of the recommendations from the literature instead (int(n ** 1/2) or int(n ** 1/3))

  4. Whatsonyourmind commented on Apr 3, 2026

    @Whatsonyourmind
  5. glevv commented on Apr 12, 2026

    @glevv
    Contributor

    Numpy uses min(sturges rule, Friedman-Diaconisis estimator) for example. They have sqrt rule (wich is int(n ** 1/2)) and rice rule (which is int(2 * n ** 1/3))

  6. ogrisel commented on Apr 15, 2026

    @ogrisel
    Member

    Another related paper:

    Calibrating the Calibration Tester: Optimal Binning and Minimax Calibration Testing for Continuous Predictive Models, 2026
    Alon Kipnis

    https://openreview.net/pdf?id=dy7XNC3W0g

  7. benjaminrbremer commented on Apr 15, 2026

    @benjaminrbremer

    It seems that taking the cube root of the number of samples (henceforth cubic method) is robust, as seen in Sun et al. (NeurIPS 2023) and Futami and Fujisawa (NeurIPS 2024). I would like to extend ZeyuSun's proposed solution by adding a floor. In both papers, it appears that the method starts working around 4-5 bins. Here is an updated code snippet:

    if n_bins == 'auto':
        n_bins = max(5, int(len(y_true) ** (1/3)))    # Also, a typo fix to cube root, which is what is mentioned in the paper
    

    I am also intrigued by the new paper. Both papers given above are trying to determine how miscalibrated the model is, using an optimal number of bins to give the best possible estimate of ECE. The new paper determines if there is enough data for that ECE measurement to be statistically powerful enough to detect miscalibration at a given threshold. Based on that, I have an idea:

    ...    # Assume scipy.stats and warnings imported
    if n_bins == 'auto':
        z = stats.norm.ppf(1 - risk / 2)
        max_bins_kipnis = int(np.floor((n**2 * epsilon**4) / (8 * z**2)))    # Equation given in Kipnis (2026)
        n_bins = max(5, int(len(y_true) ** (1/3)))
        if n_bins > max_bins_kipnis:
            min_detectable = (8 * z**2 * n_bins / n**2) ** 0.25
            warnings.warn(
                f"The optimal bin count ({n_bins}) exceeds the Kipnis "
                f"ceiling ({max_bins_kipnis}) for epsilon={epsilon}. The "
                f"calibration curve is computed at the theoretically "
                f"optimal resolution, but with n={len(y_true} samples the results "
                f"may not be statistically reliable for detecting "
                f"miscalibration below {min_detectable:.3f}. Consider "
                f"collecting more data.",
                UserWarning,
            )
    ...
    

    This uses the new paper to warn the user when they might not have enough data for their calibration results to be statistically significant.

    Additional Considerations:

    • The Kipnis Ceiling is a slightly less tested method than the cubic method (which exists in two peer-reviewed papers from 2+ years ago). I considered the idea of implementing it on its own (i.e., instead of "auto", you could choose "kipnis" or "cubic"), but combined with the fact that it is very new, and also measures something slightly different, it seems like it makes sense to use it as a sanity check for the cubic method, as opposed to a standalone method.
    • The Kipnis Ceiling depends on two parameters: risk and epsilon. I suggest hard-coding these at 0.1 for the following reasons:
      • There is no peer-reviewed research I found that specifies what epsilon should be set to
      • risk=0.1 is roughly analagous to 10% significance, which is a common rule of thumb for some fields (though, for others, it's 5%). However Kipnis' risk parameter applies to Type I and Type II error, which kind of throws this out the window as far as peer-reviewed research is concerned
      • So, 0.1 is a conservative, round number. Because it is only being used to warn the user as a ceiling, it is okay if it is not 100% optimal. And, it is better to not clog up the API with two extra parameters that don't really change much, and don't have good peer-reviewed defaults. It would just add more complication for the user

    It appears as if nobody is actively working on implementing a solution. I'm more than willing to open a PR, along the lines of the code snippet above (so long as @ZeyuSun is okay with that). I am also open to further discussion about what the best way forward might be.

  8. benjaminrbremer commented on Apr 15, 2026

    @benjaminrbremer

    Numpy uses min(sturges rule, Friedman-Diaconisis estimator) for example. They have sqrt rule (wich is int(n ** 1/2)) and rice rule (which is int(2 * n ** 1/3))

    These methods are great for histograms, as they're meant to estimate the shape of a probability distribution. A calibration curve is a 1D regression problem (how close are predicted probabilities to actual outcomes). The NumPy estimators don't account for the tension between having too few bins and too many bins, but the cubic method does (as it's derived from wanting to minimize the error). Hence, I didn't include them in my comment above.

    Edit: I think a better way of saying it is the NumPy methods are optimizing for density, whereas this function needs a method that minimizes error in a calibration context (which the cubic method does)

  9. glevv commented on Apr 15, 2026

    @glevv
    Contributor

    I'm all for replacing arbitrary number (5) with something more robust, but I think I have a important (IMO) question here:
    As I understand sklearn.calibration.calibration_curve is just a diagnostic tool, it is not a recalibration method. It could be used to calculate binned ECE, but primarily it is used to plot calibration plot. So trying to apply the logic of recalibration (minimizing the ECE or else) to it could lead to a strange user experience.
    What calibration curve should do is to be representative, easy to understand and easy to do model debugging. For example, a lot of research papers when plotting calibration curves usually just use 10 bins - easy to understand (deciles), easy to understand if model is under or overestimating probabilities and easy to plot.
    On the other hand, if I'm trying to estimate true calibration error (TCE) through binned ECE, I would love to have the least biased estimator, and in that case 10 bins would be a non-optimal solution. I think we need to answer this question first: what is the purpose of this function - to plot visualizations or to estimate metrics?

    Because, if this is a plotting tool, then cubic root rule could lead to hundreds or even thousands of bins on some datasets with large N, which is not user friendly, if we are talking about probabilities that are bound to [0, 1]. I'm sure nobody needs that much in their visualization.

    P.S. I referenced numpy, becase of 2 points: if scikit-learn will "diverge" from numpy there should be a good documentation how 'auto' works, why and how it is different from numpy, because there will be questions for sure; and secondly, I think there still will be a problem of sparse/dense regions in probability ditributions and these rules (FD and Sturges) tries to take this data variability into account, while rules that rely only on number of samples do not.

  10. benjaminrbremer commented on Apr 15, 2026

    @benjaminrbremer

    I agree with you, as far as a large number of bins for a huge dataset being cumbersome. However, as Futami and Fujisawa state, the binning bias term dominates the total bias when using a suboptimal bin count, scaling to O(1/B)=O(1/5)=0.2 for 5 bins. So the idea (far as I can tell) is that, using only 5 bins for a large dataset, the graph could be off by up to 20%. It doesn't make sense to unilaterally increase the default, as then there will be too many bins to generate meaningful information for smaller datasets.

    From my point of view, if there is a robust way to automatically use the optimal number of bins to provide the most accurate metric, it's worth using. It won't increase execution time, as the algorithm seems to be O(nlogn). It will result in slightly more raw data output, but will be significantly more accurate.

    From the original post, it sounds like this number is already getting tuned by hand anyways. Why not add it into the function, so those more naive to the math don't have to worry about it?

  11. lorentzenchr commented on Apr 16, 2026

    @lorentzenchr
    Member

    I agree in large parts with what @glevv wrote.
    Let us focus on the diagnostic calibration plot / reliability diagram and not on calculating ECE which scikit-learn does not provide.

    As a user, I would prefer a better default than n_bins=5. To not have an endless discussion, I recommend to follow numpy.histogram_bin_edges and set it to 10. Additionally, all the other options of numpy.histogram_bin_edges would be nice.

  12. benjaminrbremer commented on Apr 16, 2026

    @benjaminrbremer

    I will push back one more time for sake of discussion and growing my own understanding:

    The data returned from this function enables an ECE calculation, but is not an ECE calculation in and of itself. Moving to an 'auto' selection for n_bins does not recalibrate a model or minimize ECE - it simply provides the most accurate data for one to do that (or simply generate a plot).

    Yes, it would be nice to have a consistent structure of output - you always see the same number of bins. However, using a fixed number of bins introduces room for inaccurate calculations:

    • Too few bins: mean for predicted probability and fraction of positives in each bin are computed over too coarse an interval
    • Too many bins: there are too few samples in each bin to be meaningful, leading to volatile data

    Even the docs for n_bins mention that a higher number should be used for large datasets. Why not add an easy 'auto' option?

    As for the NumPy methods, they are designed to solve a different problem (density estimation for histogram visualization). I understand wanting consistency with NumPy, but in this case, I think there's a strong argument against including those methods.

    In short, the cube root method described in Sun et al. and Futami and Fujisawa has theoretical backing for being the most accurate. Adding a ceiling according to the method described in Kipnis makes the method more robust. Maintaining a floor of 5 also ensures the cube root method doesn't fall apart for extremely small datasets.

    If the consensus still falls toward what @glevv and @lorentzenchr have said, I will yield. I just think it's worth noting that the goal would be improving the accuracy of the resulting data (whether it is used for an ECE calculation, or given to one of the plotting methods mentioned in the docs). Switching the default to 10, while being consistent with NumPy, does not meet that goal. Including the n_bins estimations that NumPy uses doesn't fulfill that goal either.

  13. 4 remaining items

  14. ogrisel commented on Apr 20, 2026

    @ogrisel
    Member

    Thanks all for taking part in this discussion. I am very aligned with the recommendations of the summary @ZeyuSun and I appreciate the point in "2. Usefulness of diagnostic tools depends on its accuracy" in particular.

    Remaining questions:

    • Am I right to say that the n_bins = int(len(y_true) ** (1/3)) ("cubic-root rule") is only mathematically grounded for quantile-based bins? If so, we should switch the strategy argument from a default of "uniform" to "quantile". This is a change that I also wanted to make in the past by the way (see the discussion in UX CalibrationDisplay's naive use can lead to very confusing results #30664).

    • Is it correct that for strategy="uniform" then n_bins = np.ceil(len(y_true) ** (1/2)) ("square-root rule") is better? If so, then n_bins="auto" could be use "cubic-root" when strategy == "quantile" and n_bins="square-root" when strategy == "uniform".

    My current opinion

    • +1 for at least implementing n_bins="cubic_root" as an option (even if we don't make it the default right away).

    • +1 for making it the default (along with changing the other default to strategy="quantile") while implementing the usual future warning cycle.

    • +0 for also implementing n_bins="square_root" if it's optimal for strategy="uniform".

    • Ideally, we would also want to provide an easy way to plot uncertainty bounds (e.g. using bootstrapping or something else as discussed in UX CalibrationDisplay's naive use can lead to very confusing results #30664) to convey the lack of calibration data, but this can happen in an independent PR.

    floor vs ceil

    • I think I am fine to not use the max(5, ...) lower bounding if we use ceil instead of int to deal with the small calibration set case. As soon as you have 65 data-points or more, you would get 5+ bins with the ceil-variant of the cubic-root rule.

    • when considering small (yet probably quite common) calibration set sizes:

    Image
    • and zooming out to large calibration set sizes:
    Image
  15. benjaminrbremer commented on Apr 20, 2026

    @benjaminrbremer

    @ogrisel Unless I am mistaken, the Futami and Fujisawa paper proves that the cubic root method is optimal for both the uniform and quantile methods.

  16. lorentzenchr commented on Apr 20, 2026

    @lorentzenchr
    Member

    Please, let us not reinvent the wheel and let us start by adding (some of) the options of numpy.histogram_bin_edges. Note that "rice" is the cubic root rule.

    After making them available, we can set up our minds for a better default.

  17. ogrisel commented on Apr 24, 2026

    @ogrisel
    Member

    Alright let's implement the "rice" rule ("cubic root") first then. Then we will open follow-up with dedicated discussions for the default value of n_bins and strategy.

  18. benjaminrbremer commented on Apr 25, 2026

    @benjaminrbremer

    @ogrisel To confirm, that is "rice" as defined by Numpy - n_bins = 2*n^(1/3)?

    Reasoning (for documentation purposes):

    • Consistent with Numpy
    • Asymptotically the ideal as given in Sun et al. (NeurIPS 2023) and Futami & Fujisawa (NeurIPS 2024)

    Is this something that @ZeyuSun wants to tackle? If not, I am more than willing to take a shot at a PR.

  19. glevv commented on Apr 25, 2026

    @glevv
    Contributor

    @benjaminrbremer
    You can check the implementation here and a bit more information here

  20. ZeyuSun commented on Apr 26, 2026

    @ZeyuSun
    ContributorAuthor

    I am onboard with starting with the cubic root rule and then revisiting the default strategy.

    I'm excited to open a PR for this! Thanks to everyone for the insightful discussion.

  21. moved this from Todo to In progress in Labson Apr 26, 2026
  22. removed
    Needs Decision
    on Apr 27, 2026
  23. lorentzenchr commented on Apr 30, 2026

    @lorentzenchr
    Member

    You might find my comment #18268 (comment) interesting. https://doi.org/10.1073/pnas.2016191118 already investigated optimal binning, states the asymptotic optimal number of bins and MSE of the estimate of the recalibrated predictions.

  24. moved this from In progress to Done in Labson Jul 29, 2026
  25. closed this as completedby moving to Done in Labson Jul 31, 2026
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

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions