计算两个给定的NumPy数组的协方差矩阵
在NumPy中,借助numpy.cov()来计算两个给定数组的协方差矩阵。在这里,我们将传递两个数组,它将返回两个给定数组的协方差矩阵。
语法:
python
numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
示例 1:
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))
输出:
[0 1 1]
[2 2 1]
Covariance matrix of the said arrays:
[[ 0.33333333 -0.16666667]
[-0.16666667 0.33333333]]
示例 2:
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:
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:
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]]