【问题标题】:NumPy - calculate histogram intersectionNumPy - 计算直方图交集
【发布时间】:2019-02-10 13:07:22
【问题描述】:

以下数据,表示 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

我正在尝试关注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 内置函数,所以我无法为函数提供必要的数据。

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

【问题讨论】:

  • 您显示的功能有什么问题?乍一看,对我来说已经足够了。
  • 该函数需要直方图方法生成的 bin。我只有直方图数据。
  • 直接np.minimum(A, B) 怎么样,因为 A 和 B 的 bin 相同?
  • 感谢回复,我试试看

标签: python numpy statistics histogram


【解决方案1】:

您可以使用 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)

【讨论】:

  • 我试图比较两个颜色直方图但得到这个错误 VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences(这是一个列表或元组的列表或元组或具有不同长度的 ndarray 或形状)已弃用。如果您打算这样做,则必须在创建 ndarray 时指定“dtype=object”。返回 np.sum(np.minimum(hist_1,hist_2))
【解决方案2】:

由于您可以使用两个直方图的相同数量的 bin:

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

【讨论】:

    【解决方案3】:

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

    另外,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) 
    

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 2017-10-24
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2015-09-07
      • 2020-12-05
      相关资源
      最近更新 更多