【问题标题】:Finding local extreme not working as expected in Scipy在 Scipy 中查找局部极端值无法按预期工作
【发布时间】:2019-07-19 04:34:54
【问题描述】:

我正在编写代码来查找类似于this stackoverflow 问题的信号梯度的局部最小值和最大值。我正在使用argrelextrema 来执行此操作。为了测试我的方法,我使用余弦函数实现了一个快速测试。

# Get the data
x = np.arange(start=0,
              stop=20,
              step=0.2)
y = np.cos(x)

# Calculate the gradient
gradient = []
for y1, y2 in zip(y, y[1:]):
    # Append the gradient (Delta Y / Delta X) where Delta X = 1
    gradient.append(y2-y1)

# Turn the gradient from a list to an array
gradient = np.array(gradient)

# Calculate the maximum points of the gradient
maxima = argrelextrema(gradient, np.greater_equal, order=2)
minima = argrelextrema(gradient, np.less_equal, order=2)

# Plot the original signal
plt.plot(x, y, label="Original Signal")
plt.scatter(x[maxima], y[maxima], color="red", label="Maxima")
plt.scatter(x[minima], y[minima], color="blue", label="Minima")
plt.title("Original Graph")
plt.legend(loc='lower left')
plt.show()

# Plot the gradient
plt.plot(gradient, label="First Derivative")
plt.scatter(maxima, gradient[maxima], color="red", label="Maxima")
plt.scatter(minima, gradient[minima], color="blue", label="Minima")
plt.title("1st Derivative Graph")
plt.legend(loc='lower left')
plt.show()

这给出了以下结果:

一切似乎都很好。但是,当我更改代码时:

x = [my data of 720 points]
y = [my data of 720 points some are np.inf]

Link to the data(另存为“.txt”文件)

我得到了如下所示的非常奇怪的结果:

起初,我认为这可能是由于argrelextrema 函数的order=2 参数或我的信号中的噪声。将order 更改为更大的窗口大小会减少找到的点数,包括数字滤波器也是如此。但是我还是不明白为什么它没有在梯度的峰值处找到最大值和最小值,而不是简单地沿着平坦区域?

注意: This question 与我的问题相反。

编辑:

将参数less_equal 更改为lessgreater_equal 更改为greater 也会删除沿平坦区域的许多点。虽然我还是很困惑为什么不选择梯度的最大值和最小值。

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    问题已解决!

    第一个问题是数据嘈杂。这意味着一直在找到最小值和最大值。你可以通过两种方式解决这个问题。首先,您可以应用过滤器来平滑线条:

    from scipy import ndimage
    
    # Filter the signal (to remove excess noise)
    scanner_readings = ndimage.gaussian_filter(data, sigma=3)
    

    另一种选择是增加argrelextremaargrelextrema 函数的窗口大小。

    # Calculate the maximum points of the gradient
    maxima = argrelextrema(gradient, np.greater_equal, order=4)
    minima = argrelextrema(gradient, np.less_equal, order=4)
    

    最后,argrelextremaargrelextrema 函数似乎不能很好地处理不连续性。为了解决这个问题,我将所有 inf 值替换为在本例中为 10 的最大值。您可以在下面看到我是如何做到的:

    # Remove discontinuity (10 is the max value in the data)
    data[data == np.inf] = 10
    

    当你这样做时,你会得到以下结果:

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 2019-07-03
      相关资源
      最近更新 更多