web-dev-qa-db-ja.com

pythonで曲線を滑らかにする方法

エントロピー曲線(1d numpy array)がありますが、この曲線にはノイズがたくさんあります。スムージングでノイズを削除したいのですが。

これは私の曲線のプロットです: curve and noise

私はこの問題を解決して、カイザーベッセルフィルターを使用した畳み込み積を作成しようとしました。

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

numpy.convolve 演算子は「有効」モードで、オーバーラップの中央の要素を返しますが、この場合は空の要素を返します。

スムージングを適用する簡単な方法はありますか?

ありがとう!

10
elviuz

わかりました、解決しました。私は別のアプローチを使用しました: 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

結果は次のとおりです。

enter image description here

15
elviuz