mgcv:如何设置样条曲线的节数和/或位置

mem*_*emy 7 regression r spline gam mgcv

我想gammgcv包中使用函数:

 x <- seq(0,60, len =600)
 y <- seq(0,1, len=600) 
 prova <- gam(y ~ s(x, bs='cr')
Run Code Online (Sandbox Code Playgroud)

我可以设置结s()吗?然后我可以知道花键使用的结点在哪里?谢谢!

李哲源*_*李哲源 16

看到错误答案总是令人失望......虽然设置k是正确的方法,但fx = TRUE绝对不对:它会强制使用纯回归样条而不会受到惩罚.


结的位置

对于惩罚回归样条,确切位置并不重要,只要:

  • k 足够大;
  • 结的传播具有良好,合理的覆盖范围.

默认情况下:

  • 自然立方回归样条bs = 'cr'分位数排列结;
  • B样条系列(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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您可以看到结点位置的差异.


设置自己的结位置:

您还可以通过knots参数提供您的自定义结位置gam()(是的,结不会被输入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)))
Run Code Online (Sandbox Code Playgroud)

现在你可以看到:

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,通常不需要自己设置结.但如果你想这样做,你必须清楚自己在做什么.此外,您提供的节点数必须匹配ks().

  • 这是一个非常丰富的答案。`bs_knots` 的长度为 24。样条基的“维度”在 `bs_fit$smooth[[1]]$bs.dim` 中。 (2认同)