python - 为什么 np.var(x) 和 np.cov(x, y) 给我不同的值?

标签 python python-3.x numpy

我是 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/

相关文章:

python-2.7 - Python从数据中删除异常值

python - 读取位级别的二进制数据

python - 如何从 Pandas 数据框中的当前行中减去前一行并将其应用于每一行;不使用循环?

python - Flask 在 try catch 运行时错误后无法引发 HTTP 异常

python - 在python中打开文本文件作为数组或列表列表

python - 使用正则表达式的 Django 过滤器

Python 3 : Convert String to variable

python - 加载经过训练的 Keras 模型并继续训练

python - 链的节点中的每个值都是由前一个值加上前一个值的数字之和计算得出的

python - 使用 Regex Python 计算一行中的三个字母首字母缩略词