📜  计算两个给定 NumPy 数组的协方差矩阵

📅  最后修改于: 2022-05-13 01:54:25.625000             🧑  作者: Mango

计算两个给定 NumPy 数组的协方差矩阵

在 NumPy 中,借助 numpy.cov() 计算两个给定数组的协方差矩阵。在此,我们将传递两个数组,它将返回两个给定数组的协方差矩阵。

示例 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))


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


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


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


输出:

[0 1 1]
[2 2 1]

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

示例 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))

输出:

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

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

示例 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))

输出

[1 2]
[1 2]

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

示例 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))

输出

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