【问题标题】:Standard deviation of binned values with `scipy.stats.binned_statistic`使用`scipy.stats.binned_statistic`的分箱值的标准偏差
【发布时间】:2018-08-06 10:15:21
【问题描述】:

当我根据scipy.stats.binned_statistic (see here for example) 对我的数据进行分箱时,如何获得平均分箱值的误差(即标准偏差)?

例如,如果我将我的数据分类如下:

windspeed = 8 * np.random.rand(500)
boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500)
bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
             boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
plt.figure()
plt.plot(windspeed, boatspeed, 'b.', label='raw data')
plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
        label='binned statistic of data')
plt.legend()

如何获得bin_means 的标准差?

【问题讨论】:

  • bin_means上的错误定义是什么?您可能应该在问题陈述中说明它是什么。
  • @RobertDodier,标准差就可以了。

标签: python statistics binning


【解决方案1】:

解决此问题的方法是从直方图构造概率密度估计(这只是适当地对直方图进行归一化的问题),然后计算标准差或估计密度的任何其他统计数据。

适当的归一化是使直方图下的面积为 1 所需的任何东西。至于计算密度估计的统计数据,从统计定义为integral(p(x)*f(x), x, -infinity, +infinity) 开始工作,用密度估计代替p(x)以及f(x) 需要的任何东西,例如xx^2 获取第一和第二时刻,从中计算方差,然后计算标准差。

我明天会发布一些公式,或者其他人想在此期间尝试一下。您也许可以查找一些公式,但我的建议是在求助之前始终尝试找出答案。

【讨论】:

    【解决方案2】:

    也许我回答得有点晚了,但我想知道如何做同样的事情并遇到了这个问题。我认为用stats.binned_statistic_2d 计算它应该是可能的,但我还没有弄清楚。现在我手动计算它,就像这样(注意,在我的代码中,我使用了固定数量的等距箱):

    windspeed = 8 * numpy.random.rand(500)
    boatspeed = .3 * windspeed**.5 + .2 * numpy.random.rand(500)
    bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
             boatspeed, statistic='median', bins=10)
    
    stds = []
    
    # Match each value to the bin number it belongs to
    pairs = zip(boatspeed, binnumber)
    
    # Calculate stdev for all elements inside each bin
    for n in list(set(binnumber)):  # Iterate over each bin
        in_bin = [x for x, nbin in pairs if nbin == n]  # Get all elements inside bin n
        stds.append(numpy.std(in_bin))
    
    # Calculate the locations of the bins' centers, for plotting
    bin_centers = []
    
    for i in range(len(bin_edges) -  1):
        center = bin_edges[i] + (float(bin_edges[i + 1]) - float(bin_edges[i]))/2.
        bin_centers.append(center)
    
    # Plot means
    pyplot.figure()
    pyplot.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
        label='binned statistic of data')
    
    # Plot stdev as vertical lines, probably can also be done with errorbar
    pyplot.vlines(bin_centers, bin_means - stds, bin_means + stds)
    
    pyplot.legend()
    pyplot.show()
    

    结果图(减去数据点):

    您必须小心处理垃圾箱。在我正在使用它的代码中,其中一个垃圾箱没有点,我必须相应地调整我对 stdev 的计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-27
      • 2013-03-11
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2015-11-10
      相关资源
      最近更新 更多