gpt4 book ai didi

python - 如何在 Numpy 中构建 argsecondmax

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:42 25 4
gpt4 key购买 nike

在 Numpy 中,argmax已经定义,但我需要 argsecondmax,它基本上是第二个最大值。我怎么能这样做,我有点困惑?

最佳答案

寻找第 N 个最大的指数

高效的可以使用 np.argparition跳过排序和简单的分区,当切片时会给我们所需的索引。我们还将其概括为沿指定轴找到第 N 最大的一个或全局一个(类似于 ndarray.argmax()),例如所以-

def argNmax(a, N, axis=None):
if axis is None:
return np.argpartition(a.ravel(), -N)[-N]
else:
return np.take(np.argpartition(a, -N, axis=axis), -N, axis=axis)

样本运行-

In [66]: a
Out[66]:
array([[908, 770, 258, 534],
[399, 376, 808, 750],
[655, 654, 825, 355]])

In [67]: argNmax(a, N=2, axis=0)
Out[67]: array([2, 2, 1, 0])

In [68]: argNmax(a, N=2, axis=1)
Out[68]: array([1, 3, 0])

In [69]: argNmax(a, N=2) # global second largest index
Out[69]: 10

寻找第 N 个最小索引

扩展它以找到沿轴或全局第 N 最小的,我们将有 -

def argNmin(a, N, axis=None):
if axis is None:
return np.argpartition(a.ravel(), N-1)[N-1]
else:
return np.take(np.argpartition(a, N-1, axis=axis), N-1, axis=axis)

样本运行-

In [105]: a
Out[105]:
array([[908, 770, 258, 534],
[399, 376, 808, 750],
[655, 654, 825, 355]])

In [106]: argNmin(a, N=2, axis=0)
Out[106]: array([2, 2, 1, 0])

In [107]: argNmin(a, N=2, axis=1)
Out[107]: array([3, 0, 1])

In [108]: argNmin(a, N=2)
Out[108]: 11

时间

@pythonic833's post 所示,给出使用 argpartition 相对于使用 argsort 进行实际排序的好处的观点。 ,这是对全局 argmax 版本的快速运行时测试 -

In [70]: a = np.random.randint(0,99999,(1000,1000))

In [72]: %timeit np.argsort(a)[-2] # @pythonic833's soln
10 loops, best of 3: 40.6 ms per loop

In [73]: %timeit argNmax(a, N=2)
100 loops, best of 3: 2.12 ms per loop

关于python - 如何在 Numpy 中构建 argsecondmax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49832185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com