【问题标题】:Finding the max value in each row of 2-dim vector when there is multiple max value in one row in python当python中的一行中有多个最大值时,在2维向量的每一行中查找最大值
【发布时间】:2020-11-27 02:36:18
【问题描述】:

我正在寻找一种方法来查找 2-dim 向量的每一行中的最大值并将其索引保存在另一个向量中。我知道我可以用这段代码做到这一点:

    max_index = np.argmax(vec, axis=1)

现在我的问题是当一行有多个最大值时,它需要它的第一个索引。假设我们有这个矩阵:

vec = [[1, 0 ,1],
       [1, 2 ,3],
        [0, 5 ,5]]

所以我想在一行中有多个最大值时将最大值的索引替换为 -1。 最后 max_index 应该是这样的。

max_index = [-1, 2, -1]

提前致谢

【问题讨论】:

标签: python numpy vector


【解决方案1】:

技巧:从左右取argmax,检查它们是否重合:

L = np.argmax(vec,1)
R = np.argmax(vec[:,::-1],1)
np.where(L+R==len(vec[0])-1,L,-1)

# array([-1,  2, -1])

【讨论】:

    【解决方案2】:

    如果您最初的问题是找到多个最大值的最后一个索引,那么您可以遵循这些方法

    方法#1

    np.argmax((vec.max(axis=1)[...,None] == vec).cumsum(axis=1), axis=1)
    

    当一行中有重复的最大值时,将 -1 作为最后一个索引,将无法为类似 [[1,1,0]] 的行提供正确的索引。

    vec.max(axis=1)给出每行的最大值。

    vec.max(axis=1)[...,None]将其转换为二维数组。

    (vec.max(axis=1)[...,None] == vec) 将每行中的每个元素与每行中的最大值进行比较。

    (vec.max(axis=1)[...,None] == vec).cumsum(axis=1) 产生累积总和,其 argmax 给出最后一个最大值的索引。

    案例1:vec = [[1, 0 ,1], [1, 2 ,3], [0, 5 ,5]],结果将是: [2,2,2]

    案例2:vec = [[1, 1 ,0], [1, 2 ,3], [0, 5 ,5]],结果为:[1,2,2]

    方法#2

    R = np.argmax(vec[:,::-1],1) # Get the index of max from right side
    result = vec.shape[1]-1-R 
    

    在这里,我将列颠倒,然后取 argmax。之后我正在调整以获得正确的索引

    【讨论】:

      【解决方案3】:

      也许这可以解决您的问题:

      # Creating a copy of vec
      vec_without_max = np.copy(vec);
      
      # Remove the max values found before from the new copy
      for i in range(np.shape(vec)[0]):
          vec_without_max[i][max_index[i]] = np.iinfo(vec_without_max[i][max_index[i]].dtype).min
      
      # Find the max values on the copy array without the max values of vec
      max_index_again = np.argmax(vec_without_max, axis=1)
      
      # Compare the two arrays, if we have the same max value we set the max_index equals to -1
      for i in range(np.shape(vec)[0]):
          if vec[i][max_index[i]] == vec[i][max_index_again[i]]:
              max_index[i] = -1
      

      这个脚本返回

      max_index = [-1, 2, -1]
      

      对于您发布的示例,但它应该适用于任何维度的数组。

      【讨论】:

      • @Milad 但它使用for i in range... 很慢
      • 我认为如果一行只包含负值,这将失败。
      • @fountainhead 你是对的。根据示例,我假设它仅由正数组成。在负数的情况下,他只需要将vec_without_max[i][max_index[i]] = 0 替换为vec_without_max[i][max_index[i]] = np.iinfo(vec_without_max[i][max_index[i]].dtype).min
      • @falfab -- 好的。不错的努力。还有一件事——在涉及numpy 的问题中,尽量消除显式循环。当然,如何准确地避免循环会因情况而异。
      猜你喜欢
      • 1970-01-01
      • 2016-03-16
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      相关资源
      最近更新 更多