在numpy数组中查找局部最大值 [英] Find local maximums in numpy array

查看:94
本文介绍了在numpy数组中查找局部最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我拥有的一些高斯平滑数据中找到峰值.我已经查看了一些可用的峰值检测方法,但它们需要一个输入范围来搜索,我希望这比这更自动化.这些方法也是为非平滑数据设计的.由于我的数据已经平滑,我需要一种更简单的方法来检索峰值.我的原始数据和平滑数据如下图所示.

本质上,是否有一种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]

解决方案

存在一个内置函数

另一个非常有用的参数是distance,它定义了两个峰之间的最小距离:

peaks, _ = find_peaks(x, distance=150)# 峰值之间的差异是 >= 150打印(np.diff(峰值))# 打印 [186 180 177 171 177 169 167 164 158 162 172]plt.plot(x)plt.plot(peaks, x[peaks], x")plt.show()

I am looking to find the peaks in some gaussian smoothed data that I have. I have looked at some of the peak detection methods available but they require an input range over which to search and I want this to be more automated than that. These methods are also designed for non-smoothed data. As my data is already smoothed I require a much more simple way of retrieving the peaks. My raw and smoothed data is in the graph below.

Essentially, is there a pythonic way of retrieving the max values from the array of smoothed data such that an array like

    a = [1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1]

would return:

    r = [5,3,6]

解决方案

There exists a bulit-in function argrelextrema that gets this task done:

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

That gives you the desired output for r.

As of SciPy version 1.1, you can also use find_peaks. Below are two examples taken from the documentation itself.

Using the height argument, one can select all maxima above a certain threshold (in this example, all non-negative maxima; this can be very useful if one has to deal with a noisy baseline; if you want to find minima, just multiply you input by -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()

Another extremely helpful argument is distance, which defines the minimum distance between two peaks:

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

这篇关于在numpy数组中查找局部最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆