Get indices of N highest values โ€‹โ€‹in ndarray

Given a histogram of the form 100x100x100, I would like to find the 2 highest values โ€‹โ€‹a and b and their indices (a1, a2, a3) and (b1, b2, b3), such as:

hist[a1][a2][a3] = a hist[b1][b2][b3] = b 

We can easily get the maximum value with hist.max (), but how can we get the highest X values โ€‹โ€‹in ndarray?

I understand that np.argmax is usually used to extract indexes of values, but in this case:

 hist.argmax().shape = () # single value for i in range(3): hist.argmax(i).shape = (100, 100) 

How can I get form (3), a tuple with a single value for measurement?

+6
source share
3 answers

You can use numpy.argpartition for a smoothed version of the array to get the indices of the top k elements, and then you can convert these 1D indices according to the shape of the array using numpy.unravel_index :

 >>> arr = np.arange(100*100*100).reshape(100, 100, 100) >>> np.random.shuffle(arr) >>> indices = np.argpartition(arr.flatten(), -2)[-2:] >>> np.vstack(np.unravel_index(indices, arr.shape)).T array([[97, 99, 98], [97, 99, 99]]) ) >>> arr[97][99][98] 999998 >>> arr[97][99][99] 999999 
+11
source

You can use where :

 a=np.random.random((100,100,100)) np.where(a==a.max()) (array([46]), array([62]), array([61])) 

to get into one array:

 np.hstack(np.where(a==a.max())) array([46, 62, 61]) 

and since the OP requested the tuple:

 tuple(np.hstack(np.where(a==a.max()))) (46, 62, 61) 

EDIT:

To get the indices of the largest sets of N , you can use the nlargest function from the heapq module:

 N=3 np.where(a>=heapq.nlargest(3,a.flatten())[-1]) (array([46, 62, 61]), array([95, 85, 97]), array([70, 35, 2])) 
+2
source

I suppose you can do this:

(pseudo code)

 #work on a copy working_hist = copy(hist) greatest = [] min_value = hist.argmin().shape #while searching for the N greatest values, do N times for i in range(N): #get the current max value max_value = hist.argmax().shape #save it greatest.append(max_value) #and then replace it by the minimum value hist(max_value.shape)= min_value 

I have not used numpy for many years, so I'm not sure about the syntax. The code here is just to give you pseudo code like an answer.

If you also keep the position of the extracted value, you can avoid working with a copy of the element using the extracted data to restore the matrix at the end.

0
source

Source: https://habr.com/ru/post/977328/


All Articles