如何在协方差矩阵中找到退化行/列

2024-04-29 01:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用numpy.cov公司从超过400个时间序列的数据集创建协方差矩阵。使用利纳格德特给我一个零值,所以矩阵是奇异的。我可以用利纳格公司为了看秩比列数少两个,所以在协方差矩阵的某个地方,我有一些线性组合,使矩阵退化。我在底层时间序列中使用了corrcoef,但没有相关性,因此不明显。有人能建议一种方法来确定退化列的位置吗。谢谢您。在


Tags: 数据方法numpy地方时间公司序列矩阵
1条回答
网友
1楼 · 发布于 2024-04-29 01:37:10

如果对矩阵A进行QR分解,则沿对角线具有非零值的{}列对应于{}的线性独立列。在


import numpy as np
linalg = np.linalg

def independent_columns(A, tol = 1e-05):
    """
    Return an array composed of independent columns of A.

    Note the answer may not be unique; this function returns one of many
    possible answers.

    http://stackoverflow.com/q/13312498/190597 (user1812712)
    http://math.stackexchange.com/a/199132/1140 (Gerry Myerson)
    http://mail.scipy.org/pipermail/numpy-discussion/2008-November/038705.html
        (Anne Archibald)

    >>> A = np.array([(2,4,1,3),(-1,-2,1,0),(0,0,2,2),(3,6,2,5)])
    >>> independent_columns(A)
    np.array([[1, 4],
              [2, 5],
              [3, 6]])
    """
    Q, R = linalg.qr(A)
    independent = np.where(np.abs(R.diagonal()) > tol)[0]
    return A[:, independent]

def matrixrank(A,tol=1e-8):
    """
    http://mail.scipy.org/pipermail/numpy-discussion/2008-February/031218.html
    """
    s = linalg.svd(A,compute_uv=0)
    return sum( np.where( s>tol, 1, 0 ) )


matrices = [
    np.array([(2,4,1,3),(-1,-2,1,0),(0,0,2,2),(3,6,2,5)]),
    np.array([(1,2,3),(2,4,6),(4,5,6)]).T,
    np.array([(1,2,3,1),(2,4,6,2),(4,5,6,3)]).T,
    np.array([(1,2,3,1),(2,4,6,3),(4,5,6,3)]).T,
    np.array([(1,2,3),(2,4,6),(4,5,6),(7,8,9)]).T
    ]

for A in matrices:
    B = independent_columns(A)
    assert matrixrank(A) == matrixrank(B) == B.shape[-1]

assert matrixrank(A) == matrixrank(B)检查independent_columns函数是否返回与A相同秩的矩阵。在

assert matrixrank(B) == B.shape[-1]检查B的列数是否等于B的列数。在

相关问题 更多 >