Repository navigation
Description
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
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 (
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_featuresofRandomForestClassifierdefaults tosqrt, which uses$\sqrt{n\_features}$ for classifiers. -
gammaofSVChas 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
-
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
glemaitre commentedon Apr 1, 2026
@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?
ogrisel commentedon Apr 2, 2026
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)orint(n ** 1/3))Whatsonyourmind commentedon Apr 3, 2026
glevv commentedon Apr 12, 2026
Numpy uses min(sturges rule, Friedman-Diaconisis estimator) for example. They have sqrt rule (wich is
int(n ** 1/2)) and rice rule (which isint(2 * n ** 1/3))ogrisel commentedon Apr 15, 2026
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
benjaminrbremer commentedon Apr 15, 2026
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:
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:
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:
riskandepsilon. I suggest hard-coding these at 0.1 for the following reasons:risk=0.1is 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 concernedIt 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.
benjaminrbremer commentedon Apr 15, 2026
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)
glevv commentedon Apr 15, 2026
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.
benjaminrbremer commentedon Apr 15, 2026
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.2for 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?
lorentzenchr commentedon Apr 16, 2026
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 follownumpy.histogram_bin_edgesand set it to 10. Additionally, all the other options ofnumpy.histogram_bin_edgeswould be nice.benjaminrbremer commentedon Apr 16, 2026
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:
Even the docs for
n_binsmention 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.
4 remaining items
ogrisel commentedon Apr 20, 2026
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 thestrategyargument 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 UXCalibrationDisplay's naive use can lead to very confusing results #30664).Is it correct that for
strategy="uniform"thenn_bins = np.ceil(len(y_true) ** (1/2))("square-root rule") is better? If so, thenn_bins="auto"could be use "cubic-root" whenstrategy == "quantile"andn_bins="square-root"whenstrategy == "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 forstrategy="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 useceilinstead ofintto 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:
benjaminrbremer commentedon Apr 20, 2026
@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.
lorentzenchr commentedon Apr 20, 2026
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.
ogrisel commentedon Apr 24, 2026
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_binsandstrategy.benjaminrbremer commentedon Apr 25, 2026
@ogrisel To confirm, that is "rice" as defined by Numpy -
n_bins = 2*n^(1/3)?Reasoning (for documentation purposes):
Is this something that @ZeyuSun wants to tackle? If not, I am more than willing to take a shot at a PR.
glevv commentedon Apr 25, 2026
@benjaminrbremer
You can check the implementation here and a bit more information here
ZeyuSun commentedon Apr 26, 2026
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.
lorentzenchr commentedon Apr 30, 2026
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.