支持加权协方差计算的Python包

11

有没有一个Python的统计包支持计算加权协方差(即每个观察值具有权重)?不幸的是,numpy.cov不支持权重。

最好在numpy/scipy框架下工作(即能够使用numpy数组加速计算)。

非常感谢!


尝试这个链接:http://www-pcmdi.llnl.gov/svn/repository/cdat/trunk/Packages/genutil/Lib/statistics.py - Brian Cain
@BrianCain:该链接导致 404 错误。 - Make42
https://github.com/CDAT/genutil/blob/master/Lib/statistics.py - Brian Cain
2个回答

6

stats 中,statsmodels 已经有了加权协方差的计算。

但我们仍然可以直接计算加权协方差:

# -*- coding: utf-8 -*-
"""descriptive statistic with case weights

Author: Josef Perktold
"""

import numpy as np
from statsmodels.stats.weightstats import DescrStatsW


np.random.seed(987467)
x = np.random.multivariate_normal([0, 1.], [[1., 0.5], [0.5, 1]], size=20)
weights = np.random.randint(1, 4, size=20)

xlong = np.repeat(x, weights, axis=0)

ds = DescrStatsW(x, weights=weights)

print 'cov statsmodels'
print ds.cov

self = ds  #alias to use copied expression
ds_cov = np.dot(self.weights * self.demeaned.T, self.demeaned) / self.sum_weights

print '\nddof=0'
print ds_cov
print np.cov(xlong.T, bias=1)

# calculating it directly
ds_cov0 = np.dot(self.weights * self.demeaned.T, self.demeaned) / \
              (self.sum_weights - 1)
print '\nddof=1'
print ds_cov0
print np.cov(xlong.T, bias=0)

这将打印:

cov  statsmodels
[[ 0.43671986  0.06551506]
 [ 0.06551506  0.66281218]]

ddof=0
[[ 0.43671986  0.06551506]
 [ 0.06551506  0.66281218]]
[[ 0.43671986  0.06551506]
 [ 0.06551506  0.66281218]]

ddof=1
[[ 0.44821249  0.06723914]
 [ 0.06723914  0.68025461]]
[[ 0.44821249  0.06723914]
 [ 0.06723914  0.68025461]]

编辑备注

最初的答案指出了statsmodels中的一个错误,目前已经修复。


看起来statsmodels的bug已经在2013年得到了修复(https://github.com/statsmodels/statsmodels/issues/370#issuecomment-15357376)。 - drevicko
@Mayou36 感谢您的编辑。我看到时它已经被拒绝了。我更新了我的答案以反映更正后的statsmodels版本。 - Josef
我认为这仅在我们将权重视为代表各自观察值的倍数的整数时才有效。例如,如果权重是小浮点数,总和为1或小于1,则无偏归一化无法正常工作。换句话说,权重类似于https://numpy.org/doc/stable/reference/generated/numpy.cov.html中的“fweights”,但不像numpy的cov中的“aweights”。 - Make42
freq_weights 不必是整数。自由度校正的唯一假设是 sum_weights 对应于观测值的数量或有效样本量。例如,在鲁棒回归中,完整权重选项为1,而异常值候选观测的权重小于1。例如,协方差或散布矩阵的 M 估计器。 - Josef
statsmodels不会重新缩放权重(与Stata相反)。因此,用户可以使用不同的缩放(sum_weights)来解释权重。 - Josef
然而,DescrStatsW 将权重视为 freq_weights,并且只有这种解释是被验证的。 - Josef

4
自1.10版本起,numpy.cov函数支持使用'aweights'参数进行加权协方差计算。

它还接受 fweights(类似于 statsmodel 的权重)。这应该是现在被接受的答案。 - Make42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接