问题描述
我正在尝试弄清楚如何使用Python Numpy函数cov计算协方差.当我将其传递给两个一维数组时,我得到了一个2x2的结果矩阵.我不知道该怎么办.我不太擅长统计,但我相信在这种情况下的协方差应该是一个整数. 这是我想要的.我写了我自己的:
I am trying to figure out how to calculate covariance with the Python Numpy function cov. When I pass it two one-dimentional arrays, I get back a 2x2 matrix of results. I don't know what to do with that. I'm not great at statistics, but I believe covariance in such a situation should be a single number. This is what I am looking for. I wrote my own:
def cov(a, b):
if len(a) != len(b):
return
a_mean = np.mean(a)
b_mean = np.mean(b)
sum = 0
for i in range(0, len(a)):
sum += ((a[i] - a_mean) * (b[i] - b_mean))
return sum/(len(a)-1)
那行得通,但我认为Numpy版本要有效得多,如果我能弄清楚如何使用它的话.
That works, but I figure the Numpy version is much more efficient, if I could figure out how to use it.
有人知道如何使Numpy cov函数像我写的那样执行吗?
Does anybody know how to make the Numpy cov function perform like the one I wrote?
谢谢
戴夫
推荐答案
当a
和b
是一维序列时,numpy.cov(a,b)[0][1]
等同于您的cov(a,b)
.
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
np.cov(a,b)
返回的2x2数组的元素等于
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(其中cov
是您上面定义的功能.)
(where, again, cov
is the function you defined above.)
这篇关于用Python和Numpy计算协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!