【问题标题】:How to find indices of local maximum in a 2d array (matrix)?如何在二维数组(矩阵)中找到局部最大值的索引?
【发布时间】:2021-03-18 01:52:26
【问题描述】:

我创建了矩阵 x:

import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=(5, 5))

 x=array([[5, 0, 3, 3, 7],
   [9, 3, 5, 2, 4],
   [7, 6, 8, 8, 1],
   [6, 7, 7, 8, 1],
   [5, 9, 8, 9, 4]])

局部最大指数应该是这样的:

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

我尝试过类似以下代码的方法来找到局部最大值,但我越来越困惑,甚至没有接近结果。

for i in range(0,5):
A12=np.r_[ x[1:-1][i] > x[:-2][i] , False]
result12= np.where(A12 == False)
result12=np.asarray(result12)
A22=np.r_[ x[i][1:-1][i] < x[2:][i] , True]
result22= np.where(A22 == True)
result22=np.asarray(result22)
print(np.intersect1d(result12, result22))

【问题讨论】:

    标签: python numpy matrix multidimensional-array max


    【解决方案1】:

    here 上有一个方法。如果你检查它,我相信这会对你有所帮助。我想到的是你也可以把你的二维数组变成图像。像这样:

    import numpy as np
    import pandas as pd 
    import matplotlib.pyplot as plt
    
    np.random.seed(0)
    x = np.random.randint(10, size=(5, 5))
    plt.matshow(x)
    

    之后,您可以检查颜色以找到连贯性。你也可以试试这个:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    
    np.random.seed(0)
    a = np.random.randint(10, size=(5, 5))
    a += a[::-1,:]
    
    fig = plt.figure()
    ax2 = fig.add_subplot(122)
    # 'nearest' interpolation - faithful but blocky
    ax2.imshow(a, interpolation='nearest', cmap=cm.Greys_r)
    
    plt.show()
    

    输出将是: like this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2017-07-17
      相关资源
      最近更新 更多