ngy找到argmax指向的最大值

时间:2018-03-20 13:13:46

标签: numpy

我有一个三维数组。我使用argmax找到沿轴的最大值索引。我现在如何使用这些索引来获取最大值? 第二部分:如何对N-d阵列进行此操作?

例如:

u = np.arange(12).reshape(3,4,1)

In [125]: e = u.argmax(axis=2)
Out[130]: e
array([[0, 0, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 0]])

如果你[e]产生预期的结果会很好,但它不起作用。

2 个答案:

答案 0 :(得分:1)

argmax沿轴的返回值不能简单地用作索引。它仅适用于1d情况。

In [124]: u = np.arange(12).reshape(3,4,1)
In [125]: e = u.argmax(axis=2)
In [126]: u.shape
Out[126]: (3, 4, 1)
In [127]: e.shape
Out[127]: (3, 4)

e是(3,4),但其值仅索引u的最后一个维度。

In [128]: u[e].shape
Out[128]: (3, 4, 4, 1)

相反,我们必须为其他2个维度构建索引,这些维度使用e进行广播。例如:

In [129]: I,J=np.ix_(range(3),range(4))
In [130]: I
Out[130]: 
array([[0],
       [1],
       [2]])
In [131]: J
Out[131]: array([[0, 1, 2, 3]])

那些是(3,1)和(1,4)。这些与(3,4)e和所需的输出

兼容
In [132]: u[I,J,e]
Out[132]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

之前已经提出过这种问题,因此可能应该标记为重复。您的最后一个维度是大小1,因此e全部为0,这会让读者分散注意力(使用多维argmax作为索引)。

numpy: how to get a max from an argmax result

Get indices of numpy.argmax elements over an axis

假设你已经在最后一个维度上采用了argmax

In [156]: ij = np.indices(u.shape[:-1])
In [157]: u[(*ij,e)]
Out[157]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

或:

ij = np.ix_(*[range(i) for i in u.shape[:-1]])

如果轴位于中间,则需要更多的元组摆设ij元素和e

答案 1 :(得分:0)

所以对于一般的N-d数组

dims = np.ix_(*[range(x) for x in u.shape[:-1]])
u.__getitem__((*dims,e))

你不能写你[* dims,e],这是一个语法错误,所以我认为你必须直接使用 getitem