numpy:如何从argmax结果中获得最大值

时间:2016-11-01 09:33:21

标签: python numpy argmax

我有一个任意形状的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) 

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

3 个答案:

答案 0 :(得分:6)

您可以使用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]

答案 1 :(得分:0)

对于具有任意形状的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])

答案 2 :(得分:0)

对于任意形状的数组,下面的方法应该起作用:)

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))
相关问题