6

我有以下代码:

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)来验证。任何帮助将不胜感激。

4

3 回答 3

9

这是一种方法 -

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

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)验证我们在减去后得到一个全zeros数组:np.max(a,axis=2)max_values

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]]])
于 2017-02-28T22:03:42.753 回答
2

的替代方案np.ogridnp.indices

I, J = np.indices(argmax_indices.shape)

sample[I,J,argmax_indices] = 0

于 2017-06-17T16:14:38.163 回答
0

这也可以推广到处理任何维度的矩阵。结果函数会将矩阵的每个 1-d 向量中的最大值沿所需的任何维度 d(在原始问题的情况下为维度 2)设置为 0(或任何所需的值):

def set_zero(sample, d, val):
    """Set all max value along dimension d in matrix sample to value val."""
    argmax_idxs = sample.argmax(d)
    idxs = [np.indices(argmax_idxs.shape)[j].flatten() for j in range(len(argmax_idxs.shape))]
    idxs.insert(d, argmax_idxs.flatten())
    sample[idxs] = val
    return sample

set_zero(sample, d=2, val=0)

(在 python 3.6.4 和 python 2.7.14 上测试了 numpy 1.14.1)

于 2018-03-07T17:11:40.963 回答