脾气暴躁:argmax多轴无循环

Car*_*osH 4 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)
Run Code Online (Sandbox Code Playgroud)

在这里,我们将有:

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.]]
Run Code Online (Sandbox Code Playgroud)

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

我尝试使用np.apply_over_axes,但是我没有设法使它返回我想要的结果。

Div*_*kar 7

你可以做这样的事情-

# 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))
Run Code Online (Sandbox Code Playgroud)

样品运行-

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
Run Code Online (Sandbox Code Playgroud)