Skip to content

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

Open

Description

@robertmaxwilliams

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.

Description

sklearn.feature_selection.f_regression raises RuntimeWarning: invalid value encountered in sqrt when an array with any constant column is passed in.

If this is the expected behavior, this issue should be closed. However, it seem suspicious that this only happens when center is True, and even so it may be worthwhile to check for constant columns and raise a more helpful warning.

If the call to f_regression below is replaced with
f_regression(X, y, center=False) then all values are returned with no NaN's or warnings.

I'm still not sure what conditions are needed for the error to occur. A constant column usually creates a division by zero warning, which appears to be the correct behavior. This specific array always results in square root of a negative, which is unexpected.

Steps/Code to Reproduce

import numpy as np
from sklearn.feature_selection import f_regression

X = np.array([[  0.92  ,   0.2674,  54.934 ,  26.    ],
              [  0.92  ,   0.2674,  54.934 ,  28.    ],
              [  0.92  ,   0.2674,  54.934 ,  23.    ],
              [  0.92  ,   0.2674,  54.934 ,  21.    ],
              [  0.92  ,   0.2674,  54.934 ,  29.    ],
              [  0.92  ,   0.2674,  54.934 ,  25.    ],
              [  0.92  ,   0.2674,  54.934 ,  23.    ],
              [  0.92  ,   0.2674,  54.934 ,  28.    ],
              [  0.92  ,   0.2674,  54.934 ,  27.    ],
              [  0.92  ,   0.2674,  54.934 ,  27.    ]])
y = np.array([ 0.92,  0.92,  0.92,  0.92,  0.92,  0.92,  0.92,  0.92,  0.92,  0.92])

f_regression(X, y)

Expected Results

No warning raised and no NaN's in output

Actual Results

/usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scikit_learn-0.19.1-py3.6-macosx-10.7-x86_64.egg/sklearn/feature_selection/univariate_selection.py:292: RuntimeWarning: invalid value encountered in sqrt
  n_samples * X_means ** 2)
/usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater
  return (self.a < x) & (x < self.b)
/usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less
  return (self.a < x) & (x < self.b)
/usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:1821: RuntimeWarning: invalid value encountered in less_equal
  cond2 = cond0 & (x <= self.a)
(array([        nan, -8.        , -8.        , -8.07593079]),
 array([ nan,   1.,   1.,   1.]))

Another example without the error

...
f_regression(X, y, center=False)

returns

(array([ -2.02661983e+16,  -2.02661983e+16,  -2.02661983e+16,
          9.57231884e+02]),
 array([  1.00000000e+00,   1.00000000e+00,   1.00000000e+00,
          1.88654093e-10]))

Versions

Darwin-15.6.0-x86_64-i386-64bit
Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]
NumPy 1.12.1
SciPy 1.1.0
Scikit-Learn 0.19.1

Activity

  1. robertmaxwilliams commented on Jun 30, 2018

    @robertmaxwilliams
    Author

    I don't know enough about the statistics to suggest how this should be fixed, but the invalid values are encountered here:

    X_norms = np.sqrt(row_norms(X.T, squared=True) -

  2. robertmaxwilliams commented on Jun 30, 2018

    @robertmaxwilliams
    Author

    The problem disappears if X is changed in certain ways, such as adding or deleting rows. The issue does not seem to be sensitive to scaling or adding constants to X, or to any value of y.

    Here is another example with normal results, which does not reproduce the issue.

    import numpy as np
    from sklearn.feature_selection import f_regression
    
    X = np.ones((5,4))
    y = np.ones(5,)
    
    f_regression(X, y)

    returns

    /usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scikit_learn-0.19.1-py3.6-macosx-10.7-x86_64.egg/sklearn/feature_selection/univariate_selection.py:301: RuntimeWarning: invalid value encountered in true_divide
      corr /= X_norms
    /usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater
      return (self.a < x) & (x < self.b)
    /usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less
      return (self.a < x) & (x < self.b)
    /usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:1821: RuntimeWarning: invalid value encountered in less_equal
      cond2 = cond0 & (x <= self.a)
    
    (array([ nan,  nan,  nan,  nan]), array([ nan,  nan,  nan,  nan]))

    and

    ...
    f_regression(X, y, center=False)

    returns

    /usr/local/miniconda3/envs/testml/lib/python3.6/site-packages/scikit_learn-0.19.1-py3.6-macosx-10.7-x86_64.egg/sklearn/feature_selection/univariate_selection.py:306: RuntimeWarning: divide by zero encountered in true_divide
      F = corr ** 2 / (1 - corr ** 2) * degrees_of_freedom
    
    (array([ inf,  inf,  inf,  inf]), array([ 0.,  0.,  0.,  0.]))
  3. agramfort commented on Jul 8, 2018

    @agramfort
    Member
  4. arnaualba commented on Oct 18, 2021

    @arnaualba

    This issue has not been fixed yet. The problem is that f_regression() from sklearn/feature_selection/_univariate_selection uses

            # compute the scaled standard deviations via moments                                                                                                                                                                                                                                                                                                                                 
            X_norms = np.sqrt(row_norms(X.T, squared=True) -                                                                                                                                                           
                              n_samples * X_means ** 2)  
    

    to compute the standard deviation. When the variance is zero, this method sometimes finds negative small (~1e-15) values.
    For example in the example above:

    >>> xtest = 0.92*np.ones(5)
    >>> n_samples = xtest.shape[0]
    >>> print("Method used in f_regression()", np.sum(xtest**2) - n_samples*xtest.mean()**2)
    >>> print("Numpy variance", n_samples*np.var(xtest))
    
    Method used in f_regression() -8.881784197001252e-16
    Numpy variance 6.162975822039155e-32
    
  5. added a commit that references this issue on Mar 26, 2026
    9a5dafd
  6. Lawson-Darrow commented on Jun 3, 2026

    @Lawson-Darrow

    This still reproduces on main. In r_regression (which f_regression calls), X_norms = sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2) hits catastrophic cancellation for constant columns: the variance is mathematically 0 but the subtraction lands at a tiny negative value, so sqrt returns NaN and raises the RuntimeWarning.

    Following @agramfort's earlier suggestion, computing the per-column variance via mean_variance_axis (or clamping the term at 0 for the dense path) would fix it cleanly. I'm happy to open a PR with a regression test for the constant-column case. Any preference on mean_variance_axis vs a simple clamp before I do?

  7. added
    Needs Investigation
    and removed on Jun 10, 2026
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions