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

2024-09-28 10:10:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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]

Tags: 数据方法数组pythonic峰值本质峰值检测
3条回答

如果原始数据是有噪声的,那么最好使用统计方法,因为并非所有的峰值都是显著的。对于您的a数组,可能的解决方案是使用双微分:

peaks = a[1:-1][np.diff(np.diff(a)) < 0]
# peaks = array([5, 3, 6])

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

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])

函数^{}中存在一个bulit,它完成了此任务:

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
maxInd = argrelextrema(a, np.greater)

# get the actual values using these indices
r = a[maxInd]  # 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

相关问题 更多 >

    热门问题