Repository navigation
Conversation
025ca82 to
a503045
Compare
|
I would wait for #33856. |
|
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
Indeed the @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 cc @ogrisel |
|
I have been wanting to do a |
|
The linting CI failure may go away if you merge main, see #34331. |
|
@GaelVaroquaux doesn't like the name |
|
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. |
|
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 |
|
I have a crazy idea but it could work :) Why not name it
|
|
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. |
|
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. |
|
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)? |
|
For reference, in pytorch it seems to be named They also have a For the "Brier" calibration error, this is l2**2, so we could:
For other tasks (eg quantile regression), we could use a dedicated naming. |
|
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:
In the past, we went with the 1st option, e.g., |
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 |
|
We need to agree both on the function name (possibly with a cv_results = cross_validate(classifier, X, y, scoring=["neg_brier_score", "neg_l2_calibration_error"])For string names I am fine with any of:
I am also fine adding 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 EDIT: I originally forgot the ugly "neg_" prefixes... I'd like to get rid of them, but this is another PR. |
|
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:
Then, conditional mean analysis for regressions eventually adopt |
|
+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. |
|
I will be +1 as soon as someone shows how this works out for classifiers as well as (mean) regressors. |
|
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.
So if anything, it is us not reaching consensus on names or neglecting to address this requirement. |
|
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.
So I would be in favor of a separate follow-up PR to implement reliability_ {curve,error} for (mean) regressors.
Sounds good to me
|
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.
3f11f4d to
bf54f70
Compare
|
I currently refrained from adding
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 |
|
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. |
|
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. |
|
Ok then, so let's stick to your suggestion @samronsin for the moment, ping me when you feel the PR is ready for review. |
antoinebaker
left a comment
There was a problem hiding this comment.
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, | ||
| ) | ||
|
|
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
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.
| 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) | ||
| ) |
There was a problem hiding this comment.
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)| 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) |
There was a problem hiding this comment.
You can use the global_random_seed to vary the test cases
| 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)) |
There was a problem hiding this comment.
Could you add a comment to explain why sqrt(0.025) is expected ? (Or remove the assertion if it's not easy to explain)
| 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. |
There was a problem hiding this comment.
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).
| [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 |
There was a problem hiding this comment.
| [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 |
There was a problem hiding this comment.
Maybe reference the calibration.rst page for the n_bins = n**(1/3), to skip the citation controversy in #34289 :)
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore", FutureWarning) |
| # 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))) |
There was a problem hiding this comment.
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.
| norm="l2", | ||
| squared=False, |
There was a problem hiding this comment.
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).
Reference Issues/PRs
Based on #11096 with reduced scope as agreed.
What does this implement/fix? Explain your changes.
Adds
sklearn.metrics.calibration_errorfor binary probabilistic predictions with the L2 norm and the correspondingneg_l2_calibration_errorscorer.Why: scikit-learn has
calibration_curvefor visual inspection but no scalar metric that quantifies the distance to a perfectly calibrated classifier, usable directly in model selection (cross_val_score/GridSearchCVvia the scorer). The metric uses uniform-mass (weighted-quantile) binning consistent withcalibration_curve(strategy="quantile"), with the number of bins set toceil(cbrt(n_samples))following the analysis of uniform-mass binning in Sun et al. (2023, arXiv:2305.10886). Supportssample_weight,pos_label, and the array API.Areas that deserve careful review:
ceil(cbrt(n))bin-count rule is a deliberate design choice (non_bins/strategyparameter). A consequence is that integersample_weightis not equivalent to repeating samples (bin count depends on the number of distinct weighted samples, not total weight); the common test exemptionMETRICS_WITH_SAMPLE_WEIGHT_NOT_EQUIVALENT_TO_REPETITIONintest_common.pymakes this explicit.searchsorted(bins[1:-1], y_proba)(left-inclusive), matchingcalibration_curve; ties at a weighted-quantile edge collapse into the lower bin by design.squared=Trueis exposed on the metric without a dedicated squared scorer.AI usage disclosure
I used AI assistance for: