python - Numpy:没有循环的多轴上的argmax

标签 python numpy vectorization argmax

我有一个 N 维数组(名为 A)。对于 A 的第一轴的每一行,我想获得沿 A 的其他轴的最大值的坐标。然后我将返回一个二维数组,其中包含第一轴的每一行的最大值的坐标A.

我已经使用循环解决了我的问题,但我想知道是否有更有效的方法来执行此操作。我当前的解决方案(例如数组 A)如下:

import numpy as np

A=np.reshape(np.concatenate((np.arange(0,12),np.arange(0,-4,-1))),(4,2,2))
maxpos=np.empty(shape=(4,2))
for n in range(0, 4):
    maxpos[n,:]=np.unravel_index(np.argmax(A[n,:,:]), A[n,:,:].shape)

在这里,我们会:

A: 
[[[ 0  1]
  [ 2  3]]

 [[ 4  5]
  [ 6  7]]

 [[ 8  9]
  [10 11]]

 [[ 0 -1]
  [-2 -3]]]

maxpos:
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 0.  0.]]

如果有多个最大化器,我不介意选择哪个。

我尝试过使用 np.apply_over_axes,但我没能让它返回我想要的结果。

最佳答案

你可以这样做 -

# Reshape input array to a 2D array with rows being kept as with original array.
# Then, get idnices of max values along the columns.
max_idx = A.reshape(A.shape[0],-1).argmax(1)

# Get unravel indices corresponding to original shape of A
maxpos_vect = np.column_stack(np.unravel_index(max_idx, A[0,:,:].shape))

sample 运行-

In [214]: # Input array
     ...: A = np.random.rand(5,4,3,7,8)

In [215]: # Setup output array and use original loopy code
     ...: maxpos=np.empty(shape=(5,4)) # 4 because ndims in A is 5
     ...: for n in range(0, 5):
     ...:     maxpos[n,:]=np.unravel_index(np.argmax(A[n,:,:,:,:]), A[n,:,:,:,:].shape)
     ...:     

In [216]: # Proposed approach
     ...: max_idx = A.reshape(A.shape[0],-1).argmax(1)
     ...: maxpos_vect = np.column_stack(np.unravel_index(max_idx, A[0,:,:].shape))
     ...: 

In [219]: # Verify results
     ...: np.array_equal(maxpos.astype(int),maxpos_vect)
Out[219]: True

泛化到 n 维数组

我们可以概括求解 n-dim 数组以获得最后 N 轴的 argmax 结合这样的东西 -

def argmax_lastNaxes(A, N):
    s = A.shape
    new_shp = s[:-N] + (np.prod(s[-N:]),)
    max_idx = A.reshape(new_shp).argmax(-1)
    return np.unravel_index(max_idx, s[-N:])

结果将是索引数组的元组。如果您需要最终输出为数组,我们可以使用 np.stacknp.concatenate

关于python - Numpy:没有循环的多轴上的argmax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30589211/

相关文章:

python - 为什么这段代码不起作用?如何正确将元组列表转换为字典

python - 检查时间戳字符串是否在时间范围内

Python:矩阵的非对角线元素为0

python - 是否有计算部分和的 NumPy 函数?

multidimensional-array - 如何使用矢量化代码求解许多超定线性方程组?

python - 从 Scrapinghub 下载项目的源代码

python - Django 检查是否在基于类的 View 中的 super 用户

python - NumPy 数组元素的自定义排列

r - 在不同的上下文中, "vectorization"一词是否意味着不同的事物?

r - 查找字符串和长字符串向量之间的最小汉明距离(快速)