简体   繁体   English

NumPy中的加权标准差

[英]Weighted standard deviation in NumPy

numpy.average() has a weights option, but numpy.std() does not. numpy.average()具有权重选项,但numpy.std()没有。 Does anyone have suggestions for a workaround? 有没有人建议解决方法?

How about the following short "manual calculation"? 以下简短的“手动计算”如何?

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))

There is a class in statsmodels that makes it easy to calculate weighted statistics: statsmodels.stats.weightstats.DescrStatsW . statsmodels中有一类可以轻松计算加权统计信息: statsmodels.stats.weightstats.DescrStatsW

Assuming this dataset and weights: 假设此数据集和权重:

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

You initialize the class (note that you have to pass in the correction factor, the delta degrees of freedom at this point): 初始化类(请注意,此时您必须输入校正因子,即自由度增量):

weighted_stats = DescrStatsW(array, weights=weights, ddof=0)

Then you can calculate: 然后,您可以计算:

  • .mean the weighted mean : .mean 加权平均值

     >>> weighted_stats.mean 1.97196261682243 
  • .std the weighted standard deviation : .std 加权标准偏差

     >>> weighted_stats.std 0.21434289609681711 
  • .var the weighted variance : .var 加权方差

     >>> weighted_stats.var 0.045942877107170932 
  • .std_mean the standard error of weighted mean: .std_mean加权平均值的标准误差

     >>> weighted_stats.std_mean 0.020818822467555047 

    Just in case you're interested in the relation between the standard error and the standard deviation: The standard error is (for ddof == 0 ) calculated as the weighted standard deviation divided by the square root of the sum of the weights minus 1 ( corresponding source for statsmodels version 0.9 on GitHub ): 以防万一您对标准误差和标准偏差之间的关系感兴趣:标准误差是(对于ddof == 0 ),计算方法是:将加权标准偏差除以权重总和的平方根减去1( GitHub上statsmodels版本0.9的相应来源 ):

     standard_error = standard_deviation / sqrt(sum(weights) - 1) 

这里还有一个选择:

np.sqrt(np.cov(values, aweights=weights))

There doesn't appear to be such a function in numpy/scipy yet, but there is a ticket proposing this added functionality. 在numpy / scipy中似乎还没有这样的功能,但是有一张票证提出了这个附加功能。 Included there you will find Statistics.py which implements weighted standard deviations. 在那里,您将找到Statistics.py ,它实现了加权标准差。

There is a very good example proposed by gaborous : 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

Correct equation for weighted unbiased sample covariance, URL (version: 2016-06-28) 加权无偏样本协方差的正确方程式,URL(版本:2016-06-28)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM