Savitzky-Golay 滤波在 1D 中给出不正确的导数

Savitzky-Golay filtering giving incorrect derivative in 1D

我有一个 x 和 y 数据集,x 作为自变量,y 作为因变量。

y=2x


我向 'y' 添加了一些噪音并应用了 scipy Savitzky Golay 过滤器。当我试图获得 y 的一阶导数时,我得到的导数为零。 我知道这是因为过滤器只需要 'y' 作为输入。我想要一个同时考虑 x 和 y 的过滤器,并为我提供一个导数值。

在这里,我用指示不正确数据的图来展示我的实现。

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

# create some sample twoD data
x = np.linspace(-3,3,100)
y = 2*x
y = y + np.random.normal(0, 0.2, y.shape)

# filter it
Zn = signal.savgol_filter(y, window_length=29, polyorder=4, deriv=0)
Zf = signal.savgol_filter(y, window_length=29, polyorder=4, deriv=1)
# do some plotting
plt.plot(x,y, label = 'Input')
plt.plot(x,Zn, label= 'Savitzky-Golay filtered')
plt.plot(x,Zf, label= 'Savitzky-Golay filtered - 1st derivative')
plt.legend()
plt.show()

结果:

求导结果: dy/dx = 2。
我需要 Savitzky-Golay 过滤器来提供这个结果。请帮助我考虑两个变量的 python 实现。

要在savgol_filter中使用deriv > 0,还必须给出x坐标的间距。修复很简单:在调用中的 deriv=1 之后添加 delta=x[1] - x[0]

Zf = signal.savgol_filter(y, window_length=29, polyorder=4, deriv=1, delta=x[1] - x[0])

在你的情况下你没有 dy/dx = 2,但是 dy/1.0 = 0.06 作为你有 x = np.linspace(-3,3,100).

您没有将 dx 定义为 delta 并使用了默认值 delta=1.0.

因此,使用等于 dxdelta 可以解决您的问题。

dx = x[0] - x[1]
Zf = signal.savgol_filter(y, window_length=29, polyorder=4, deriv=1, delta=dx)