Numpy: argmax over multiple axes without loop

You could do something like this – # 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 run – In [214]: … Read more

Preventing GCC from automatically using AVX and FMA instructions when compiled with -mavx and -mfma

What you want to do is compile different object files for each instruction set you are targeting. Then create a cpu dispatcher which asks CPUID for the available instruction set and then jumps to the appropriate version of the function. I already described this in several different questions and answers disable-avx2-functions-on-non-haswell-processors do-i-need-to-make-multiple-executables-for-targetting-different-instruction-set how-to-check-with-intel-intrinsics-if-avx-extensions-is-supported-by-the-cpu cpu-dispatcher-for-visual-studio-for-avx-and-sse create-separate-object-files-from-the-same-source-code-and-link-to-an-executable

Vectorizing `numpy.random.choice` for given 2D array of probabilities along an axis

Here’s one vectorized way to get the random indices per row, with a as the 2D array of probabilities – (a.cumsum(1) > np.random.rand(a.shape[0])[:,None]).argmax(1) Generalizing to cover both along the rows and columns for 2D array – def random_choice_prob_index(a, axis=1): r = np.expand_dims(np.random.rand(a.shape[1-axis]), axis=axis) return (a.cumsum(axis=axis) > r).argmax(axis=axis) Let’s verify with the given sample by running … Read more