是否有支持加權協方差計算的python統計軟件包(即每個觀察值都有權重)?不幸numpy.cov不支持重量。支持加權協方差計算的Python軟件包
最好在numpy/scipy框架下工作(即能夠使用numpy數組來加速計算)。
非常感謝!
是否有支持加權協方差計算的python統計軟件包(即每個觀察值都有權重)?不幸numpy.cov不支持重量。支持加權協方差計算的Python軟件包
最好在numpy/scipy框架下工作(即能夠使用numpy數組來加速計算)。
非常感謝!
statsmodels在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]]
編者按
最初的答案已經statsmodels指出的錯誤在此期間固定。
看起來像statsmodels錯誤[在2013年修復](https://github.com/statsmodels/statsmodels/issues/370#issuecomment-15357376)。 – drevicko 2016-09-02 13:36:12
@ Mayou36感謝您的編輯。當我看到它時,它已經被拒絕了。我更新了我的答案以反映修正的statsmodels版本 – user333700 2016-10-18 19:10:01
http://www-pcmdi.llnl.gov/svn/repository/cdat/trunk/Packages/genutil/Lib/statistics.py - 試試那個? – 2012-07-12 00:47:44
statsmodels幾乎擁有它 – user333700 2012-07-12 21:05:47