Python 为什么numpy cov对角元素和var函数有不同的值?
为什么会有这种行为?我认为协方差矩阵对角线元素应该是序列的方差 在numpy中,Python 为什么numpy cov对角元素和var函数有不同的值?,python,numpy,Python,Numpy,为什么会有这种行为?我认为协方差矩阵对角线元素应该是序列的方差 在numpy中,cov默认为“增量自由度”1,而var默认为ddof 0。从注释到numpy.var In [127]: x = np.arange(2) In [128]: np.cov(x,x) Out[128]: array([[ 0.5, 0.5], [ 0.5, 0.5]]) In [129]: x.var() Out[129]: 0.25 因此,您可以通过以下方式让他们同意: Notes ----
cov
默认为“增量自由度”1,而var
默认为ddof 0。从注释到numpy.var
In [127]: x = np.arange(2)
In [128]: np.cov(x,x)
Out[128]:
array([[ 0.5, 0.5],
[ 0.5, 0.5]])
In [129]: x.var()
Out[129]: 0.25
因此,您可以通过以下方式让他们同意:
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite population.
``ddof=0`` provides a maximum likelihood estimate of the variance for
normally distributed variables.
只需使用np.cov(x,x,bias=True)
即可获得相同的结果
解释可以在(和)比我更清楚的答案中找到:)还值得一提的是,基本上所有其他numpy函数都默认为
ddof=0
numpy.cov
是个例外,可能是因为历史原因。谢谢你们两位!这确实令人困惑。在excel中,我们有一个用于不同目的的总体版本和一个示例版本,这更清楚。
In [69]: cov(x,x)#defaulting to ddof=1
Out[69]:
array([[ 0.5, 0.5],
[ 0.5, 0.5]])
In [70]: x.var(ddof=1)
Out[70]: 0.5
In [71]: cov(x,x,ddof=0)
Out[71]:
array([[ 0.25, 0.25],
[ 0.25, 0.25]])
In [72]: x.var()#defaulting to ddof=0
Out[72]: 0.25