【问题标题】:numpy: how to get a max from an argmax resultnumpy:如何从 argmax 结果中获取最大值
【发布时间】:2016-11-01 09:33:21
【问题描述】:

我有一个任意形状的 numpy 数组,例如:

a = array([[[ 1,  2],
            [ 3,  4],
            [ 8,  6]],

          [[ 7,  8],
           [ 9,  8],
           [ 3, 12]]])
a.shape = (2, 3, 2)

最后一个轴上 argmax 的结果:

np.argmax(a, axis=-1) = array([[1, 1, 0],
                               [1, 0, 1]])

我想得到最大值:

np.max(a, axis=-1) = array([[ 2,  4,  8],
                            [ 8,  9, 12]])

但无需重新计算所有内容。我试过了:

a[np.arange(len(a)), np.argmax(a, axis=-1)]

但是得到了:

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,3) 

怎么做?二维的类似问题:numpy 2d array max/argmax

【问题讨论】:

  • 什么是reshape_x?
  • 对不起,应该是a。现在更正。

标签: python numpy argmax


【解决方案1】:

你可以使用advanced indexing -

In [17]: a
Out[17]: 
array([[[ 1,  2],
        [ 3,  4],
        [ 8,  6]],

       [[ 7,  8],
        [ 9,  8],
        [ 3, 12]]])

In [18]: idx = a.argmax(axis=-1)

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

In [20]: a[np.arange(m)[:,None],np.arange(n),idx]
Out[20]: 
array([[ 2,  4,  8],
       [ 8,  9, 12]])

对于任意维数的通用 ndarray 情况,如 comments by @hpaulj 中所述,我们可以使用 np.ix_,就像这样 -

shp = np.array(a.shape)
dim_idx = list(np.ix_(*[np.arange(i) for i in shp[:-1]]))
dim_idx.append(idx)
out = a[dim_idx]

【讨论】:

  • 好的,但是如何使用任意形状的数组而不是 3 维数组呢?
  • 使用np.xi_ 和元组连接idx 生成第一个维度。
  • @hpaulj 谢谢,应该这样做!用那个更新了帖子。
  • 谢谢。某处有错字吗?看来dims 没有使用。
  • @sygi 对不起,尝试了一些东西,最后不需要。删除了那行。
【解决方案2】:

对于具有任意形状的 ndarray,您可以将 argmax 索引展平,然后恢复正确的形状,如下所示:

idx = np.argmax(a, axis=-1)
flat_idx = np.arange(a.size, step=a.shape[-1]) + idx.ravel()
maximum = a.ravel()[flat_idx].reshape(*a.shape[:-1])

【讨论】:

    【解决方案3】:

    对于任意形状的数组,以下应该可以工作:)

    a = np.arange(5 * 4 * 3).reshape((5,4,3))
    
    # for last axis
    argmax = a.argmax(axis=-1)
    a[tuple(np.indices(a.shape[:-1])) + (argmax,)]
    
    # for other axis (eg. axis=1)
    argmax = a.argmax(axis=1)
    idx = list(np.indices(a.shape[:1]+a.shape[2:]))
    idx[1:1] = [argmax]
    a[tuple(idx)]
    

    a = np.arange(5 * 4 * 3).reshape((5,4,3))
    
    argmax = a.argmax(axis=0)
    np.choose(argmax, np.moveaxis(a, 0, 0))
    
    argmax = a.argmax(axis=1)
    np.choose(argmax, np.moveaxis(a, 1, 0))
    
    argmax = a.argmax(axis=2)
    np.choose(argmax, np.moveaxis(a, 2, 0))
    
    argmax = a.argmax(axis=-1)
    np.choose(argmax, np.moveaxis(a, -1, 0))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多