2012-07-11 5 views
9

가중치 공분산 계산을 지원하는 파이썬 통계 패키지가 있습니까 (즉, 각 관측에는 가중치가 있습니까?)? Unfortuantely numpy.cov는 가중치를 지원하지 않습니다.가중치 공분산 계산을 지원하는 Python 패키지

numpy/scipy 프레임 워크에서 작업하는 것이 좋습니다 (즉, 계산 속도를 높이기 위해 numpy 배열을 사용할 수 있음).

고마워요!

+0

http://www-pcmdi.llnl.gov/svn/repository/cdat/trunk/Packages/genutil/Lib/statistics.py - 그 중 하나를 시도해보십시오. –

+0

statsmodels 거의 있음 – user333700

답변

6

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의 버그를 지적

그동안 고정 됐어.

+0

statsmodels 버그가 [2013 년에 수정되었습니다]처럼 보입니다 (https://github.com/statsmodels/statsmodels/issues/370#issuecomment-15357376). – drevicko

+0

@ Mayou36 편집 해 주셔서 감사합니다. 그것은 내가 그것을 보았을 때 이미 거절당했습니다. 수정 된 통계 모델 버전을 반영하여 답변을 업데이트했습니다. – user333700