Skip to content

FEA add calibration_error metric with L2 norm and neg_l2_calibration_error scorer - #34261

Open
samronsin wants to merge 7 commits into
scikit-learn:mainfrom
samronsin:brier-calibration-error
Open

samronsin wants to merge 7 commits into
scikit-learn:mainfrom
samronsin:brier-calibration-error

Conversation

@samronsin

@samronsin samronsin commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

Based on #11096 with reduced scope as agreed.

What does this implement/fix? Explain your changes.

Adds sklearn.metrics.calibration_error for binary probabilistic predictions with the L2 norm and the corresponding neg_l2_calibration_error scorer.

Why: scikit-learn has calibration_curve for visual inspection but no scalar metric that quantifies the distance to a perfectly calibrated classifier, usable directly in model selection (cross_val_score/GridSearchCV via the scorer). The metric uses uniform-mass (weighted-quantile) binning consistent with calibration_curve(strategy="quantile"), with the number of bins set to ceil(cbrt(n_samples)) following the analysis of uniform-mass binning in Sun et al. (2023, arXiv:2305.10886). Supports sample_weight, pos_label, and the array API.

Areas that deserve careful review:

  • The fixed ceil(cbrt(n)) bin-count rule is a deliberate design choice (no n_bins/strategy parameter). A consequence is that integer sample_weight is not equivalent to repeating samples (bin count depends on the number of distinct weighted samples, not total weight); the common test exemption METRICS_WITH_SAMPLE_WEIGHT_NOT_EQUIVALENT_TO_REPETITION in test_common.py makes this explicit.
  • Bin assignment uses searchsorted(bins[1:-1], y_proba) (left-inclusive), matching calibration_curve; ties at a weighted-quantile edge collapse into the lower bin by design.
  • squared=True is exposed on the metric without a dedicated squared scorer.

AI usage disclosure

I used AI assistance for:

  • Code generation (review fixes: input validation, error paths, array API device handling)
  • Test/benchmark generation (error-path and invariance tests)
  • Research and understanding (multi-angle code review of the implementation)

@samronsin
samronsin force-pushed the brier-calibration-error branch 2 times, most recently from 025ca82 to a503045 Compare June 12, 2026 09:56
@lorentzenchr

Copy link
Copy Markdown
Member

I would wait for #33856.

@antoinebaker

antoinebaker commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Thanks a lot @samronsin !

I was thinking of the following refactoring to ease testing or if we later change our mind on the signature of brier_calibration_error:

  1. make a private _weighted_calibration_curve which is essentially the same as calibration_curve (same arguments and options) but supports weighting / array api and returns bin_weights in addition to prob_true, prob_pred
  2. we can then easily check that this private give the same results as calibration_curve for all strategy / n_bins
  3. we can also test the repeated/weighted equivalence for integer sample_weights in _weighted_calibration_curve with an integer n_bins
  4. brier_calibration_error is just then mostly a call to it + computing the calibration error

Indeed the n_bins = n**(1/3) rule won't make the brier calibration error compatible with the repeated/weighted equivalence for integer weights we would like to enforce. We always have this caveat in sklearn: when a parameter involves n_samples it breaks the equivalence as n_repeated = sample_weight.sum() != n_weighted. Sometimes we use sample_weight.sum() as an effective number of samples. It is then okay for integer weights but very brittle for scaled weights, for instance when sample_weight.sum() is small.

@ZeyuSun have you considered weighted brier score in your research ? Is there a optimal number of bins in the weighted case ?

@lorentzenchr do you know any literature on optimal binning for the weighted case (for regressogram or histogram) ?

If adapting the optimal number of bins in the weighted case is unknown, I'm fine with the current solution: we just skip it for brier_calibration_error. With the refactoring mentioned above, we can still check that _weighted_calibration_curve properly supports sample weight.

cc @ogrisel

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Jun 19, 2026
@samronsin

Copy link
Copy Markdown
Contributor Author

I have been wanting to do a _weighted_calibration_curve-like refactor (and eventually use it in calibration_curve but that's for another PR I guess) for a while, so I'm glad we're on the same page @antoinebaker !

@antoinebaker

antoinebaker commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

The linting CI failure may go away if you merge main, see #34331.

@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Jun 19, 2026
@samronsin
samronsin marked this pull request as ready for review June 19, 2026 17:43
@antoinebaker

Copy link
Copy Markdown
Member

@GaelVaroquaux doesn't like the name brier_calibration_error, he would prefer squared_calibration_error if I remember correctly ?

@lorentzenchr

Copy link
Copy Markdown
Member

How about using it for regressors? Squared calibration error would be required to work for both, classification and regression as there is no other name left for regressors.

@antoinebaker

antoinebaker commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Yep , that is a bit annoying. As we don't want the regressor score (taking y_pred) and binary classifier score (taking y_prob) to share the same name and function, we need to find distinct names.

The original suggestion brier_calibration_error was a naming convention {loss}_calibration_score. An alternative could be {task}_calibration_score, like binary_calibration_score, multiclass_calibration_score, regression_calibration_score, quantile_regression_calibration_score. Sorry that's a bit ugly but I'm not very inspired, if you have suggestions I'm all ears :)

@antoinebaker

Copy link
Copy Markdown
Member

I have a crazy idea but it could work :)

Why not name it calibration_error ? More precisely:

  • we implement for each case a calibration error score function with a precise name, for instance here brier_calibration_score
  • we also implement a generic calibration_error(y_true, y_pred), which would dispatch on the type of y_pred (binary or multiclass y_prob, regressor y_pred)
  • in the doc of calibration_error we can give the precise formula and refer to all the alternative names / definitions in the literature (Expected calibration error, Adaptive calibration error, Static calibration error, Miscalibration, Calibration component of the Brier score decomposition, ...)

WDYT @ogrisel @GaelVaroquaux @samronsin @lorentzenchr ?

@samronsin

Copy link
Copy Markdown
Contributor Author

Love the idea @antoinebaker, going full circle !

My only concern is mixing up units / scales, although tbf all probabilistic calibration errors are unit-less. Still, by construction the scale might vary quite significantly between squared loss and say ECE.

@samronsin

Copy link
Copy Markdown
Contributor Author

Regarding regressions, calibration seems much less relevant there than for classifications, where we need to convert the discrete outcomes to frequencies in order to compare with the continuous output of predictors.

@GaelVaroquaux

Copy link
Copy Markdown
Member

In terms of naming, I still feel that we are moving away from the names classically used in machine learning (and in existing implementations such as Pytorch). We shouldn't do that.

This PR is for the l2 version. What's the planned strategy for the l1 version (the most popular calibration error)?

@antoinebaker

antoinebaker commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

For reference, in pytorch it seems to be named CalibrationError:
https://lightning.ai/docs/torchmetrics/stable/classification/calibration_error.html
with dedicated {Binary, MultiClass}CalibrationError depending on the inputs.

They also have a norm (l1, l2 or max) argument. Would you be happy @GaelVaroquaux with calibration_error and the norm argument ? We'll be quite close to pytorch api then. Actually, this was the original proposal by @samronsin :)

For the "Brier" calibration error, this is l2**2, so we could:

  • implement a norm=l2_squared argument (even if it's no longer a norm...)
  • not implement it, when discussing the brier score decomposition in tutorials not forgot to square it to give the calibration component

For other tasks (eg quantile regression), we could use a dedicated naming.

@GaelVaroquaux

GaelVaroquaux commented Jun 29, 2026 via email

Copy link
Copy Markdown
Member

@lorentzenchr

lorentzenchr commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

They also have a norm (l1, l2 or max) argument. Would you be happy @GaelVaroquaux with calibration_error and the norm argument ? We'll be quite close to pytorch api then. Actually, this was the original proposal by @samronsin :)
That is the proposal that resonates best with me, as it feels close to the vocabulary used in machine learning.

What is important to me is that we don't block a name for (mean) regression. There are 2 options:

  1. Same function can handle classification and regression (hard to achieve, we usually don't do that, but I would like it)
  2. Have 2 different functions, one for classification, one for regression.

In the past, we went with the 1st option, e.g., brier_score_loss and mean_squared_error.

@samronsin

Copy link
Copy Markdown
Contributor Author

What is important to me is that we don't block a name for (mean) regression.

When we eventually get to the equivalent of calibration curves for regressions, I'm not sure we would want to call them "calibration curves", instead of e.g. something referring to "conditional bias".

Besides, current calibration_curve is already a bit specific to classifications (because of pos_label), and I retro-fitting it to accommodate regressions would make the signature a little funky. If we want to avoid that, new vocabulary would already be required here, and then it would be more consistent to adapt that vocabulary to the dependent metrics.

@ogrisel

ogrisel commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

We need to agree both on the function name (possibly with a norm kwarg to select the variant) and the string scoring names. In practice, people will use the string names, possibly to compute several values together, e.g. with a call such as:

cv_results = cross_validate(classifier, X, y, scoring=["neg_brier_score", "neg_l2_calibration_error"])

For string names I am fine with any of:

  • "neg_l2_squared_calibration_error"
  • "neg_squared_calibration_error"
  • "neg_brier_calibration_error"

"neg_l2_calibration_error" could work as well but is a bit misleading because we do not plan to take the square root to compute the actual l2 norm.

I am also fine adding "neg_l1_calibration_error" (either as part of this PR or later) to implement the variant based on the averaged absolute differences instead of the averaged squared differences.

I also agree that we will probably want to later add support for regressor. Maybe it will be possible to evolve our scorer API to have a scorer object that accept both classifiers and regressors, in which case we could reuse the same name. If not, then we will have to introduce a new name for the calibration term of the MSE decomposition of regressors (conditional mean estimators in particular). Maybe we could use "neg_(l2_squared,squared,l2)_reliability_error" in the context of regressors to workaround the conflicting names.

EDIT: I originally forgot the ugly "neg_" prefixes... I'd like to get rid of them, but this is another PR.

@samronsin

Copy link
Copy Markdown
Contributor Author

Thank you for your input @ogrisel @lorentzenchr @GaelVaroquaux @antoinebaker !

How acceptable would the API:

calibration_error(
    y_true,
    y_proba,
    *,
    norm="l1",  # also valid: "l2", "max" 
    squared=False,  # True only valid for norm="l2"
)

be considered ?

Scorers would be:

  • neg_l1_calibration_error
  • neg_l2_squared_calibration_error / neg_l2_calibration_error (why not add both actually ? they are redundant as an objective but make the API translate more consistently + almost costless + we could later add neg_l2_squared_debiased_calibration_error)
  • neg_max_calibration_error.

Then, conditional mean analysis for regressions eventually adopt reliability_{curve,error} vocabulary, which makes the distinction between continuous and discrete labels clearer anyways.

@antoinebaker

Copy link
Copy Markdown
Member

+1, I like very much this plan, sounds good to me !

Do we have also your go @ogrisel @lorentzenchr @GaelVaroquaux ?

From my point my view the most important is to move this forward, so we can finally (after many years!) have a calibration error metric in sklearn and follow up with the multiclass case :)

Once we agree on the plan, I will review in depth this PR and we will hopefully merge soon.

@lorentzenchr

lorentzenchr commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

I will be +1 as soon as someone shows how this works out for classifiers as well as (mean) regressors.

@GaelVaroquaux

GaelVaroquaux commented Jul 17, 2026 via email

Copy link
Copy Markdown
Member

@lorentzenchr

Copy link
Copy Markdown
Member

I will be +1 as soon as someone shows how this works out for classifiers as well as (mean) regressors.

Why put this as a design goal? What's the problem we are trying to solve here? It complicates the design and I don't see how it makes the life of the users easier.

We often deal with regressors as 2nd class estimators compared to classifiers. The reliability diagram as well as calibration losses are as valid for regressors that estimate the conditional expectation E[Y|X] as they are valid for classifiers estimating class probabilities.
I want to avoid a design that neglects regressors. Technically, the requirement is not hard to fulfil. There are basically 2 ways to fulfil it:

  1. Implement 2 different functions with 2 different names for a calibration loss based on squared error.
  2. Implement one function but make it work for regressors and classifiers.

So if anything, it is us not reaching consensus on names or neglecting to address this requirement.

@antoinebaker

antoinebaker commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

I now prefer option 1. We could implement reliability_{curve,error} for (mean) regressors in a separate follow-up PR, as suggested here:

Then, conditional mean analysis for regressions eventually adopt reliability_{curve,error} vocabulary, which makes the distinction between continuous and discrete labels clearer anyways.

@GaelVaroquaux

GaelVaroquaux commented Jul 17, 2026 via email

Copy link
Copy Markdown
Member

Add brier_calibration_error, the binned calibration term of the Brier
score decomposition for binary probabilistic predictions, using
uniform-mass binning with ceil(cbrt(n_samples)) bins following
Sun et al. (2023), with sample_weight and array API support, and
register the corresponding neg_brier_calibration_error scorer.
…_common

Revert an accidental reformatting of the invalids_nan_inf parametrize
entry that ruff format rejects, and reword the comment explaining why
brier_calibration_error is exempt from the weight-vs-repetition invariance.
…helper

Extract the quantile binning and per-bin reliability computation into a
reusable, weight-aware _weighted_calibration_curve helper (backed by a
new _array_api_quantiles that matches np.percentile for unweighted
data and interpolates on a cumulative-weight scale otherwise). This removes
the duplicated binning logic, centralises input validation, and keeps the
public metric a thin wrapper that only derives the bin count.

Also strengthen the tests: replace the fragile unweighted-mean comparison
with an independent mass-weighted reference, make the perfect-cube test
actually pin the bin count, add a scorer value/pos_label-routing test, and
drop redundant hand-value and over-parametrized cases.
Use array.shape[0] instead of array.size in _array_api_quantiles: .size is a
bound method (not an int) on PyTorch tensors, which broke quantile binning
under the torch and array_api_strict namespaces.

Also move sample_weight onto y_prob's namespace and device before
_find_matching_floating_dtype in _weighted_calibration_curve, so that mixed
namespace/device inputs (e.g. numpy y_proba with an mps sample_weight) no
longer raise when converting across boundaries.
Add the norm and squared parameters and rename the scorer to neg_l2_calibration_error.
@samronsin
samronsin force-pushed the brier-calibration-error branch from 3f11f4d to bf54f70 Compare July 21, 2026 11:41
@samronsin

samronsin commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I currently refrained from adding "neg_l2_squared_calibration_error" (could add it but then eventually debiased would add two more scorers, total 4 scorers for L2 calibration error, 2 of them being the exact square of the 2 others...) and just added "neg_l2_calibration_error" with the square root so as to not be misleading.

"neg_l2_calibration_error" could work as well but is a bit misleading because we do not plan to take the square root to compute the actual l2 norm.

Not sure why you don't want to take the square root @ogrisel though, this is a quite cheap operation that is performed once per loss computation (at the very end). But again, happy to add "neg_l2_squared_calibration_error" or replace "neg_l2_calibration_error" with it (although a bit sad to break symmetry between L1 and L2 when L1 is subsequently introduced, which should be imminent as L1 appears to be the main character here).

@antoinebaker

Copy link
Copy Markdown
Member

The "l2_squared" variant was considered because it is the calibration component of the Brier score decomposition. I guess that depends if we want the loss decomposition into calibration, refinement etc to be part of sklearn scope or not.

We could name this variant "brier_calibration_error" (back to square one :)) and norm="brier". Or we could simply drop it as you suggested, I don't have a strong opinion.

@GaelVaroquaux

GaelVaroquaux commented Jul 21, 2026 via email

Copy link
Copy Markdown
Member

@samronsin samronsin changed the title FEA add brier_calibration_error metric and neg_brier_calibration_error scorer FEA add calibration_error metric with L2 norm and neg_l2_calibration_error scorer Jul 21, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

The first priority is to implement what is massively used in the ML literature: this is the community that we serve

This comment does not really help us to move forward. If anything, it is putting pressure. Everybody involved here is motivated to add calibration error(s) to scikit-learn. As often, the actual implementation is not that hard, but the (decision of the) design of the API is. We want to make it easy for users (type length, searching, ...) but also avoid to block further development.

@scikit-learn/core-devs Your opinion on introducing calibration error(s) would help. It is mainly the API design and names that need to be found and agreed upon.

@antoinebaker

Copy link
Copy Markdown
Member

Ok then, so let's stick to your suggestion @samronsin for the moment, ping me when you feel the PR is ready for review.
We'll see what olivier thinks when he's back from holidays :) in any case it should be a relatively small change.

@StefanieSenger StefanieSenger moved this from In progress to PR Stalled in Labs Jul 27, 2026

@antoinebaker antoinebaker left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @samronsin, here is a first pass. Some comments will be easier to address once the naming / API discussion is settled, so feel free to ignore them until then :)

strategy="uniform",
sample_weight=sample_weight,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a small comment to explain the expected numbers, for example

# We have two bins:
# 1st bin = indices 0 and 1 with weights 1 and 3
# 2nd bin = indices 2 and 3 with weights 2 and 4

assert_allclose(bin_weights, [4, 6])


def test_array_api_quantiles_with_weights():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a test to check the repeated/weighted equivalence for _array_api_quantiles and one to check that _array_api_quantiles = np.percentile(method="linear") when sample_weight=None and sample_weight = all ones.

Comment on lines +3259 to +3264
y_true = np.array([0, 0])
y_proba = np.array([0.1, 0.2])

assert calibration_error(y_true, y_proba) == pytest.approx(
calibration_error(y_true, y_proba, pos_label=1)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would test on more diverse / difficult y_true, y_proba. For example using the global random seed:

rng = check_random_state(global_random_seed)
y_true = np.zeros(n_samples)
y_proba = rng.rand(n_samples)

Comment on lines +3244 to +3247
def test_calibration_error_matches_reference(n_samples, squared):
# Cross-check the full pipeline (binning + mass-weighted aggregation) against
# an independent reference.
rng = check_random_state(n_samples)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use the global_random_seed to vary the test cases

Suggested change
def test_calibration_error_matches_reference(n_samples, squared):
# Cross-check the full pipeline (binning + mass-weighted aggregation) against
# an independent reference.
rng = check_random_state(n_samples)
def test_calibration_error_matches_reference(global_random_seed, n_samples, squared):
# Cross-check the full pipeline (binning + mass-weighted aggregation) against
# an independent reference.
rng = check_random_state(global_random_seed)

To test all random seeds locally:

SKLEARN_TESTS_GLOBAL_RANDOM_SEED=all pytest -k test_calibration_error_matches_reference

assert calibration_error(y_true, y_proba) == pytest.approx(
calibration_error(y_true, y_proba, pos_label=1)
)
assert calibration_error(y_true, y_proba) == pytest.approx(np.sqrt(0.025))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment to explain why sqrt(0.025) is expected ? (Or remove the assertion if it's not easy to explain)

Comment on lines +2021 to +2024
The :func:`calibration_error` function computes a binned calibration error for
binary probabilistic predictions. This metric measures calibration alone by
comparing, within each bin, the average predicted probability assigned to the
positive class and the observed fraction of positive samples.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mentioning / cross referencing calibration_curve could be nice in this section, something like calibration error ~ "distance" of the calibration curve to the diagonal (perfectly calibrated model).

Comment on lines +2044 to +2045
[Sun2023]_, the number of bins is set to the ceiling of the cube root of
:math:`N`, where :math:`N` is the number of samples. Set ``squared=True`` to

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
[Sun2023]_, the number of bins is set to the ceiling of the cube root of
:math:`N`, where :math:`N` is the number of samples. Set ``squared=True`` to
[Sun2023]_, the number of bins is set to :math:`\lceil n_{\text{samples}}^{1/3} \rceil`. Set ``squared=True`` to

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe reference the calibration.rst page for the n_bins = n**(1/3), to skip the citation controversy in #34289 :)

Comment on lines +3809 to +3810
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why catch warnings here ?

Comment on lines +4131 to +4138
# The number of bins is derived from the number of effective (non-zero
# weight) samples so that zero-weighted samples behave like removed samples.
if sample_weight is None:
n_samples = y_proba.shape[0]
else:
sw_xp, _ = get_namespace(sample_weight)
sample_weight_array = sw_xp.asarray(sample_weight)
n_samples = int(sw_xp.sum(sw_xp.astype(sample_weight_array != 0, sw_xp.int64)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would keep it simple and just use n_samples = y_proba.shape[0] instead of the count of nonzero weight.

I agree that the count of nonzero weight is slightly better (with the equivalence zero weight / removing samples). But as we don't have a good solution of the repeated/weighted equivalence in general, and as the count of nonzero weight / n_samples logic would make the docstring a bit tedious to read, I think it's overkill.

Comment on lines +4050 to +4051
norm="l2",
squared=False,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll wait for the API decision, but personally I don't like the squared argument, only relevant for the norm="l2" case. Having norm options as {"l1", "l2","brier"} seems a bit cleaner to me (even if "brier" is not a norm but that's a nitpick IMO).

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants