#23732·keras

pearson_correlation has no zero-variance guard, unlike concordance_correlation in the same file

Author: gaurav-gandhi-2411Created Sep 23, 2026Updated Sep 25, 2026
LabelsGood first issuebackend:torchbackend:tensorflowbackend:jax

Summary

A single degenerate (zero-variance) batch poisons PearsonCorrelation.result() to NaN for the rest of the epoch: a clean batch gives 0.9819806, a batch containing one constant row then gives nan, and a third, entirely clean batch run afterward still reads nan — it does not recover until reset_state(). This happens because pearson_correlation/PearsonCorrelation (correlation_metrics.py) divides by ops.std(...) with no zero-variance guard, unlike its neighbor in the same file:

python
# pearson_correlation -- unguarded
y_true_norm = y_true_norm / ops.std(y_true_norm, axis=axis, keepdims=True)
y_pred_norm = y_pred_norm / ops.std(y_pred_norm, axis=axis, keepdims=True)
python
# concordance_correlation -- guarded
return ops.mean(2 * covar / (norm + backend.epsilon()), axis=axis)

Repro: a batch of 2 rows where only one is constant (e.g. y_true=[[0.1,0.5,0.9],[2.0,2.0,2.0]]) reproduces on numpy/jax/torch/tensorflow. Only numpy raises any warning; jax/torch/tf are silent.

What I checked before filing:

  • scipy.stats.pearsonr on constant input returns nan with ConstantInputWarning.
  • sklearn.feature_selection.r_regression(force_finite=True) (default) forces 0.0; force_finite=False returns nan.
  • concordance_correlation, run on the same repro, maps the degenerate row to 0.0, which lowers the batch mean (0.471 on this repro).
  • R2Score (#23420) chose force-finite (1.0 for a zero-variance perfect prediction), modeled on sklearn's default.

I don't have a recommendation between keeping NaN (correct, but poisons Mean-based aggregation), forcing a finite value (lowers the batch mean, like concordance_correlation/ sklearn's default), or excluding degenerate rows from the mean (changes the effective sample count). This looks like a semantics decision for the team. Happy to implement whichever direction is preferred, with tests across all four backends.