python numpy argmax到多维数组中的最大值

标签 python numpy multidimensional-array max argmax

我有以下代码:

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

即我沿 axis=2 取 argmax,它给了我一个 (10,10) 矩阵。现在,我想为这些索引分配值 0。为此,我想索引示例数组。我试过:

max_values = sample[argmax_indices]

但它不起作用。我想要类似的东西

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

我只是通过检查 max_values - np.max(sample, axis=2) 应该给出形状为 (10,10) 的零矩阵来进行验证。 任何帮助将不胜感激。

最佳答案

这是一种方法-

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

分步运行示例

1) 示例输入数组:

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) 获取沿 axis=2 的 argmax 索引:

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

3) 获取用于索引到前两个 dims 的形状和数组:

In [264]: m,n = a.shape[:2]

In [265]: I,J = np.ogrid[:m,:n]

4) 使用 I、J 和 idx 进行索引,使用 advanced-indexing 存储最大值:

In [267]: max_values = a[I,J,idx]

In [268]: max_values
Out[268]: 
array([[8, 7],
       [8, 6]])

5) 验证我们在从 max_values 中减去 np.max(a,axis=2) 后得到一个全 zeros 数组:

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

6) 再次使用 advanced-indexing 将这些位置分配为 zeros 并进行更多级别的视觉验证:

In [269]: a[I,J,idx] = 0

In [270]: a
Out[270]: 
array([[[0, 4, 6], # <=== Compare this against the original version
        [0, 6, 2]],

       [[1, 0, 1],
        [4, 0, 4]]])

关于python numpy argmax到多维数组中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519475/

相关文章:

python - 在 python 3.4 中排序文件路径

python - 通过 Python 打开一个新的 AutoCAD 实例

python - 无法使用 numpy 将值分配给 'double slice'

python - 如何仅展平numpy数组的某些维度

python - Pip 没有安装 python 3.7.3 即使我在安装时选择了它

python - 如何在 Python 3 中使用 cmp()?

python - 值相等时的 numpy argmax

php - 如何将平面数组排序为多维树

arrays - 二维数组连续元素算法

Javascript - 如何连接两个不同大小的数组中的字符串值?