看来你来自我2016年之前的一个回答:mgcv:如何设置样条线的结的数量和/或位置 https://stackoverflow.com/a/40113075/4891738,借用我的代码片段:
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)
在那个答案中,我的演示是用三次回归样条进行的(bs = 'cr'
),打结很简单。但对于 B 样条来说,事情就更复杂了。因此,将此答案作为对该答案的补充。
对于 B 样条类mgcv, i.e., 'bs'
是“废话”(?b.spline
)、“ps”(?p.spline
) 或“广告”(?adaptive.smooth
),论证k
是 B 样条线的数量,而不是结的数量。第一条带回家的信息是:B 样条的数量不等于结的数量。
B 样条线的结放置是一项肮脏的工作。通常您只需指定k
and mgcv会自动为您打结(例如,参见,提取自适应平滑中 P 样条的节点、基础、系数和预测 https://stackoverflow.com/q/37379609/4891738)。如果您想自己控制结的放置,您提供的结的数量必须与k
。如果您不太了解 B 样条,这可能会造成很大的混乱。
我强烈建议您阅读我的一篇作品的附录(第 33-34 页):非均匀 B 样条的通用 P 样条 https://arxiv.org/pdf/2201.06808.pdf,了解 B 样条的一些基本知识。确保您了解什么是domain, 内结 and 辅助边界结。下面,我将向您展示如何利用这些知识来编写正确的代码。
以下是如何为您的示例打结。
## degree of spline
deg <- 3
## domain
a <- min(x)
#[1] 5.86
b <- max(x)
#[1] 24.16
## interior knots (must be between a and b)
xs <- c(6, 20)
#[1] 6 20
## domain knots
xd <- c(a, xs, b)
#[1] 5.86 6.00 20.00 24.16
## clamped auxiliary boundary knots
left.aux <- rep(a, deg)
#[1] 5.86 5.86 5.86
right.aux <- rep(b, deg)
#[1] 24.16 24.16 24.16
## complete B-spline knots
my.knots <- c(left.aux, xd, right.aux)
#[1] 5.86 5.86 5.86 5.86 6.00 20.00 24.16 24.16 24.16 24.16
以下是如何指定k
以你为例。
my.k <- length(xs) + deg + 1
#[1] 6
现在我们可以与mgcv.
myfit <- gam(y ~ s(x, bs = 'bs', k = my.k),
knots = list(x = my.knots))
#Family: gaussian
#Link function: identity
#
#Formula:
#y ~ s(x, bs = "bs", k = my.k, m = deg)
#
#Estimated degrees of freedom:
#3.81 total = 4.81
你传入的结存储在这里(与my.knots
):
## For B-spline classes, knots are stored in $knots instead of $xp
myfit$smooth[[1]]$knots
#[1] 5.86 5.86 5.86 5.86 6.00 20.00 24.16 24.16 24.16 24.16
随同非均匀 B 样条的通用 P 样条 https://arxiv.org/pdf/2201.06808.pdf是 R 包gps and gps.mgcv。后一个包引入了一个新的“gps”类mgcv, where bs = 'ps'
and bs = 'bs'
是特殊情况bs = 'gps'
。新的“gps”类使结的放置更加容易,因为它会自动为您放置辅助边界结,而您只需要提供内部结。
## The package stays on GitHub for the moment
## but will be on CRAN in the future.
## You may need to first install package 'devtools' from CRAN.
devtools::install_github("ZheyuanLi/gps")
devtools::install_github("ZheyuanLi/gps.mgcv")
library(gps.mgcv)
## as same as using 'bs = 'bs''
myfit <- gam(y ~ s(x, bs = 'gps', k = my.k, xt = list(derivative = TRUE)),
knots = list(x = xs)) ## provide interior knots
## the novel general P-spline
gpsfit <- gam(y ~ s(x, bs = 'gps', k = my.k),
knots = list(x = xs)) ## provide interior knots
构造信息(域、内部结等)存储在myfit$smooth[[1]]$xt
and gpsfit$smooth[[1]]$xt
.