簡體   English   中英

如何在python中平滑曲線

[英]how to smooth a curve in python

我有一個熵曲線(1d numpy數組),但這條曲線有很多噪音。 我想用平滑刪除噪音。

這是我的曲線圖: 曲線和噪音

我試圖解決這個問題,使用Kaiser-Bessel過濾器制作卷積產品:

gaussian_curve = window_kaiser(windowLength, beta=20)  # kaiser filter
gaussian_curve = gaussian_curve / sum(gaussian_curve)

for i in range(0, windows_number):
     start = (i * step) + 1
     end = (i * step) + windowLength
     convolution[i] = (np.convolve(entropy[start:end + 1], gaussian_curve, mode='valid'))
     entropy[i] = convolution[i][0]

但此代碼返回此錯誤:

File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 822, in convolve
    raise ValueError('v cannot be empty')
ValueError: v cannot be empty

具有'valid'模式的numpy.convolve運算符返回重疊中的中心元素,但在這種情況下,返回一個空元素。

是否有一種簡單的方法來應用平滑?

謝謝!

好的,我解決了。 我使用了另一種方法: Savitzky-Golay過濾器

代碼:

def savitzky_golay(y, window_size, order, deriv=0, rate=1):

    import numpy as np
    from math import factorial

    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except ValueError, msg:
        raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order+1)
    half_window = (window_size -1) // 2
    # precompute coefficients
    b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
    m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
    lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve( m[::-1], y, mode='valid')

現在,我可以輸入:

entropy = np.array(entropy)
entropy = savitzky_golay(entropy, 51, 3) # window size 51, polynomial order 3

結果是這樣的:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM