fix: extend zero_division parameter to percentage and range-based metrics
Checklist before merging this PR:
- [x] Mentioned all issues that this PR fixes or addresses.
- [x] Summarized the updates of this PR under Summary.
- [x] Added an entry under Unreleased in the Changelog.
Mirrors the design of #3059 for the percentage / range-based metric family. Adopts the breaking-change π΄ marker convention discussed in #3080.
Summary
Percentage and range-based metrics (wmape, ope, arre, marre, coefficient_of_variation) previously either raised a hard ValueError or silently returned nan/inf when their denominator was zero. This made batch evaluation pipelines brittle for constant or all-zero components.
This PR extends the zero_division parameter pattern introduced in #3059 to these five metrics:
"warn"(default) β returnsnp.nanand emits a warning."raise"β preserves the legacyValueError.
A new _safe_pct_divide helper sits next to _safe_scaled_divide in darts/metrics/utils.py. The two differ only in fill semantics: percentage metrics multiply the ratio by 100, so a 1.0 fill for the 0/0 case (the scaled-metric "on par with naive") would surface as 100 % error and be misleading β hence np.nan instead.
Two adjacent bugs are fixed in the same change:
opepreviously checkedsum > 0and rejectedactual_serieswith a strictly negative sum (e.g. financial return series). The check is nowsum != 0via the helper.wmape's docstring claimedValueError if actual_series contains some zeros, but the implementation divides bysum(|y_true|)and only the all-zero case ever triggered any path. Docstring corrected.
Behavior change
| Input shape | Behavior |
|---|---|
| Healthy inputs (non-zero denominator) | Unchanged β all 455 existing tests pass without modification |
Zero denominator + default "warn" |
Returns np.nan and logs a warning (previously: silent NaN/inf, or hard ValueError) |
Zero denominator + "raise" |
Raises ValueError (legacy behavior preserved as opt-in) |
Negative-sum actual_series in ope |
Now works correctly (previously: incorrectly raised) |
Per the discussion in #3080, the CHANGELOG entry for the parameter addition carries the breaking-change π΄ marker because the default behavior flips from raising to warning.
Test plan
- New parametrized
test_pct_metrics_zero_divisioncovering all 5 metrics: warn-mode returns NaN with warning, raise-mode raisesValueError, invalid string rejected, healthy inputs unaffected. - New
test_ope_accepts_negative_sumverifying thesum != 0fix using a series with a strictly negative sum. - Updated existing
test_ope_zeroandtest_arreto opt into legacy behavior withzero_division="raise". uv run pytest darts/tests/metrics/test_metrics.pyβ 461 passed (was 455, +6 new).uv run pre-commit run --files <changed>β all hooks pass (ruff, ruff-format, trailing whitespace, end-of-file).
Other Information
Files changed (+208/-31):
darts/metrics/utils.pyβ_safe_pct_dividehelperdarts/metrics/metrics.pyβ 5 metrics extendeddarts/tests/metrics/test_metrics.pyβ 6 new tests + 2 legacy-test updatesCHANGELOG.mdβ entries under**Fixed**(the bug fixes) and**Improved**(the new parameter, with π΄ marker)
Hi @dennisbader β gentle nudge on this when you get a chance. CI hasn't triggered yet (looks like it needs a maintainer approve-and-run for first-time contributors). It extends the #3059 zero_division pattern to the percentage/range metrics (wmape, ope, arre, marre, coefficient_of_variation), with tests. Thanks!
Codecov Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 96.97%. Comparing base (b006a1d) to head (41c7790).
Additional details and impacted files
@@ Coverage Diff @@
## master #3122 +/- ##
==========================================
- Coverage 97.03% 96.97% -0.07%
==========================================
Files 165 165
Lines 17926 17924 -2
==========================================
- Hits 17394 17381 -13
- Misses 532 543 +11
:umbrella: View full report in Codecov by Harness.
:loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
Hey @mahimn01, thanks for this PR and contributing :). Will review it shortly as this is something we should definitely add, but it would be also great if you could create an issue for this first. Thanks!
Thanks @jakubchlapek, this makes sense β best-score for 0/0 is the right call, and it actually fixes a latent bug I'd missed: with NaN-everywhere, a genuinely perfect forecast on a degenerate series scores NaN (ope on a zero-sum series with an identical prediction; arre/marre on a constant series predicted perfectly).
I'll collapse _safe_pct_divide into _safe_scaled_divide β one helper with a configurable 0/0 fill (1.0 scaled, 0.0 percentage), x/0 β NaN, and "raise" preserved (keeping each caller's existing message). A nice side effect of the shared helper's element-wise fill: for arre/marre it fixes a case the current code gets wrong β a constant-actual column is currently all-NaN even at timesteps where the per-step error is 0; element-wise gives 0/0 β 0 and x/0 β NaN within the same column.
On scope (full breakdown in the issue): wmape/ope/arre/marre/coefficient_of_variation are already in this PR β I'll switch them to the unified helper. Good news on the rest of the family: sape/smape already encode 0/0 β 0.0 inline and have no x/0 case, so the only delta there is exposing the explicit zero_division knob for the "raise" option. ape/mape are the trickier ones β they still hard-raise on any y_t == 0, and because their denominator is the per-timestep actual (not a column scalar) they need element-wise handling; relaxing MAPE's default is also a larger behavioral change. Would you prefer ape/mape in this PR (default kept as raise, opt into fill via zero_division) or as a focused follow-up?
One small flag: coefficient_of_variation is RMSE/mean (not abs-wrapped, and the mean can be negative), so a zero mean is a legitimate non-degenerate case β I've proposed 0/0 β 0.0 / x/0 β NaN for it but happy to adjust.
Inline replies:
- (arre, "why removed?") that was the old
if not (y_max > y_min).all(): raise(...)guard β the zero-range check moved into the helper, gated behindzero_division(default fills;"raise"re-raises, preserving the legacy behavior). The old message also said "MARRE" insidearre(), so that copy-paste slip drops out. - (test) agreed β I'll fold the negative-sum check into
test_ope()with a small negative-series helper. I'll also add a0/0best-score case to the zero-division test (the current fixtures are allx/0, so they stay NaN and need no change).
I've opened #3132 to track the design. Thanks for the thoughtful review!
Hey @jakubchlapek β no rush, just a bump on this one whenever you get a chance.
I think we're aligned on the core: fold the percentage path into the unified _safe_scaled_divide with best-score for 0/0 and x/0 β NaN. I opened #3132 to track the design.
Two calls are yours before I finish the rework:
ape/mapeβ happy to fold them into this PR or split them into a focused follow-up. They're a bit trickier than the rest since their denominator is per-timestep (so element-wise handling), and relaxing MAPE's default is a slightly bigger behavioural change β so I'd rather defer to you on scope.coefficient_of_variation's0/0fill β I'm leaning0.0(RMSE = 0 is a genuinely perfect forecast), flagging it since its denominator can go negative.
Point me either way and I'll turn it around quickly, and rebase at the same time since master's moved.
Hey @mahimn01, thanks for the update.
Regarding the cv 0/0 fill it definitely makes sense for me to use 0.0 Maybe we could extend the _safe_scaled_divide to accept a best_score/zero_fill/fitting_name parameter. to pass for a metric what should be the output in case of 0/0.
Regarding the ape/mape I would definitely include them in this PR. This being said I am not quite sure what exactly the issue with them is for this approach. Similarly to other metrics (like coefficient_of_variation which you already implemented) ape exposes y_true and y_pred which we would just need to similarly wrap with the division helper. Similarly I don't get what you mean with the relaxing MAPE's default. Could you double check this and clarify? Thanks :)
Hey @jakubchlapek, agreed on both.
On ape/mape, you're right. Once _safe_pct_divide is folded into _safe_scaled_divide (which fills element-wise) it falls out with no special handling. You pass errors = y_true - y_pred and scale = y_true, both (t, c), and per element 0/0 gives 0.0 for a perfect forecast and x/0 gives NaN, same as cv. I'll include them.
On MAPE's default, ape and mape currently raise on a zero actual (it's documented), so defaulting zero_division="warn" changes that to warn-and-fill. Same raiseβwarn shift the PR already makes for the other five, so it stays under the π΄ note. I'll default them to "warn" and update the docstrings.
I'll unify _safe_pct_divide into _safe_scaled_divide with a best_score arg (1.0 scaled, 0.0 percentage), route wmape, ope, arre, marre, cv, ape and mape through it, and rebase since master moved.
Reworked and pushed, also rebased onto master. _safe_pct_divide is now folded into _safe_scaled_divide via the best_score arg (1.0 scaled, 0.0 percentage), and ape, mape, wmape, ope, arre, marre and cv all route through it. 0/0 gives the perfect-forecast score and x/0 gives NaN, filled element-wise so a constant actual_series no longer NaNs a whole component.
One heads-up, since mape is the default metric for backtest and gridsearch, the raise to warn change makes those surface NaN instead of raising on a zero actual, consistent with the #3059 scaled metrics.