Skip to content

d2_tweedie_score raises ZeroDivisionError when y_true is constant #35402

Open

Description

@Charly21r

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. $D^2$ is mathematically undefined when the null model's deviance is zero, so the problem is not the lack for a numeric score, it's that the current behavior looks accidental and inconsistent.

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))    # ZeroDivisionError

Expected 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: SkylakeX

Interest 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:

  1. Follow r2_score example and return 1.0 for perfect predictions and 0.0 otherwise. We could reuse _assemble_fraction_of_explained_deviance (called assemble_r2_explained_variance in 1.7.2), and maybe exposing force_finite like in r2_score.
  2. Treat the case as undefined and return NaN with an UndefinedMetricWarning.

Activity

  1. added
    Needs Triage
    on Nov 15, 2026
  2. Alm0stSurely commented on Nov 22, 2026

    @Alm0stSurely

    Root-cause analysis (verified on main, 9bd6b83)

    I reproduced the inconsistency and traced it to a single structural difference: d2_tweedie_score is 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_score ends with a raw scalar fraction (sklearn/metrics/_regression.py, end of the function body):

    y_avg = _average(y_true, weights=sample_weight, xp=xp)
    denominator = _mean_tweedie_deviance(y_true, y_avg, sample_weight=sample_weight, power=power)
    return 1 - numerator / denominator

    When y_true is constant, y_avg coincides with y_true elementwise, so the null-model deviance (denominator) is identically zero and the score is 1 - c/0 with c ≥ 0. The observed behavior depends on which route the zero takes:

    case numerator denominator result
    constant y_true, imperfect y_pred, p ∈ {0, 1} or p < 0 > 0 0.0 (exact) ZeroDivisionError (Python float path, no numpy warning)
    constant y_true, imperfect y_pred, 1 < p < 2, zero-valued entries > 0 nan silent nan
    constant y_true, perfect y_pred 0.0 0.0 ZeroDivisionError
    p ≥ 2, zero-valued entries — — ValueError (strict-positivity domain check) — legitimate, unrelated

    The nan route for 1 < p < 2 is worth noting: with y_avg = 0, the deviance term -y_true * y_pred**(1 - p) / (1 - p) evaluates 0 * inf inside the array expression, so the denominator becomes nan rather than 0.0, and the Python-level fraction silently yields nan instead of raising. Same degenerate input, three different failure signatures depending on power — exactly the accidentality the report describes.

    The existing guard it bypasses

    r2_score, explained_variance_score, d2_absolute_error_score and d2_pinball_score all 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 of y_true as constant prediction … gets a D² score of 0.0" — and it also matches the docstring claim that power=0 *"corresponds to r2_score", which is currently false for constant y_true (r2_scorereturns0.0`; this raises).

    Suggested fix surface

    One-line conceptual change: route d2_tweedie_score through _assemble_fraction_of_explained_deviance with force_finite=True (and n_outputs=1, multioutput="uniform_average"), adapting the squeezed 1-D inputs to the small array shape the helper expects. That single change:

    • makes power=0 behave exactly like r2_score for constant y_true (imperfect → 0.0, perfect → 1.0),
    • collapses all three failure modes into the family convention,
    • covers the weighted variant for free (constant y_true under weights has the same zero-null-deviance structure).

    Two design questions for the maintainers before a PR:

    1. force_finite as a new public parameter (parity with r2_score) vs. hard-coded True (parity with d2_absolute_error_score/d2_pinball_score, which don't expose it)?
    2. Should the degenerate case emit an UndefinedMetricWarning? The n<2 branch of this same function warns and returns nan; the _assemble_* path does not warn. Either is defensible, but they should be made consistent deliberately rather than by inheritance.

    The p ≥ 2 ValueError on 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).

  3. Charly21r commented on Nov 22, 2026

    @Charly21r
    Author

    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.

  4. Anish8800 commented on Nov 22, 2026

    @Anish8800

    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.

  5. Atharsha-k commented on Dec 2, 2026

    @Atharsha-k

    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_true consistently 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!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions