gpt4 book ai didi

python - 为什么 numpy cov 对角元素和 var 函数有不同的值?

转载 作者:太空狗 更新时间:2023-10-29 18:22:15 24 4
gpt4 key购买 nike

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

为什么会这样?我认为协方差矩阵对角线元素应该是序列的方差。

最佳答案

在 numpy 中,cov 默认为 1 的“delta degree of freedom”,而 var 默认为 0 的 ddof。从注释到 numpy。变种

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.

所以你可以通过以下方式让他们同意:

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

关于python - 为什么 numpy cov 对角元素和 var 函数有不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21030668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com