首页 > 解决方案 > 为 R 中的一个特征变量生成平滑样条曲线

问题描述

在阅读了有关平滑样条的材料后,我想使用以下 R 代码为特征变量 x 生成平滑样条。

这是我为获得特征变量 x 的平滑样条曲线的基础所做的工作:

x = sort(rnorm(30)) # x is the feature variable 
px = stats::poly(x, degree = 3) # orthogonal polynomial basis

smooth_spline_basis1 = smooth.spline(x, px[,1],df=3, all.knots = TRUE)$y 
smooth_spline_basis2 = smooth.spline(x, px[,2],df=3, all.knots = TRUE)$y 
smooth_spline_basis3 = smooth.spline(x, px[,3],df=3, all.knots = TRUE)$y 

par(mfrow=c(2,2))
plot(px[,1],smooth_spline_basis1, main = "smoothing_spline_basis1 VS polynomial_spline_basis1")
plot(px[,2],smooth_spline_basis2, main = "smoothing_spline_basis2 VS polynomial_spline_basis2")
plot(px[,3],smooth_spline_basis3, main = "smoothing_spline_basis3 VS polynomial_spline_basis3")
par(mfrow=c(1,1))

思维过程正确吗?还是我错过了什么?

在此处输入图像描述

标签: rsplinesmoothing

解决方案


该软件包mgcv为您提供了一个很好的样条平滑器,具有gam()广义加法模型的功能。下面是样条拟合到正弦曲线的示例:

library(mgcv)

x <- seq(0, 2 * pi, length.out = 100)
y <- sin(x)

mod <- gam(y ~ s(x))
summary(mod)

plot(x, y)
lines(x, fitted(mod), col = "green", lwd = 2)

在此处输入图像描述


推荐阅读