我是 Python 新手,想知道为什么 np.var(x) 给出的答案与 np.cov(x, y) 输出中找到的 cov(x,x) 值不同。它们不应该是一样的吗?我知道这与偏差或 ddof 有关,与标准化有关,但我不太确定这意味着什么,也找不到任何专门回答我的问题的资源。希望有人能帮忙!
最佳答案
在 numpy 中,cov 默认为“delta 自由度”1,而 var 默认为 ddof 0。从注释到 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.
因此,您可以通过以下方式让他们同意:
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 - 为什么 np.var(x) 和 np.cov(x, y) 给我不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170335/