原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.cov.html
校对:(虚位以待)
numpy.
cov
(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)[source]估计协方差矩阵,给定数据和权重。
协方差表示两个变量一起变化的水平。If we examine N-dimensional samples, , then the covariance matrix element is the covariance of and . 元素是的方差。
有关算法的概述,请参见注释。
参数: | m:array_like
y:array_like,可选
rowvar:bool,可选
bias:bool,可选
ddof:int,可选
fweights:array_like,int,可选
aweights:array_like,可选
|
---|---|
返回: | out:ndarray
|
也可以看看
corrcoef
笔记
Assume that the observations are in the columns of the observation array m and let f = fweights
and a = aweights
for brevity. 计算加权协方差的步骤如下:
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=1, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
注意,当a == 1
时,归一化因子v1 / (v1 ** 2 - ddof * v2) / t11>
转到1 / (np.sum(f) - t16 > ddof)
。
例子
考虑两个变量,和,它们完全相关,但方向相反:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
注意增加而减少。协方差矩阵清楚地表明:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
注意,示出和之间的相关性的元素是负的。
此外,请注意x和y是如何组合的:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.vstack((x,y))
>>> print(np.cov(X))
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print(np.cov(x, y))
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print(np.cov(x))
11.71