Skip to content
Related Articles

Related Articles

Improve Article

Compute the covariance matrix of two given NumPy arrays

  • Last Updated : 29 Aug, 2020

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.

Syntax: numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)

Example 1:

Python




import numpy as np
  
  
array1 = np.array([0, 1, 1])
array2 = np.array([2, 2, 1])
  
# Original array1
print(array1)
  
# Original array2
print(array2)
  
# Covariance matrix
print("\nCovariance matrix of the said arrays:\n",
      np.cov(array1, array2))

Output:

[0 1 1]
[2 2 1]

Covariance matrix of the said arrays:
 [[ 0.33333333 -0.16666667]
 [-0.16666667  0.33333333]]

Example 2:



Python




import numpy as np
  
  
array1 = np.array([2, 1, 1, 4])
array2 = np.array([2, 2, 1, 1])
  
# Original array1
print(array1)
  
# Original array2
print(array2)
  
# Covariance matrix
print("\nCovariance matrix of the said arrays:\n"
      np.cov(array1, array2))

Output:

[2 1 1 4]
[2 2 1 1]

Covariance matrix of the said arrays:
 [[ 2.         -0.33333333]
 [-0.33333333  0.33333333]]

Example 3:

Python




import numpy as np
  
  
array1 = np.array([1, 2])
array2 = np.array([1, 2])
  
# Original array1
print(array1)
  
# Original array2
print(array2)
  
# Covariance matrix
print("\nCovariance matrix of the said arrays:\n"
      np.cov(array1, array2))

Output

[1 2]
[1 2]

Covariance matrix of the said arrays:
 [[0.5 0.5]
 [0.5 0.5]]

Example 4:

Python




import numpy as np 
    
x = [1.23, 2.12, 3.34, 4.5
y = [2.56, 2.89, 3.76, 3.95
    
# find out covariance with respect 
# rows 
cov_mat = np.stack((x, y), axis = 1)  
    
print("shape of matrix x and y:"
      np.shape(cov_mat)) 
  
print("shape of covariance matrix:",
      np.shape(np.cov(cov_mat))) 
  
print(np.cov(cov_mat))

Output

shape of matrix x and y: (4, 2)
shape of covariance matrix: (4, 4)
[[ 0.88445  0.51205  0.2793  -0.36575]
 [ 0.51205  0.29645  0.1617  -0.21175]
 [ 0.2793   0.1617   0.0882  -0.1155 ]
 [-0.36575 -0.21175 -0.1155   0.15125]]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :