np.argmax on multidimensional arrays, keeping some indexes fixed

1k views Asked by At

I have a collection of 2D narrays, depending on two integer indexes, say p1 and p2, with each matrix of the same shape.

Then I need to find, for each pair (p1,p2), the maximum value of the matrix and the indexes of these maxima. A trivial, albeit slow, way to do this would would be to do something like this

import numpy as np
import itertools
range1=range(1,10)
range2=range(1,20)

for p1,p2 in itertools.product(range1,range1):
    mat=np.random.rand(10,10)
    index=np.unravel_index(mat.argmax(), mat.shape)
    m=mat[index]
    print m, index

For my application this is unfortunately too slow, I guess due to the usage of double for loops. Therefore I tried to pack everything in a 4-dimensional array (say BigMatrix), where the first two coordinates are the indexes p1,p2, and the other 2 are the coordinates of the matrices.

The np.amax command

    >>res=np.amax(BigMatrix,axis=(2,3))
    >>res.shape
         (10,20)
    >>res[p1,p2]==np.amax(BigMatrix[p1,p2,:,:])
         True

works as expected, as it loops through the 2 and 3 axis. How can I do the same for np.argmax? Please keep in mind that speed is important.

Thank you very much in advance,

Enzo

1

There are 1 answers

1
plonser On BEST ANSWER

This here works for me where Mat is the big matrix.

# flatten the 3 and 4 dimensions of Mat and obtain the 1d index for the maximum
# for each p1 and p2
index1d = np.argmax(Mat.reshape(Mat.shape[0],Mat.shape[1],-1),axis=2)

# compute the indices of the 3 and 4 dimensionality for all p1 and p2
index_x, index_y = np.unravel_index(index1d,Mat[0,0].shape)

# bring the indices into the right shape
index = np.array((index_x,index_y)).reshape(2,-1).transpose()

# get the maxima
max_val = np.amax(Mat,axis=(2,3)).reshape(-1)

# combine maxima and indices
sol = np.column_stack((max_val,index))

print sol