[英]How to manually specify outer knots for smoother in gam (mgcv package)
[英]mgcv: How to set number and / or locations of knots for splines
我想在mgcv
包中使用函数gam
:
x <- seq(0,60, len =600)
y <- seq(0,1, len=600)
prova <- gam(y ~ s(x, bs='cr')
我可以在s()
中设置结数吗? 然后我能知道样条使用的结在哪里吗? 谢谢!
虽然设置k
是正确的方法,但fx = TRUE
绝对不正确:它将强制使用纯回归样条而不会受到惩罚。
结的位置
对于惩罚回归样条,确切的位置并不重要,只要:
k
足够大;默认:
bs = 'cr'
按分位数放置结;bs = 'bs'
, bs = 'ps'
, bs = 'ad'
)均匀地放置结。比较以下内容:
library(mgcv)
## toy data
set.seed(0); x <- sort(rnorm(400, 0, pi)) ## note, my x are not uniformly sampled
set.seed(1); e <- rnorm(400, 0, 0.4)
y0 <- sin(x) + 0.2 * x + cos(abs(x))
y <- y0 + e
## fitting natural cubic spline
cr_fit <- gam(y ~ s(x, bs = 'cr', k = 20))
cr_knots <- cr_fit$smooth[[1]]$xp ## extract knots locations
## fitting B-spline
bs_fit <- gam(y ~ s(x, bs = 'bs', k = 20))
bs_knots <- bs_fit$smooth[[1]]$knots ## extract knots locations
## summary plot
par(mfrow = c(1,2))
plot(x, y, col= "grey", main = "natural cubic spline");
lines(x, cr_fit$linear.predictors, col = 2, lwd = 2)
abline(v = cr_knots, lty = 2)
plot(x, y, col= "grey", main = "B-spline");
lines(x, bs_fit$linear.predictors, col = 2, lwd = 2)
abline(v = bs_knots, lty = 2)
您可以看到结位置的差异。
设置自己的结位置:
您还可以通过gam()
的knots
参数提供自定义的结位置(是的,结不是馈送到s()
,而是馈送到gam()
)。 例如,您可以为cr
做均匀间隔的结:
xlim <- range(x) ## get range of x
myfit <- gam(y ~ s(x, bs = 'cr', k = 20),
knots = list(x = seq(xlim[1], xlim[2], length = 20)))
现在你可以看到:
my_knots <- myfit$smooth[[1]]$xp
plot(x, y, col= "grey", main = "my knots");
lines(x, myfit$linear.predictors, col = 2, lwd = 2)
abline(v = my_knots, lty = 2)
但是,通常不需要自己设置结。 但是如果你真的想这样做,你必须清楚你在做什么。 特别是,您提供的结数不得与s()
中的k
冲突。
这是一个非常丰富的答案。
bs_knots
的长度为 24。样条基的“维度”在bs_fit$smooth[[1]]$bs.dim
中,即 20。
是的,对于 B 样条系列,B 样条的数量不等于结的数量。 B样条的结放置是一项肮脏的工作并且容易出错。 有关 B 样条的演示,请参阅https://stackoverflow.com/a/72723391/4891738 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.