协方差提供了两个变量或更多组变量之间的相关强度的度量。协方差矩阵元素Cij是xi和xj的协方差。元素Cii是xi的方差。
如果COV(xi,xj)= 0,则变量不相关
如果COV(xi,xj)> 0,则变量呈正相关
如果COV(xi,xj)>
用法:numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
参数:
m :[数组]一个1D或2D变量。变量是列
y :[数组]它具有与m相同的形式。
rowvar :[bool,可选]如果rowvar为True(默认值),则每一行代表一个变量,各列中具有观察值。否则,该关系将转置:
bias :默认规范化为False。如果偏差为True,则将数据点归一化。
ddof :如果不是“无”,则将覆盖由偏置隐含的默认值。请注意,即使同时指定了权重和权重,ddof = 1也会返回无偏估计。
fweights :fweight是整数频率权重的一维数组
aweights :aweight是观测向量权重的一维数组。
返回:返回ndarray协方差矩阵
范例1:
# Python code to demonstrate the
# use of numpy.cov
import numpy as np
x = np.array([[0, 3, 4], [1, 2, 4], [3, 4, 5]])
print(“Shape of array:\n”, np.shape(x))
print(“Covarinace matrix of x:\n”, np.cov(x))
输出:
Shape of array:
(3, 3)
Covarinace matrix of x:
[[ 4.33333333 2.83333333 2. ]
[ 2.83333333 2.33333333 1.5 ]
[ 2. 1.5 1. ]]
范例2:
# Python code to demonstrate the
# use of numpy.cov
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 columns
cov_mat = np.stack((x, y), axis = 0)
print(np.cov(cov_mat))
输出:
[[ 2.03629167 0.9313 ]
[ 0.9313 0.4498 ]]
范例3:
# Python code to demonstrate the
# use of numpy.cov
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]]