[英]calculate histogram peaks in python
在 Python 中,如何計算直方圖的峰值?
我試過這個:
import numpy as np
from scipy.signal import argrelextrema
data = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 1, 2, 3, 4,
5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9,
12,
15, 16, 17, 18, 19, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24,]
h = np.histogram(data, bins=[0, 5, 10, 15, 20, 25])
hData = h[0]
peaks = argrelextrema(hData, np.greater)
但結果是:
(array([3]),)
我希望它能在 bin 0 和 bin 3 中找到峰值。
請注意,峰值跨度超過 1 個區間。 我不希望它將跨越 1 列以上的峰視為附加峰。
我願意接受另一種方式來獲得峰值。
筆記:
>>> h[0]
array([19, 15, 1, 10, 5])
>>>
在計算拓撲中,持久同源性的形式提供了“峰值”的定義,似乎可以滿足您的需求。 在一維情況下,峰值由下圖中的藍條表示:
好消息是這種方法不僅可以識別峰值,而且可以以自然的方式量化“重要性”。
一個簡單有效的實現(與排序數字一樣快)以及本博客文章中給出的上述答案的源材料: https : //www.sthu.org/blog/13-perstopology-peakdetection/index.html
我寫了一個簡單的函數:
def find_peaks(a):
x = np.array(a)
max = np.max(x)
lenght = len(a)
ret = []
for i in range(lenght):
ispeak = True
if i-1 > 0:
ispeak &= (x[i] > 1.8 * x[i-1])
if i+1 < lenght:
ispeak &= (x[i] > 1.8 * x[i+1])
ispeak &= (x[i] > 0.05 * max)
if ispeak:
ret.append(i)
return ret
我將峰值定義為大於相鄰值的 180% 且大於最大值的 5% 的值。 當然,您可以根據自己的喜好調整這些值,以便為您的問題找到最佳設置。
試試findpeaks
庫。
pip install findpeaks
# Your input data:
data = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,]
# import library
from findpeaks import findpeaks
# Find some peaks using the smoothing parameter.
fp = findpeaks(lookahead=1, interpolate=10)
# fit
results = fp.fit(data)
# Make plot
fp.plot()
# Results with respect to original input data.
results['df']
# Results based on interpolated smoothed data.
results['df_interp']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.