R2Score reports a perfect score for a mean predictor after rescaling nonconstant targets
🐛 Bug
r2_score and R2Score return 1 for a mean predictor when the targets have small magnitudes, although the targets are nonconstant and the residual sum of squares equals the total sum of squares. Scaling the targets and predictions back up gives the expected score of 0.
This came from testing the mean-prediction baseline, rather than a failure in a production training run. It affects an ordinary regression evaluation: changing the units of both predictions and targets should preserve R².
To Reproduce
Code sample
import torch
from torchmetrics.functional.regression import r2_score
from torchmetrics.regression import R2Score
for scale in (1.0, 0.001):
target = torch.arange(4, dtype=torch.float64) * scale
preds = torch.full_like(target, target.mean())
metric = R2Score().set_dtype(torch.float64)
metric.update(preds[:2], target[:2])
metric.update(preds[2:], target[2:])
scores = torch.stack([r2_score(preds, target), metric.compute()])
print(f"scale={scale}: functional={scores[0].item()}, streaming={scores[1].item()}")
torch.testing.assert_close(scores, torch.zeros_like(scores), atol=1e-12, rtol=0)
Observed functional and streaming scores are both 0 at scale 1, and both 1 at scale 0.001. The expected score is 0 in both cases. At the smaller scale, RSS and centered TSS are both 5e-6; neither is zero. A direct centered calculation and scikit-learn agree on 0. Predicting zero instead of the mean gives an expected score of -1.8, but TorchMetrics also returns 1.
The behavior was reproduced with float32 and float64 on unmodified master 6c551c6469dc04fe92291c000ce2607860df92d2 and the PyPI 1.9.0 package. Repeating the same small-scale samples 100 times makes the result return to approximately 0.
Environment
- macOS 26.6.2 arm64; Python 3.12.3; CPU.
- PyTorch 2.8.0; NumPy 2.3.5; scikit-learn 1.9.1.
- TorchMetrics master at the commit above, and a separate PyPI 1.9.0 installation.
Additional context
In _r2_score_compute, both RSS and TSS are compared with zero using atol=1e-4. When both fall below that absolute threshold, raw_scores retains its initial value of 1.
I checked #1573 and #1576: the existing guard addresses a real cancellation problem with near-constant targets. Simply removing it could reintroduce that problem. Would a criterion based on data scale and numerical precision be appropriate, or would you prefer a change to the accumulation of the centered statistics? The existing test_constant_target needs to remain part of the discussion and regression coverage.
A standalone proposed regression file on master has four failures for the small-scale mean baseline and nine passing controls, including the existing near-constant scenario. No library fix or full-suite result is claimed.
AI assistance was used for investigation and drafting. The reproduction and control comparisons were executed locally.
Hi! Thanks for your contribution! Great first issue!
One more consequence of the same absolute tolerance, in case it is useful as a regression case for #3525: with multi-output averaging it can reverse the ranking of two fixed predictors, not only inflate a score.
import torch
from torchmetrics.functional import r2_score
y = torch.tensor([[-1.0, 0.0], [0.0, 1.0], [1.0, -1.0]], dtype=torch.float64)
C = y * torch.tensor([0.8, 0.1], dtype=torch.float64)
D = y * 0.3
for s in (1.0, 0.01):
print(s, round(r2_score(C * s, y * s).item(), 6), round(r2_score(D * s, y * s).item(), 6))
# 1.0 0.575 0.51 C ranks above D
# 0.01 0.595 1.0 D ranks above C
Both predictors have positive R² at scale 1. At scale 0.01 both target sums of squares are 2e-4, above the tolerance, so this is not the near-constant-target case: both of D's residual sums fall under atol=1e-4 and are scored 1, while only one of C's does. In exact arithmetic the order is reversed for 1/16200 < s² ≤ 1/9800 (s from about 0.00786 to 0.0101). For a single output the same branch can tie two predictors but not reverse them, so the reversal needs aggregation across outputs.
Observed on TorchMetrics 1.9.0 with PyTorch 2.14.0 on CPU: float32 and float64, r2_score and R2Score, uniform_average and variance_weighted. scikit-learn 1.9.1 returns 0.575 and 0.51 at both scales. Not run against the #3525 branch; applying the tolerance rule shown in its diff to these inputs (re-implemented, not the PR code) gives 0.575 and 0.51 at both scales.
Derivation and the exact interval are in section 4 of https://doi.org/10.5281/zenodo.22973131 (my preprint, 26 September 2026).
AI assistance was used for the analysis and drafting. The snippet and the comparisons above were run locally.