B 样条曲线拟合实例:能平滑化曲线
1. 实例1
为MASS包中mcycle数据集。它测试了一系列模拟的交通车事故中,头部的加速度,以此来评估头盔的性能。times为撞击时间(ms),accel为加速度(g)。首先导入数据,并绘制散点图
(1) 关键函数
# bs() ====
# bs(x, df = NULL, knots = NULL, degree = 3, intercept = FALSE,
# Boundary.knots = range(x))
#参数解释:
#x:自变量,这里为x
#df: 自由度(回归函数中的参数个数),默认为0,由于我们需要截距,
# 2.2 节中c中提到的公式减去1,因此自由度为4+3 = 7
#knots:节点的位置,这里为c(15,20,32,40)
#degree:q值,默认为3
#其他的参数保持默认即可
然后搭配lm 函数,即可画出样条函数曲线
(2) 代码
# Spline ====
x=mcycle$time
y=mcycle$accel
plot(x, y, type="p", pch=19, cex=0.5)library(splines)
#B = spline(y, n=3*length(y) )
#lines(B$x, B$y, lty=2, col="red")bspl <- lm(y~bs(x, df =7, #knots = c(15,20,32,40), degree=2))
lines(x, fitted(bspl),lwd = 2, col = 2)ref: https://blog.csdn.net/weixin_39642998/article/details/110705947
似乎不靠谱,需要自己指定锚点位置?去掉 knots 参数就好了。
请直接看2(2)
2. help 例子:更靠谱的方法
(1) 原例:不明显
require(stats); require(graphics)
head(women)
bs(women$height, df = 5)
summary(fm1 <- lm(weight ~ bs(height, df = 5), data = women))## example of safe prediction
plot(women, xlab = "Height (in)", ylab = "Weight (lb)")
ht <- seq(57, 73, length.out = 200)
lines(ht, predict(fm1, data.frame(height = ht)))
(2) 重做例1,模仿(1)
library(MASS)
head(mcycle)
x=mcycle$times
y=mcycle$accel#plot(x, y, pch=19, cex=0.5)
library(splines)
bs(y, df = 5)
summary(fm1 <- lm(y ~ bs(x, df = 7, degree = 2), data = NULL))## example of safe prediction
plot(mcycle, xlab = "times", ylab = "accel", pch=19, cex=0.5)
x_2 <- seq(min(x), max(x), length.out = 200)
lines(x_2, predict(fm1, data.frame(x = x_2)), lwd=2, col="red")
目测效果很好!
参数解释:
df=7,有大概7个控制点,越多拟合越好;太多就会过拟合!
degree=3,次数。