Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy covariance matrix

Tags:

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]]) 

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]]) 

How can I get the 25x25 covariance matrix?

like image 716
user13321 Avatar asked Feb 23 '13 02:02

user13321


People also ask

How do you find the covariance matrix in Numpy?

In NumPy for computing the covariance matrix of two given arrays with help of numpy. cov(). In this, we will pass the two arrays and it will return the covariance matrix of two given arrays.

How do you find the covariance of a matrix in Python?

covMatrix = np. cov(data,bias=True) # bias = True ,to get the population covarince matrix based on N. In the above example, we create a dataset with A, B, C columns using numpy library. To get the population covariance matrix (based on N)we had mentioned ,bias = True in cov() function.

How do you find the covariance of two random variables in Python?

Covariance between 2 random variables is calculated by taking the product of the difference between the value of each random variable and its mean, summing all the products, and finally dividing it by the number of values in the dataset.


2 Answers

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) 

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

like image 57
David Marx Avatar answered Sep 21 '22 08:09

David Marx


Try this:

import numpy as np x=np.random.normal(size=25) y=np.random.normal(size=25) z = np.vstack((x, y)) c = np.cov(z.T) 
like image 21
Sylou Avatar answered Sep 22 '22 08:09

Sylou