【问题标题】:python numpy argmax to max in multidimensional arraypython numpy argmax到多维数组中的最大值
【发布时间】:2017-02-28 21:55:11
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 为什么会这样?沿平面/轴最大化索引时的矩阵值应等于沿该平面的矩阵的最大值。不?或者 numpy 是否在 axis=2 的所有值上取最大值,而不管第 1 轴和第 2 轴是什么?
  • 让我换个方式问。我的阵列是 10x10x3。所以,对于每个 i(x-axis) 和 j(y-axis),我想要最好的 k(z-axis)。我想要它的索引以及价值。上面的方法不适合吗?
  • 对不起,我没听懂,但看起来你的索引是错误的,看看答案。

标签: python numpy multidimensional-array max argmax


【解决方案1】:

这是一种方法 -

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) 获取用于索引到前两个维度的形状和数组:

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]]])

【讨论】:

  • 非常感谢 :) 非常完美
【解决方案2】:

np.ogrid 的替代品是np.indices

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

sample[I,J,argmax_indices] = 0

【讨论】:

    【解决方案3】:

    这也可以推广到处理任何维度的矩阵。生成的函数会将矩阵的每个 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多