Python使用scipy.signal.argrelextrema查找离散序列极值点
本文介绍利用Python中scipy.signal库的argrelextrema函数来高效查找离散序列中的极值点。通过示例代码展示如何定位局部极大值与极小值,并指出该函数在遇到连续相同数值时的识别局限,帮助用户在实际数据处理中合理应用此方法。
使用scipy.signal查找极值点
在Python中,可以使用scipy.signal模块提供的argrelextrema函数来便捷地查找离散序列中的极值点。该方法API简洁,易于实现。
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
import scipy.signal as signal
x=np.array([
0, 6, 25, 20, 15, 8, 15, 6, 0, 6, 0, -5, -15, -3, 4, 10, 8, 13, 8, 10, 3,
1, 20, 7, 3, 0 ])
plt.figure(figsize=(16,4))
plt.plot(np.arange(len(x)),x)
print x[signal.argrelextrema(x, np.greater)]
print signal.argrelextrema(x, np.greater)
plt.plot(signal.argrelextrema(x,np.greater)[0],x[signal.argrelextrema(x, np.greater)],'o')
plt.plot(signal.argrelextrema(-x,np.greater)[0],x[signal.argrelextrema(-x, np.greater)],'+')
# plt.plot(peakutils.index(-x),x[peakutils.index(-x)],'*')
plt.show()
[25 15 6 10 13 10 20]
(array([ 2, 6, 9, 15, 17, 19, 22]),)
函数局限性与注意事项
需要注意的是,当极值点附近存在左右相邻且数值相同的点时,该函数可能无法正确识别极值。不过,在实际应用场景中,这种情况较为罕见,因此通常可以忽略这一限制。
x=np.array([
0, 15, 15, 15, 15, 8, 15, 6, 0, 6, 0, -5, -15, -3, 4, 10, 8, 13, 8, 10, 3,
1, 20, 7, 3, 0 ])
plt.figure(figsize=(16,4))
plt.plot(np.arange(len(x)),x)
print x[signal.argrelextrema(x, np.greater)]
print signal.argrelextrema(x, np.greater)
plt.plot(signal.argrelextrema(x,np.greater)[0],x[signal.argrelextrema(x, np.greater)],'o')
plt.plot(signal.argrelextrema(x,np.less)[0],x[signal.argrelextrema(x, np.less)],'+')
plt.show()
[15 6 10 13 10 20]
(array([ 6, 9, 15, 17, 19, 22]),)
以上内容分享了利用Python查找离散序列极值点的方法,希望能为读者提供有价值的参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









