我使用numpy.cov创建从超过400的时间序列的数据集的协方差矩阵。 使用linalg.det给了我零值,矩阵是奇异的。 我可以用linalg.svd地看到,排名比列数少两个协方差矩阵中我有一些线性组合,使基质退化这样的地方。 我已经使用corrcoef对标的时间序列,但没有相关性> 0.78所以不会有明显的。 有人建议的方法来确定退化列的位置。 谢谢。
Answer 1:
如果取QR
矩阵的分解A
,的列R
与沿对角线对应的到线性独立的列的非零值A
。
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
。
文章来源: How to find degenerate rows/columns in a covariance matrix