减少的最大值的 Numpy 索引 - numpy.argmax.reduceat [英] Numpy index of the maximum with reduction - numpy.argmax.reduceat

查看:57
本文介绍了减少的最大值的 Numpy 索引 - numpy.argmax.reduceat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个平面数组 b:

a = numpy.array([0, 1, 1, 2, 3, 1, 2])

还有一个索引数组 c 标记每个块"的开始:

And an array c of indices marking the start of each "chunk":

b = numpy.array([0, 4])

我知道我可以使用减少找到每个块"中的最大值:

I know I can find the maximum in each "chunk" using a reduction:

m = numpy.maximum.reduceat(a,b)
>>> array([2, 3], dtype=int32)

但是...有没有办法在一个块</edit>中找到最大的索引(比如numpy.argmax),带有矢量化操作(无列表、循环)?

But... Is there a way to find the index of the maximum <edit>within a chunk</edit> (like numpy.argmax), with vectorized operations (no lists, loops)?

推荐答案

借鉴这篇文章的想法.

涉及的步骤:

  • 按限制偏移量偏移组中的所有元素.对它们进行全局排序,从而限制每个组停留在它们的位置,但对每个组内的元素进行排序.

  • Offset all elements in a group by a limit-offset. Sort them globally, thus limiting each group to stay at their positions, but sorting the elements within each group.

在已排序的数组中,我们将查找最后一个元素,即组最大值.它们的索引将是针对组长度向下偏移后的 argmax.

In the sorted array, we would look for the last element, which would be the group max. Their indices would be the argmax after offsetting down for the group lengths.

因此,矢量化实现将是 -

Thus, a vectorized implementation would be -

def numpy_argmax_reduceat(a, b):
    n = a.max()+1  # limit-offset
    grp_count = np.append(b[1:] - b[:-1], a.size - b[-1])
    shift = n*np.repeat(np.arange(grp_count.size), grp_count)
    sortidx = (a+shift).argsort()
    grp_shifted_argmax = np.append(b[1:],a.size)-1
    return sortidx[grp_shifted_argmax] - b

作为一个微小的调整,可能会更快,我们可以使用 cumsum 或者创建 shift 并因此有早期方法的变体,就像这样 -

As a minor tweak and possibly faster one, we could alternatively create shift with cumsum and thus have a variation of the earlier approach, like so -

def numpy_argmax_reduceat_v2(a, b):
    n = a.max()+1  # limit-offset
    id_arr = np.zeros(a.size,dtype=int)
    id_arr[b[1:]] = 1
    shift = n*id_arr.cumsum()
    sortidx = (a+shift).argsort()
    grp_shifted_argmax = np.append(b[1:],a.size)-1
    return sortidx[grp_shifted_argmax] - b

这篇关于减少的最大值的 Numpy 索引 - numpy.argmax.reduceat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆