NumPy-计算直方图交集

时间:2018-09-05 11:38:31

标签: python numpy statistics histogram

以下数据代表2个给定的直方图,分为13个bin:

key 0   1-9 10-18   19-27   28-36   37-45   46-54   55-63   64-72   73-81   82-90   91-99   100
A   1.274580708 2.466224824 5.045757621 7.413716262 8.958855646 10.41325305 11.14150951 10.91949012 11.29095648 10.95054297 10.10976255 8.128781795 1.886568472
B   0   1.700493692 4.059243006 5.320899616 6.747120132 7.899067471 9.434997257 11.24520022 12.94569391 12.83598464 12.6165661  10.80636314 4.388370817

enter image description here

我正在尝试遵循this article,以便使用此方法来计算这两个直方图之间的交点:

def histogram_intersection(h1, h2, bins):
   bins = numpy.diff(bins)
   sm = 0
   for i in range(len(bins)):
       sm += min(bins[i]*h1[i], bins[i]*h2[i])
   return sm

由于我的数据已经被计算为直方图,因此我无法使用numpy内置函数,因此无法为该函数提供必要的数据。

如何处理我的数据以适合算法?

3 个答案:

答案 0 :(得分:3)

由于两个直方图的包子相同,因此可以使用:

def histogram_intersection(h1, h2):
    sm = 0
    for i in range(13):
        sm += min(h1[i], h2[i])
    return sm

答案 1 :(得分:1)

首先要注意的是:数据仓中的是范围,算法中的是数字。您必须为此重新定义垃圾箱。

此外,min(bins[i]*h1[i], bins[i]*h2[i])bins[i]*min(h1[i], h2[i]),因此可以通过以下方式获得结果:

hists=pandas.read_clipboard(index_col=0) # your data
bins=arange(-4,112,9)   #  try for bins but edges are different here
mins=hists.min('rows')
intersection=dot(mins,bins) 

答案 2 :(得分:0)

您可以使用Numpy更快,更简单地计算它:

#!/usr/bin/env python3

import numpy as np

A = np.array([1.274580708,2.466224824,5.045757621,7.413716262,8.958855646,10.41325305,11.14150951,10.91949012,11.29095648,10.95054297,10.10976255,8.128781795,1.886568472])
B = np.array([0,1.700493692,4.059243006,5.320899616,6.747120132,7.899067471,9.434997257,11.24520022,12.94569391,12.83598464,12.6165661,10.80636314,4.388370817])

def histogram_intersection(h1, h2):
    sm = 0
    for i in range(13):
        sm += min(h1[i], h2[i])
    return sm

print(histogram_intersection(A,B))
print(np.sum(np.minimum(A,B)))

输出

88.44792356099998
88.447923561

但是,如果您计时的话,Numpy只需要60%的时间:

%timeit histogram_intersection(A,B)
5.02 µs ± 65.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.sum(np.minimum(A,B))
3.22 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)