有一个内置函数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()
另一个非常有用的参数是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()
np.greater
替换为 np.less
。 - Cleb如果您的原始数据存在噪声,那么使用统计方法是更可取的,因为不是所有的峰值都具有显著性。对于您的a
数组,一个可能的解决方案是使用双微分:
peaks = a[1:-1][np.diff(np.diff(a)) < 0]
# peaks = array([5, 3, 6])
>> 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])
如果您可以排除数组边缘的最大值,您总是可以通过检查以下内容来检查一个元素是否比其每个邻居都大:
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])
a
之间的差异很明显。对于图表数据,我倾向于从数据中减去平滑版本,并通过使用类似于中位数绝对偏差的统计显着峰值进行阈值处理。 - ebarr