반응형
NumPy의 가중 표준 편차
numpy.average()가중치 옵션이 있지만 numpy.std()그렇지 않습니다. 누구든지 해결 방법에 대한 제안이 있습니까?
다음의 짧은 "수동 계산"은 어떻습니까?
def weighted_avg_and_std(values, weights):
"""
Return the weighted average and standard deviation.
values, weights -- Numpy ndarrays with the same shape.
"""
average = numpy.average(values, weights=weights)
# Fast and numerically precise:
variance = numpy.average((values-average)**2, weights=weights)
return (average, math.sqrt(variance))
statsmodels가중 통계를 쉽게 계산할 수 있는 클래스가 statsmodels.stats.weightstats.DescrStatsW있습니다..
이 데이터 세트 및 가중치 가정 :
import numpy as np
from statsmodels.stats.weightstats import DescrStatsW
array = np.array([1,2,1,2,1,2,1,3])
weights = np.ones_like(array)
weights[3] = 100
클래스를 초기화합니다 ( 이 시점에서 수정 계수, 델타 자유도 를 전달해야합니다).
weighted_stats = DescrStatsW(array, weights=weights, ddof=0)
그런 다음 다음을 계산할 수 있습니다.
.mean가중 평균 :>>> weighted_stats.mean 1.97196261682243.std가중 된 표준 편차 :>>> weighted_stats.std 0.21434289609681711.var가중 분산 :>>> weighted_stats.var 0.045942877107170932-
>>> weighted_stats.std_mean 0.020818822467555047표준 오차와 표준 편차 사이의 관계에 관심이있는 경우 : 표준 오차는 (for
ddof == 0) 가중 표준 편차를 가중치 합계에서 1을 뺀 제곱근으로 나눈 값으로 계산됩니다 ( 버전의 해당 소스).statsmodels0.9 on GitHub ) :standard_error = standard_deviation / sqrt(sum(weights) - 1)
옵션이 하나 더 있습니다.
np.sqrt(np.cov(values, aweights=weights))
numpy / scipy에는 아직 이러한 기능이없는 것 같지만 이 추가 기능을 제안 하는 티켓 이 있습니다. 가중 표준 편차를 구현하는 Statistics.py 를 찾을 수 있습니다.
gaborous가 제안한 아주 좋은 예가 있습니다 .
import pandas as pd
import numpy as np
# X is the dataset, as a Pandas' DataFrame
mean = mean = np.ma.average(X, axis=0, weights=weights) # Computing the
weighted sample mean (fast, efficient and precise)
# Convert to a Pandas' Series (it's just aesthetic and more
# ergonomic; no difference in computed values)
mean = pd.Series(mean, index=list(X.keys()))
xm = X-mean # xm = X diff to mean
xm = xm.fillna(0) # fill NaN with 0 (because anyway a variance of 0 is
just void, but at least it keeps the other covariance's values computed
correctly))
sigma2 = 1./(w.sum()-1) * xm.mul(w, axis=0).T.dot(xm); # Compute the
unbiased weighted sample covariance
가중 편향되지 않은 샘플 공분산, URL에 대한 올바른 방정식 (버전 : 2016-06-28)
참고URL : https://stackoverflow.com/questions/2413522/weighted-standard-deviation-in-numpy
반응형
'Program Club' 카테고리의 다른 글
| Java, Apache Kafka에서 주제의 메시지 수를 얻는 방법 (0) | 2020.11.26 |
|---|---|
| Eclipse 내부 오류 "뉴스 피드 폴링" (0) | 2020.11.26 |
| 배열에서 for each 루프를 어떻게 사용할 수 있습니까? (0) | 2020.11.26 |
| postInvalidate ()는 무엇을합니까? (0) | 2020.11.26 |
| Rails : csrf_meta_tag는 어떻게 작동합니까? (0) | 2020.11.26 |