r - mgcv:如何设置样条线的结的数量和/或位置

标签 r regression spline gam mgcv

我想在 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'分位数放置结;
  • 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)

enter image description here

您可以看到结位置的差异。

<小时/>

设置您自己的结位置:

您还可以通过 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)

enter image description here

但是,通常不需要自己打结。但如果你确实想这样做,你必须清楚你在做什么。特别是,您提供的结数不得与 s() 中的 k 冲突。

This is a very rich answer. The length of bs_knots is 24. The "dimension" of the spline basis is in bs_fit$smooth[[1]]$bs.dim, which is 20.

是的,对于 B 样条曲线族,B 样条曲线的数量不等于结的数量。 B 样条线的结放置是一项肮脏的工作并且容易出错。请参阅https://stackoverflow.com/a/72723391/4891738使用 B 样条进行演示。

关于r - mgcv:如何设置样条线的结的数量和/或位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40056566/

相关文章:

javascript - 如何在 Three.js 中仅绘制样条曲线的下半部分

c++ - 如何应用样条基矩阵?

r - 包的功能列表

html - R Shiny 框内容背景色

python - 多项式回归度数增加误差

python - 使用 numpy/python 从头开始​​进行多项式展开

r - 从矩阵平滑表面图

html - 使用 rvest 在 r 中循环多个 url

R:如何旋转副 Y Axis 的标签?? {根据}

r - 标准化回归系数改变了显着性