【问题标题】:How to find the indices of the maximum in each line, a concatenation of rows, in numpy?如何在numpy中找到每行中最大值的索引,行的连接?
【发布时间】:2019-07-10 16:55:43
【问题描述】:

我不知道这是否简单,或者之前是否有人问过。 (我搜索了但没有找到正确的方法。我找到了numpy.argmaxnumpy.amax但我无法正确使用它们。)

我有一个 numpy 数组(它是一个CxKxN 矩阵)如下(C=K=N=3):

array([[[1, 2, 3],
        [2, 1, 4],
        [4, 3, 3]],

       [[2, 1, 1],
        [1, 3, 1],
        [3, 4, 2]],

       [[5, 2, 1],
        [3, 3, 3],
        [4, 1, 2]]])

我想找到每行中最大元素的索引。一行是每个矩阵的三行 (C) 的串联。换句话说,i-th 行是第一个矩阵中的i-th 行、第二个矩阵中的i-th 行...的串联,直到i-th C-th 矩阵中的行。

比如第一行是

[1, 2, 3, 2, 1, 1, 5, 2, 1]

所以我想退货

[2, 0, 0] # the index of the maximum in the first line

[0, 1, 2] # the index of the maximum in the second line

[0, 2, 0] # the index of the maximum in the third line

[1, 2, 1] # the index of the maximum in the third line

[2, 2, 0] # the index of the maximum in the third line

现在,我正在尝试这个

np.argmax(a[:,0,:], axis=None) # for the first line

它返回6

np.argmax(a[:,1,:], axis=None) 

它返回2

np.argmax(a[:,2,:], axis=None) 

它返回0

但我可以将这些数字转换为 6 = (2,0,0) 等索引。

【问题讨论】:

  • 您想要的输出与实际不符。第二行是[2, 1, 4], [1, 3, 1], [3, 3, 3]。那你怎么得到[0, 1, 2]呢?这同样适用于所有其他 4 行。不清楚第二行是什么?你如何构建它?你总共有多少行?只有3个?你必须首先澄清所有这些问题。如果您将所有三个数组的第一行连接到一行,将所有三个数组的第二行连接到第二行,并将所有子数组的所有第三行连接到第三行,那么您总共只有三行。那你怎么得到 6 行呢?
  • [0,1,2] 因为4 在第一个3x3 矩阵中,所以它在这个矩阵的第二行,它在这个矩阵的第三列。 i-th 行是第一个矩阵中的 i-th 行、第二个矩阵中的 i-th 行 ...,直到 i-th 行的串联987654354@-th 矩阵。
  • 4有多个条目是什么?
  • 是的,我只有三行,我只是打印了领带(在第三行)。
  • 如果有平局,我可以任意选择任何一个。

标签: python numpy


【解决方案1】:

通过转置和重塑,我得到了你的“行”

In [367]: arr.transpose(1,0,2).reshape(3,9)
Out[367]: 
array([[1, 2, 3, 2, 1, 1, 5, 2, 1],
       [2, 1, 4, 1, 3, 1, 3, 3, 3],
       [4, 3, 3, 3, 4, 2, 4, 1, 2]])
In [368]: np.argmax(_, axis=1)
Out[368]: array([6, 2, 0])

这些最大值与您的相同。相同的索引,但在 (3,3) 数组中:

In [372]: np.unravel_index([6,2,0],(3,3))
Out[372]: (array([2, 0, 0]), array([0, 2, 0]))

将它们加入中间维度范围:

In [373]: tup = (_[0],np.arange(3),_[1])
In [374]: np.transpose(tup)
Out[374]: 
array([[2, 0, 0],
       [0, 1, 2],
       [0, 2, 0]])

【讨论】:

  • 一般CxKxN数组怎么做?
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 2020-10-14
  • 2019-05-09
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多