[英]Python: finding the covariance matrix of an Nx2 matrix
I'm trying to compute a covariance matrix for an Nx2 matrix called X by hand (I know that there is a cov() function, but I want to calculate it by hand). 我正在尝试手动计算一个称为X的Nx2矩阵的协方差矩阵(我知道有一个cov()函数,但我想手动计算它)。 The code I'm trying to implement is:
我正在尝试实现的代码是:
N=len(X)
S=numpy.zeros(2*2).reshape((2,2))
sumx=numpy.zeros(N*2).reshape((N,2))
b1=numpy.zeros(N*1).reshape((N,1))
b2=numpy.zeros(N*1).reshape((N,1))
for n in range(1,N):
for i in range(0,N):
b1[i]=(X[n,i]-mean(X[i,:]))
for j in range(0,2):
b2[j]=(X[n,j]-mean(X[:,j]))
btot=b1v*b2v
bsum=sum(btot)
S=bsum/(N-1)
print S
but this doesn't work! 但这不起作用! Sorry I am fairly new to python, so it may be a simple thing I am getting wrong.
抱歉,我是python的新手,所以我弄错了可能很简单。
The error throws up from saying 错误是从说出来的
b1[i]=(X[n,i]-mean(X[i,:]))
IndexError: index 2 is out of bounds for axis 1 with size 2
UPDATE: 更新:
Where X is along the lines of: X沿以下方向:
[[ 1.89235582e-01 1.91920908e+01]
[ 6.53377180e-02 1.78733112e+01]
[ 7.71620860e-02 1.79439764e+01]
[ 8.69048860e-02 1.80507024e+01]
[ 1.94832532e-01 1.85183166e+01]
[ 1.84917732e-01 1.86287646e+01]
...]
You're missing a closing parenthesis on the following line: 您在以下行上缺少右括号:
b1=(X[n,i]-mean(X[i,:])
Also on this line: 也在这行上:
b2=(X[n,j]-mean(X[:,j])
When you get syntax errors on a given line, it is often a good idea to look for unclosed delimiters (quotes, parentheses, braces, etc.) on the previous line. 当您在给定的行上遇到语法错误时,通常最好在前一行上查找未封闭的定界符(引号,括号,花括号等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.