使用平滑參數避免過度擬合
平滑參數在概似度與曲線彎曲度之間取得平衡,以最佳化模型擬合。在這裡,你會檢視平滑參數,並以不同的固定平滑參數來擬合模型。
本練習屬於課程
R 中的廣義加法模型(GAM)之非線性建模
練習說明
- 透過從模型擷取
sp值,查看提供的gam_mod模型之平滑參數($\lambda$)。 - 以
mcycle資料為例,將accel視為times的平滑函式,分別用以下平滑參數擬合兩個模型:- 0.1
- 0.0001
- 視覺化兩個模型。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
library(mgcv)
# Extract the smoothing parameter
gam_mod <- gam(accel ~ s(times), data = mcycle, method = "REML")
___
# Fix the smoothing parameter at 0.1
gam_mod_s1 <- gam(accel ~ s(times), data = mcycle, sp = ___)
# Fix the smoothing parameter at 0.0001
gam_mod_s2 <- gam(___)
# Plot both models
par(mfrow = c(2, 1))
plot(gam_mod_s1, residuals = TRUE, pch = 1)
plot(gam_mod_s2, residuals = TRUE, pch = 1)