Skip to content

cov_nearest cannot not handle matrices with zero in the diagonal #9675

Closed

Description

@travis-leith

Describe the bug

Matrices with values of zero along the diagonal are not handled well in cov_nearest. The result shows nan in many cells. This is likely because the implementation tries to convert to a correlation matrix first, which is not possible in this case. This is a problem in the case of quadratic optimization. Sometimes you might want a zero value for a quadratic term but the solver likes to work with positive definite matrices.

Code Sample, a copy-pastable example if possible

from statsmodels.stats.correlation_tools import cov_nearest
import numpy as np

mat = np.array([[2.0, 0.0], [0.0, 0.0]])
result = cov_nearest(mat)
print(result)

Expected Output

[[ 2. nan]
 [nan nan]]

If I run this in the R package Matrix I get

2 x 2 Matrix of class "dpoMatrix"
     [,1]  [,2]
[1,]    2 0e+00
[2,]    0 2e-08

Details

INSTALLED VERSIONS

Python: 3.13.3.final.0

statsmodels

Installed: 0.14.5 (c:\repos\Scid.Bso2.venv\Lib\site-packages\statsmodels)

Required Dependencies

cython: Not installed
numpy: 2.3.3 (c:\repos\Scid.Bso2.venv\Lib\site-packages\numpy)
scipy: 1.16.2 (c:\repos\Scid.Bso2.venv\Lib\site-packages\scipy)
pandas: 2.3.2 (c:\repos\Scid.Bso2.venv\Lib\site-packages\pandas)
dateutil: 2.9.0.post0 (c:\repos\Scid.Bso2.venv\Lib\site-packages\dateutil)
patsy: 1.0.2 (c:\repos\Scid.Bso2.venv\Lib\site-packages\patsy)

Optional Dependencies

matplotlib: Not installed
cvxopt: Not installed
joblib: 1.5.2 (c:\repos\Cns.Scid.Bso2.venv\Lib\site-packages\joblib)

Developer Tools

IPython: 9.5.0 (c:\repos\Scid.Bso2.venv\Lib\site-packages\IPython)
jinja2: 3.1.6 (c:\repos\Scid.Bso2.venv\Lib\site-packages\jinja2)
sphinx: Not installed
pygments: 2.19.2 (c:\repos\Scid.Bso2.venv\Lib\site-packages\pygments)
pytest: 8.4.2 (c:\repos\Scid.Bso2.venv\Lib\site-packages\pytest)
virtualenv: Not installed

Activity

  1. josef-pkt commented on Oct 21, 2025

    @josef-pkt
    Member

    Thanks for reporting this.

    There should be a version or option to avoid this, but I have not looked at those functions in a long time.

    We might need to special case this and check for zeros on the diagonal.

    (I don't remember the details:
    Even with eigenvalue decomposition, there is likely a problem with eigen vectors of zeros, when we have a row/column of zeros. In that case just adjusting the eigenvalue would not be enough.
    Eigenvectors are normed. What's the result if the unnormed eigenvector is zeros plus floating point noise?
    )

  2. josef-pkt commented on Oct 22, 2025

    @josef-pkt
    Member

    The nearest functions work through the correlation matrix.
    The original intention was for applications where we need to fix the correlation coefficients. Variance was assumed to be correctly estimated.

    clip_evals which just forces non-negative eigenvalues, only get's a positive semi-definite.
    However, it works if we adjust the minimum required eigenvalue to, for example, 1e-8.

    cov_nearest would require that we enforce a strictly positive diagonal.
    I don't know which threshold would be a good default, maybe just imitate R.

    Aside clip_evals works by clipping the smallest eigenvalue away from negative, but does not take into account the condition number.
    We could require that the smallest eigenvalue is increased until the condition number is satisfied.
    However, that does not look good, because, AFAIR, the largest eigenvalues are upward biased in small samples.
    Here we are just enforcing positive (semi)-definiteness in a matrix, and not target a improved small sample shrinkage estimator of the variance.

    We can add an option to impose a minimum strictly positive value for diagonal elements.
    e.g. min_diag = 1e-8 or something smaller
    clip the diagonal and issue a warning if a diagonal element is below the min_diag threshold

    from statsmodels.stats.correlation_tools import clip_evals
    
    result = clip_evals(mat)
    print(result)
    (array([[2., 0.],
           [0., 0.]]), False)
    
    result = clip_evals(mat, value=1e-8)
    print(result)
    (array([[2.e+00, 0.e+00],
           [0.e+00, 1.e-08]]), False)
    
    mat = np.array([[2.0, 0.0], [0.0, 1e-8]])
    result = cov_nearest(mat)
    print(result)
    [[2.e+00 0.e+00]
     [0.e+00 1.e-08]]
    

    trying out some weird (?) cases
    maybe that does not look bad

    mat = np.array([[2.0, 1.0], [1.0, 1e-8]])
    result = cov_nearest(mat)
    print(result)
    [[2.00000000e+00 1.41421356e-04]
     [1.41421356e-04 1.00000000e-08]]
    
    mat = np.array([[2.0, 4.0], [4.0, 1e-8]])
    result = cov_nearest(mat)
    print(result)
    [[2.00000000e+00 1.41421356e-04]
     [1.41421356e-04 1.00000000e-08]]
    
    mat = np.array([[2.0, 0.0], [0.0, 1e-8]])
    result = cov_nearest(mat, method="nearest")
    print(result)
    [[2.e+00 0.e+00]
     [0.e+00 1.e-08]]
    
    mat = np.array([[2.0, 1.0], [1.0, 1e-8]])
    result = cov_nearest(mat, method="nearest")
    print(result)
    
    [[2.00000000e+00 1.41421356e-04]
     [1.41421356e-04 1.00000000e-08]]
    ...\statsmodels\stats\correlation_tools.py:89: IterationLimitWarning: 
    Maximum iteration reached.
      warnings.warn(iteration_limit_doc, IterationLimitWarning)
    
    ​
    mat = np.array([[2.0, 4.0], [4.0, 1e-8]])
    result = cov_nearest(mat, method="nearest")
    print(result)
    
    [[2.00000000e+00 1.41421356e-04]
     [1.41421356e-04 1.00000000e-08]]
    ...\statsmodels\stats\correlation_tools.py:89: IterationLimitWarning: 
    Maximum iteration reached.
      warnings.warn(iteration_limit_doc, IterationLimitWarning)
    

    more extreme:
    the current code also cannot fix a negative diagonal element

    mat = np.array([[2.0, 0.0], [0.0, -1e-8]])
    result = cov_nearest(mat)
    print(result)
    [[ 2. nan]
     [nan nan]]
    ...\statsmodels\stats\moment_helpers.py:251: RuntimeWarning: invalid value encountered in sqrt
      std_ = np.sqrt(np.diag(cov))
    
  3. josef-pkt commented on Oct 22, 2025

    @josef-pkt
    Member

    Aside:
    I don't remember if the original methods to enforce positive definiteness used the correlation matrix and not arbitrary symmetric square matrices, or whether conversion to correlation was added because our application was for fixing the correlation coefficients and not the variances.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions