scipy 寻找局部极值并确保交替的最小值/最大值

dddzy1tm  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

我试图在Python中实现一些来自不同论文的算法,有些算法需要峰值/通过检测,其中局部最小值和最大值交替出现。当然,在模拟信号中应该始终是这种情况。
然而,当使用离散信号时,情况并不总是如此,正如您可以从这个简单的示例中看到的那样:

from scipy.signal import argrelmax,argrelmin,argrelextrema
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure("local extrema")
ax = fig.subplots()
x = range(0,10)
y = np.array([0,1,0,0,1,2,1,0,0,0])
local_minima, = list(argrelmin(np.array(y)))
local_maxima, = list(argrelmax(np.array(y)))
ax.plot(local_maxima, y[local_maxima],"x",color="orange")
ax.plot(local_minima, y[local_minima],"x",color="orange")
ax.plot(x,y)
plt.show()

我知道我可以调整argrelmax和argrelmin函数,但无论我做什么,它总是有缺陷。
这里只找到两个极大值。所以没有交替极值。
是否有一种方法可以自动检测极值并确保它们是交替的,或者我必须实现某种变通方法?(这方面的想法也很受欢迎)

txu3uszq

txu3uszq1#

我发现了一个我以前不幸忽视的解决方案。argrelmax、argrelmin和argrelextrema的问题在于它们难以检测平坦峰/峰值,因为有时它们使用np.greater_equal作为比较器(平坦峰的开始和结束)发现两个最大值,这导致非交替的最大值/最小值。
在Flows回答之后,我重新访问了scipy.signal中的find_peaks,我之前忽略了它,因为在前几句中它说:“通过简单比较相邻值来找到所有局部最大值”,所以我认为它和其他算法有同样的缺陷。
但实际上,它检测的是在峰值中间(向下舍入)只有一个索引的平坦峰值,无论表面上有多宽。
因此,这解决了我的问题,对于这个简单的情况:

from scipy.signal import argrelmax,argrelmin, argrelextrema, find_peaks
fig = plt.figure("local extrema")
ax = fig.subplots()
x = range(0,10)
y = np.array([0,1,0,0,1,2,1,0,0,0])
peaks,_ = find_peaks(y)
throughs,_ = find_peaks(np.negative(y))

local_maxima = list(peaks)
local_minima = list(throughs)

ax.plot(x,y)
ax.plot(local_maxima, y[local_maxima],"x",color="orange")
ax.plot(local_minima, y[local_minima],"x",color="orange")

plt.show()

正如你现在看到的,最小值被检测到了。
我将不得不看看它是否适用于我的真实的世界数据虽然,但我认为它应该。谢谢!

相关问题