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



是否有支持加权协方差计算的python统计包(即,每个观测值都有一个权重)?不幸的是,numpy.cov不支持权重。

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

非常感谢!

统计模型在stats中具有加权协方差计算。

但我们仍然可以直接计算:

# -*- 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]]

编辑说明

最初的答案指出了统计模型中的一个错误,该错误在此期间已经修复。

由于版本1.10,numpy.cov确实支持使用"aweights"参数进行加权协方差计算。

最新更新