![](/img/trans.png)
[英]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.