Skip to content

FIX Clamp variance to zero in f_regression for constant columns - #34197

Closed
EdenRochmanSharabi wants to merge 2 commits into
scikit-learn:mainfrom
EdenRochmanSharabi:fix/f-regression-constant-columns
Closed

EdenRochmanSharabi wants to merge 2 commits into
scikit-learn:mainfrom
EdenRochmanSharabi:fix/f-regression-constant-columns

Conversation

@EdenRochmanSharabi

@EdenRochmanSharabi EdenRochmanSharabi commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

Closes #11395.

What does this implement/fix? Explain your changes.

In r_regression, which f_regression calls, the per-column scale is computed as
sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2). For a constant column
the variance is mathematically zero, but catastrophic cancellation makes the
subtraction land on a small negative value, so np.sqrt emits a RuntimeWarning and
returns NaN. The NaN propagates into the correlation coefficient, where
force_finite=True collapses it back to 0.0, so the visible symptom is the spurious
warning.

This clamps the intermediate result to zero with np.maximum before the square root.

Added test_f_regression_constant_column, which fails on main with a
RuntimeWarning and passes here.

AI usage disclosure

I used AI assistance for:

  • Documentation (including examples)
  • Research and understanding

The fix itself was written by hand. AI was used to double check the diagnosis and to
review the change, not to generate it.

Any other comments?

The diagnosis in #11395 is @Lawson-Darrow's and they had offered to open a PR with a
regression test, so apologies for getting ahead of that. They also asked whether
mean_variance_axis would be preferable to a clamp, following @agramfort's earlier
suggestion. I went with the clamp because it keeps the dense and sparse paths
identical and adds no second pass over the data, but I am happy to switch, or to close
this in favour of their PR.

When a feature column is constant, catastrophic cancellation in
row_norms(X.T, squared=True) - n_samples * X_means**2 can produce
small negative values, causing np.sqrt to emit a RuntimeWarning and
return NaN. Clamp the result to zero before taking the square root.

Closes scikit-learn#11395
@EdenRochmanSharabi

Copy link
Copy Markdown
Contributor Author

Closing to make room for other PRs. Happy to reopen if needed.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

f_regression takes square root of negative values when constant columns are present

1 participant