python numpy argmax to max in multidimensional array

2024/10/8 22:18:45

I have the following code:

import numpy as np
sample = np.random.random((10,10,3))
argmax_indices = np.argmax(sample, axis=2)

i.e. I take the argmax along axis=2 and it gives me a (10,10) matrix. Now, I want to assign these indices value 0. For this, I want to index the sample array. I tried:

max_values = sample[argmax_indices]

but it doesn't work. I want something like

max_values = sample[argmax_indices]
sample[argmax_indices] = 0

I simply validate by checking that max_values - np.max(sample, axis=2) should give a zero matrix of shape (10,10). Any help will be appreciated.

Answer

Here's one approach -

m,n = sample.shape[:2]
I,J = np.ogrid[:m,:n]
max_values = sample[I,J, argmax_indices]
sample[I,J, argmax_indices] = 0

Sample step-by-step run

1) Sample input array :

In [261]: a = np.random.randint(0,9,(2,2,3))In [262]: a
Out[262]: 
array([[[8, 4, 6],[7, 6, 2]],[[1, 8, 1],[4, 6, 4]]])

2) Get the argmax indices along axis=2 :

In [263]: idx = a.argmax(axis=2)

3) Get the shape and arrays for indexing into first two dims :

In [264]: m,n = a.shape[:2]In [265]: I,J = np.ogrid[:m,:n]

4) Index using I, J and idx for storing the max values using advanced-indexing :

In [267]: max_values = a[I,J,idx]In [268]: max_values
Out[268]: 
array([[8, 7],[8, 6]])

5) Verify that we are getting an all zeros array after subtracting np.max(a,axis=2) from max_values :

In [306]: max_values - np.max(a, axis=2)
Out[306]: 
array([[0, 0],[0, 0]])

6) Again using advanced-indexing assign those places as zeros and do one more level of visual verification :

In [269]: a[I,J,idx] = 0In [270]: a
Out[270]: 
array([[[0, 4, 6], # <=== Compare this against the original version[0, 6, 2]],[[1, 0, 1],[4, 0, 4]]])
https://en.xdnf.cn/q/70095.html

Related Q&A

Can Keras model.predict return a dictionary?

The documentation https://keras.io/models/model/#predict says that model.predict returns Numpy array(s) of predictions. In the Keras API, is there is a way to distinguishing which of these arrays are…

Flask OIDC: oauth2client.client.FlowExchangeError

The Problem: The library flask-oidc includes the scope parameter into the authorization-code/access-token exchange request, which unsurprisingly throws the following error:oauth2client.client.FlowExcha…

Cumulative count at a group level Python

I have a pandas dataframe like this : df = pd.DataFrame([[A, 1234, 20120201],[A, 1134, 20120201],[A, 1011, 20120201],[A, 1123, 20121004],[A, 1111, 20121004],[A, 1224, 20121105],[B, 1156, 20120403],[B, …

Easiest ways to generate graphs from Python? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Stripping python namespace attributes from an lxml.objectify.ObjectifiedElement [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:When using lxml, can the XML be rendered without namespace attributes? How can I strip the python attributes from an lxml…

matplotlib xkcd and black figure background

I am trying to make a plot using matplotlibs xkcd package while having a black background. However, xkcd seems to add a sort of white contour line around text and lines. On a white background you cant …

Python: Whats the difference between set.difference and set.difference_update?

s.difference(t) returns a new set with no elements in t.s.difference_update(t) returns an updated set with no elements in t.Whats the difference between these two set methods? Because the difference_u…

python telebot got unexpected response

I have been using my Telegram bot for sending me different notifications from my desktop computer using pythons telebot library. Everything was working properly for quite a long time, but one day it st…

How to set correct value for Django ROOT_URLCONF setting in different branches

Ive put site directory created by django-admin startproject under version control (Mercurial). Lets say, the site is called frobnicator.Now I want to make some serious refactoring, so I clone the site …

How do I improve scrapys download speed?

Im using scrapy to download pages from many different domains in parallel. I have hundreds of thousands of pages to download, so performance is important.Unfortunately, as Ive profiled scrapys speed, …