numpy协方差矩阵 [英] numpy covariance matrix

查看:211
本文介绍了numpy协方差矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个长度为25的向量,并且我想计算它们的协方差矩阵.我尝试使用numpy.cov进行此操作,但始终以2x2矩阵结尾.

Suppose I have two vectors of length 25, and I want to compute their covariance matrix. I try doing this with numpy.cov, but always end up with a 2x2 matrix.

>>> import numpy as np
>>> x=np.random.normal(size=25)
>>> y=np.random.normal(size=25)
>>> np.cov(x,y)
array([[ 0.77568388,  0.15568432],
       [ 0.15568432,  0.73839014]])

使用rowvar标志也无济于事-我得到的结果完全相同.

Using the rowvar flag doesn't help either - I get exactly the same result.

>>> np.cov(x,y,rowvar=0)
array([[ 0.77568388,  0.15568432],
       [ 0.15568432,  0.73839014]])

如何获取25x25的协方差矩阵?

How can I get the 25x25 covariance matrix?

推荐答案

您有两个向量,而不是25.我所用的计算机没有python,所以我无法对其进行测试,但是请尝试:

You have two vectors, not 25. The computer I'm on doesn't have python so I can't test this, but try:

z = zip(x,y)
np.cov(z)

当然....您真正想要的可能更像是:

Of course.... really what you want is probably more like:

n=100 # number of points in each vector
num_vects=25
vals=[]
for _ in range(num_vects):
    vals.append(np.random.normal(size=n))
np.cov(vals)

这采用了num_vects 1x n向量的协方差(我认为/希望)

This takes the covariance (I think/hope) of num_vects 1xn vectors

这篇关于numpy协方差矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆