Python 内核平滑

Python Kernel Smoothing

我有一些要在 Python 中复制的 R 代码。在 R 文件中,我有一个数据框,我用

平滑了数据框的一列
smoothedTime <- ksmooth(1:length(df$time), df$time, bandwidth=100, x.points=(1:length(df$time)))$y

在 Python 中,我使用 scikit-fda 库和 skfda.preprocessing.smoothing.kernel_smoothers.NadarayaWatsonSmoother() 进行平滑处理,smoothing_parameter 设置为 100,因为这就是 R ksmooth函数是基于。我遇到的问题是我得到的平滑度不一样。默认情况下,ksmooth 中的内核是 c("box", "normal"),但我没有看到 NadarayaWatsonSmoother() 的盒式内核。所以,因为 NadarayaWatsonSmoother() 默认有一个正常的内核,我试过

smoothedTime <- ksmooth(1:length(df$time), df$time, bandwidth=100, kernel=c("normal"), x.points=(1:length(df$time)))$y

结果还是不一样。我想知道为什么我没有得到相同的答案,以及我可以做些什么来获得相同的答案。

相关代码为

Python代码:

import skfda
from skfda import FDataGrid
from skfda.misc import kernels
import skfda.preprocessing.smoothing.kernel_smoothers as ks

myTime = [-0.01, -0.02, -0.01, -0.01, -0.04, -0.05, -0.07, -0.1, -0.12, -0.15, -0.19, -0.22, -0.26, -0.27, -0.31, -0.33, -0.36, -0.38, -0.4, -0.42, -0.44, -0.44, -0.46, -0.47, -0.48, -0.49, -0.5, -0.49, -0.51, -0.51, -0.51, -0.51, -0.5, -0.48, -0.48, -0.46, -0.45, -0.43, -0.41, -0.39, -0.37, -0.34, -0.34, -0.32, -0.31, -0.32, -0.35, -0.35, -0.37, -0.39, -0.42, -0.45, -0.5, -0.52, -0.55, -0.58, -0.6, -0.6, -0.6, -0.6]
fd = FDataGrid(sample_points=[*range(1, len(myTime)+1)],
           data_matrix=[myTime])
smoother = ks.NadarayaWatsonSmoother(smoothing_parameter=100)
smoothed = smoother.fit_transform(fd)

R代码:

df$time <- c(-0.01, -0.02, -0.01, -0.01, -0.04, -0.05, -0.07, -0.1, -0.12, -0.15, -0.19, -0.22, -0.26, -0.27, -0.31, -0.33, -0.36, -0.38, -0.4, -0.42, -0.44, -0.44, -0.46, -0.47, -0.48, -0.49, -0.5, -0.49, -0.51, -0.51, -0.51, -0.51, -0.5, -0.48, -0.48, -0.46, -0.45, -0.43, -0.41, -0.39, -0.37, -0.34, -0.34, -0.32, -0.31, -0.32, -0.35, -0.35, -0.37, -0.39, -0.42, -0.45, -0.5, -0.52, -0.55, -0.58, -0.6, -0.6, -0.6, -0.6)
smoothedTime <- ksmooth(1:length(df$time), df$time, kernel="normal", bandwidth=100, x.points=(1:length(df$time)))$y

这种行为的原因是 R 中的 ksmooth 函数对不同的内核有不同的缩放比例(参见 source code),而 scikit-fda 在应用内核之前简单地除以传递的带宽。如果将 smoothing_parameter 乘以 0.3706506(对于普通内核)或乘以 0.5(对于盒内核;请注意,该内核也可以是在 scikit-fda 中使用传递参数 kernel=skfda.misc.kernels.uniform).

免责声明:我是 scikit-fda 的维护者。很抱歉我迟到的回答,但是当提到它的问题出现在这个页面上时,我没有得到通知。如果您以后对软件包有任何疑问,可以尝试打开 issue or a discussion。我会收到这些通知,通常可以在几小时或几天内回复。