Repository navigation
Description
Warning
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
Introduce yourself
Hi! I'm Carlos, I'm an ML Engineer / Researcher and a student. I've been using scikit-learn for years for class projects, personal projects, and work. I've contributed to open-source before, but I'm new to scikit-learn's community.
I was practicing and playing with d2_tweedie_score to make sure I understood it beyond the theory of my classes, so I made up a simple dataset to play around with it, and found this issue.
Describe the bug and give evidence about its user-facing impact
d2_tweedie_score can't handle a validation set where y_true is constant. This could happen easily when using CV folds on targets that have lots of zeros for example. Depending on the parameter power it either raises a raw ZeroDivisionError or returns a NaN together with numpy's RuntimeWarning. Comparable metrics such as r2_score or d2_absolute_error_score return a defined value for the same inputs.
Tweedie score is a common metric for data with rare-event targets, and with those targets all-zero CV folds are common. So any user using it that runs into this edge case would be seeing the code crash with an error message that doesn't really explain why. The failure mode changes with the parameter power (exception vs silent NaN), so switching from a Poisson to a compound Poisson loss changes how the code breaks. Another case is if a user is ussing cross_val_score and make_scorer the error is caught and those folds silently score NaN, so the model selection runs on a NaN mean over the remaining folds.
Reproduced on both the 1.7.2 version and the nightly build (1.10.dev0).
Related: #34798 hit the same ZeroDivisionError through the zero-sample-weight path, but was closed without merging and its fix couldn't cover this more general case. #11435 discusses how degenerate metric inputs should be handled in general.
Steps/Code to Reproduce
from sklearn.metrics import d2_tweedie_score, r2_score
y_true = [0, 0, 0] # e.g. a CV fold with no claims
y_pred = [0.1, 0.2, 0.1]
print(r2_score(y_true, y_pred)) # 0.0
print(d2_tweedie_score(y_true, y_pred, power=1.5)) # nan (+ NumPy RuntimeWarnings)
print(d2_tweedie_score(y_true, y_pred, power=1)) # ZeroDivisionErrorExpected Results
A defined, documented and consistent behavior for constant y_true, the same for every power, instead of a ZeroDivisionError is one case and NaN + RuntimeWarning in another.
Actual Results
0.0
/home/carlos/practice/.venv/lib/python3.10/site-packages/sklearn/metrics/_regression.py:1379: RuntimeWarning: divide by zero encountered in power
- y_true * xp.pow(y_pred, 1 - p) / (1 - p)
/home/carlos/practice/.venv/lib/python3.10/site-packages/sklearn/metrics/_regression.py:1379: RuntimeWarning: invalid value encountered in multiply
- y_true * xp.pow(y_pred, 1 - p) / (1 - p)
nan
/home/carlos/practice/.venv/lib/python3.10/site-packages/sklearn/metrics/_regression.py:1372: RuntimeWarning: invalid value encountered in divide
dev = 2 * (xlogy(y_true, y_true / y_pred) - y_true + y_pred)
Traceback (most recent call last):
File "/home/carlos/practice/r.py", line 8, in <module>
print(d2_tweedie_score(y_true, y_pred, power=1)) # ZeroDivisionError
File "/home/carlos/practice/.venv/lib/python3.10/site-packages/sklearn/utils/_param_validation.py", line 218, in wrapper
return func(*args, **kwargs)
File "/home/carlos/practice/.venv/lib/python3.10/site-packages/sklearn/metrics/_regression.py", line 1680, in d2_tweedie_score
return 1 - numerator / denominator
ZeroDivisionError: float division by zero
Versions
System:
python: 3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]
executable: /home/carlos/practice/.venv/bin/python
machine: Linux-6.18.58.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
Python dependencies:
sklearn: 1.7.2
pip: 22.0.2
setuptools: 84.0.0
numpy: 1.26.4
scipy: 1.15.3
Cython: None
pandas: 2.3.3
matplotlib: 3.10.9
joblib: 1.6.0
threadpoolctl: 3.7.0
Built with OpenMP: True
threadpoolctl info:
user_api: openmp
internal_api: openmp
num_threads: 8
prefix: libgomp
filepath: /home/carlos/practice/.venv/lib/python3.10/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0
version: None
user_api: blas
internal_api: openblas
num_threads: 8
prefix: libopenblas
filepath: /home/carlos/practice/.venv/lib/python3.10/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so
version: 0.3.23.dev
threading_layer: pthreads
architecture: SkylakeX
user_api: blas
internal_api: openblas
num_threads: 8
prefix: libscipy_openblas
filepath: /home/carlos/practice/.venv/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-68440149.so
version: 0.3.28
threading_layer: pthreads
architecture: SkylakeXInterest in fixing the bug
Yes, I'd be happy to open a PR once maintainers agree on the expected behavior.
I think there are two reasonable ways to deal with this:
- Follow
r2_scoreexample and return 1.0 for perfect predictions and 0.0 otherwise. We could reuse_assemble_fraction_of_explained_deviance(calledassemble_r2_explained_variancein 1.7.2), and maybe exposingforce_finitelike inr2_score. - Treat the case as undefined and return NaN with an
UndefinedMetricWarning.
Activity
Alm0stSurely commentedon Nov 22, 2026
Root-cause analysis (verified on
main, 9bd6b83)I reproduced the inconsistency and traced it to a single structural difference:
d2_tweedie_scoreis the only D²-family metric that computes the explained-deviance fraction inline, without the degenerate-case guard its siblings share.Where the three failure modes come from
d2_tweedie_scoreends with a raw scalar fraction (sklearn/metrics/_regression.py, end of the function body):When
y_trueis constant,y_avgcoincides withy_trueelementwise, so the null-model deviance (denominator) is identically zero and the score is1 - c/0withc ≥ 0. The observed behavior depends on which route the zero takes:y_true, imperfecty_pred,p ∈ {0, 1}orp < 0> 00.0(exact)ZeroDivisionError(Python float path, no numpy warning)y_true, imperfecty_pred,1 < p < 2, zero-valued entries> 0nannany_true, perfecty_pred0.00.0ZeroDivisionErrorp ≥ 2, zero-valued entriesValueError(strict-positivity domain check) — legitimate, unrelatedThe
nanroute for1 < p < 2is worth noting: withy_avg = 0, the deviance term-y_true * y_pred**(1 - p) / (1 - p)evaluates0 * infinside the array expression, so the denominator becomesnanrather than0.0, and the Python-level fraction silently yieldsnaninstead of raising. Same degenerate input, three different failure signatures depending onpower— exactly the accidentality the report describes.The existing guard it bypasses
r2_score,explained_variance_score,d2_absolute_error_scoreandd2_pinball_scoreall funnel through_assemble_fraction_of_explained_deviance(_regression.py:946), which encodes the established convention for the degenerate case (force_finite=True): zero numerator →1.0(perfect), nonzero numerator with zero denominator →0.0(no better than the null model). That matches this function's own documented contract — "A model that always uses the empirical mean ofy_trueas constant prediction … gets a D² score of 0.0" — and it also matches the docstring claim thatpower=0*"corresponds tor2_score", which is currently false for constanty_true(r2_scorereturns0.0`; this raises).Suggested fix surface
One-line conceptual change: route
d2_tweedie_scorethrough_assemble_fraction_of_explained_deviancewithforce_finite=True(andn_outputs=1,multioutput="uniform_average"), adapting the squeezed 1-D inputs to the small array shape the helper expects. That single change:power=0behave exactly liker2_scorefor constanty_true(imperfect →0.0, perfect →1.0),y_trueunder weights has the same zero-null-deviance structure).Two design questions for the maintainers before a PR:
force_finiteas a new public parameter (parity withr2_score) vs. hard-codedTrue(parity withd2_absolute_error_score/d2_pinball_score, which don't expose it)?UndefinedMetricWarning? The n<2 branch of this same function warns and returnsnan; the_assemble_*path does not warn. Either is defensible, but they should be made consistent deliberately rather than by inheritance.The
p ≥ 2ValueErroron zero-valued inputs is a genuine domain error and should stay as-is — it fires before the fraction is ever reached.Happy to prepare the PR once the intended semantics are settled (or defer to whoever picks it up — no claim from my side).
Charly21r commentedon Nov 22, 2026
Thanks for the additional analysis! I agree that the existing behavior of the other$D^2$ metrics provides a good precedent here. I'd still be happy to work on the implementation once we have some feedback from the maintainers on the expected behavior.
Anish8800 commentedon Nov 22, 2026
Hi! I'd be interested in working on this issue and contributing a fix.
I've gone through the reproduction and the discussion regarding the degenerate-case handling in
d2_tweedie_score. I'd like to investigate the existing implementation, understand how the related D² metrics handle these cases, and work on a regression test and fix.I'm relatively new to contributing to scikit-learn, so I'd appreciate any guidance regarding the expected behavior or the proposed approach. If this issue is still open for contributions, I'd be happy to work on it.
Atharsha-k commentedon Dec 2, 2026
Hi! I'm an AI & Data Science student interested in contributing to scikit-learn. I've read the issue description and the discussion about handling constant
y_trueconsistently with the other D² metrics.I'd like to help investigate the issue, write regression tests and work on a fix under the project's contribution guidelines. Since the issue is still marked "Needs Triage," would it be appropriate for me to start investigating, or should I wait for a maintainer to confirm the intended behavior?
Thank you!