scipy.linalg.eig return complex eigenvalues for covariance matrix?

后端 未结 2 1469
说谎
说谎 2021-01-04 00:11

The eigenvalues of a covariance matrix should be real and non-negative because covariance matrices are symmetric and semi positive definite.

However, take a look at

相关标签:
2条回答
  • 2021-01-04 00:19

    What you are experiencing is numerical instability due to limitations on floating point precision.

    Note that:

    (1) MATLAB also returned negative values, but the printing format is set to short and you don't see the full precision of the double stored in memory. Use format long g for printing more decimals

    (2) All imaginary parts returned by numpy's linalg.eig are close to the machine precision. Thus you should consider them zero.

    0 讨论(0)
  • 2021-01-04 00:25

    You have raised two issues:

    1. The eigenvalues returned by scipy.linalg.eig are not real.
    2. Some of the eigenvalues are negative.

    Both of these issues are the result of errors introduced by truncation and rounding errors, which always happen with iterative algorithms using floating-point arithmetic. Note that the Matlab results also produced negative eigenvalues.

    Now, for a more interesting aspect of the issue: why is Matlab's result real, whereas SciPy's result has some complex components?

    Matlab's eig detects if the input matrix is real symmetric or Hermitian and uses Cholesky factorization when it is. See the description of the chol argument in the eig documentation. This is not done automatically in SciPy.

    If you want to use an algorithm that exploits the structure of a real symmetric or Hermitian matrix, use scipy.linalg.eigh. For the example in the question:

    >>> eigh(C, eigvals_only=True)
    array([ -3.73825923e-17,  -1.60154836e-17,   8.11704449e-19,
             3.65055777e-17,   7.90175615e-01])
    

    This result is the same as Matlab's, if you round to the same number of digits of precision that Matlab printed.

    0 讨论(0)
提交回复
热议问题