代码之家  ›  专栏  ›  技术社区  ›  GeoMonkey

在numpy数组中查找局部最大值

  •  13
  • GeoMonkey  · 技术社区  · 9 年前

    我正在寻找一些高斯平滑数据中的峰值。我已经研究了一些可用的峰值检测方法,但它们需要搜索的输入范围,我希望这比这更自动化。这些方法也适用于非平滑数据。由于我的数据已经平滑,我需要一种更简单的方法来检索峰值。我的原始数据和平滑数据如下图所示。

    enter image description here

    本质上,是否有一种从平滑数据数组中检索最大值的pythonic方法,以便

        a = [1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1]
    

    将返回:

        r = [5,3,6]
    
    4 回复  |  直到 9 年前
        1
  •  31
  •   Cleb    4 年前

    函数中存在bulit argrelextrema 完成这项任务:

    import numpy as np
    from scipy.signal import argrelextrema
        
    a = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
    
    # determine the indices of the local maxima
    max_ind = argrelextrema(a, np.greater)
    
    # get the actual values using these indices
    r = a[max_ind]  # array([5, 3, 6])
    

    这将为您提供所需的输出 r .

    从SciPy 1.1版开始,您还可以使用 find_peaks 。下面是两个取自文档本身的示例。

    使用 height 参数,可以选择高于某个阈值的所有最大值(在本例中,所有非负最大值;如果必须处理有噪声的基线,这可能非常有用;如果要找到最小值,只需将输入乘以 -1 ):

    import matplotlib.pyplot as plt
    from scipy.misc import electrocardiogram
    from scipy.signal import find_peaks
    import numpy as np
    
    x = electrocardiogram()[2000:4000]
    peaks, _ = find_peaks(x, height=0)
    plt.plot(x)
    plt.plot(peaks, x[peaks], "x")
    plt.plot(np.zeros_like(x), "--", color="gray")
    plt.show()
    

    enter image description here

    另一个非常有用的论点是 distance ,定义了两个峰值之间的最小距离:

    peaks, _ = find_peaks(x, distance=150)
    # difference between peaks is >= 150
    print(np.diff(peaks))
    # prints [186 180 177 171 177 169 167 164 158 162 172]
    
    plt.plot(x)
    plt.plot(peaks, x[peaks], "x")
    plt.show()
    

    enter image description here

        2
  •  2
  •   ebarr    9 年前

    如果原始数据有噪声,那么最好使用统计方法,因为不是所有的峰值都是显著的。为了您的 a 一种可能的解决方案是使用双差分:

    peaks = a[1:-1][np.diff(np.diff(a)) < 0]
    # peaks = array([5, 3, 6])
    
        3
  •  1
  •   CodeCode    4 年前
    >> import numpy as np
    >> from scipy.signal import argrelextrema
    >> a = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
    >> argrelextrema(a, np.greater)
    array([ 4, 10, 17]),)
    >> a[argrelextrema(a, np.greater)]
    array([5, 3, 6])
    

    如果您的输入表示有噪声的分布,您可以尝试 smoothing 它具有NumPy卷积函数。

        4
  •  0
  •   MSeifert    9 年前

    如果可以排除数组边缘的最大值,则可以始终通过检查来检查一个元素是否大于其每个相邻元素:

    import numpy as np
    array = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])
    # Check that it is bigger than either of it's neighbors exluding edges:
    max = (array[1:-1] > array[:-2]) & (array[1:-1] > array[2:])
    # Print these values
    print(array[1:-1][max])
    # Locations of the maxima
    print(np.arange(1, array.size-1)[max])