且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-13 17:21:24

在numpy中,cov的默认"delta***度"为1,而var的默认ddof为0. c2>

In numpy, cov defaults to a "delta degree of freedom" of 1 while var defaults to a ddof of 0. From the notes to numpy.var

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.

因此,您可以通过以下方式使他们同意:

So you can get them to agree by taking:

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