GAM 交叉验证测试预测误差

机器算法验证 r 交叉验证 广义加法模型 毫克CV
2022-03-19 22:09:01

我的问题涉及mgcv R 包中的 GAM。由于样本量小,我想使用留一法交叉验证来确定预测误差。这合理吗?有没有我可以做到这一点的包或代码?ipred包中的errorest()功能不起作用。一个简单的测试数据集是:

library(mgcv)
set.seed(0)
dat <- gamSim(1,n=400,dist="normal",scale=2)
b<-gam(y~s(x0)+s(x1)+s(x2)+s(x3),data=dat)
summary(b)
pred <- predict(b, type="response")

非常感谢您的帮助!

2个回答

我真的很喜欢这样的包caret,但不幸的是我刚刚读到你不能准确地指定formulagam

“当你在这个模型中使用 train 时,你不能(此时)指定 gam 公式。插入符号有一个内部函数,它根据每个预测变量有多少唯一级别等计算出一个公式。换句话说,train 当前确定哪个项是平滑的,它们是普通的旧线性主效应。”

来源:https ://stackoverflow.com/questions/20044014/error-with-train-from-caret-package-using-method-gam

但是如果您让train选择平滑项,在这种情况下,无论如何它都会生成您的模型。在这种情况下,默认性能指标是 RMSE,但您可以使用函数的summaryFunction参数更改它trainControl

我认为 LOOCV 的主要缺点之一是当数据集很大时,它需要很长时间。由于您的数据集很小并且运行速度非常快,因此我认为这是一个明智的选择。

希望这可以帮助。

library(mgcv)
library(caret)

set.seed(0)

dat <- gamSim(1, n = 400, dist = "normal", scale = 2)

b <- train(y ~ x0 + x1 + x2 + x3, 
        data = dat,
        method = "gam",
        trControl = trainControl(method = "LOOCV", number = 1, repeats = 1),
        tuneGrid = data.frame(method = "GCV.Cp", select = FALSE)
)

print(b)
summary(b$finalModel)

输出:

> print(b)
Generalized Additive Model using Splines 

400 samples
  9 predictors

No pre-processing
Resampling: 

Summary of sample sizes: 399, 399, 399, 399, 399, 399, ... 

Resampling results

  RMSE      Rsquared 
  2.157964  0.7091647

Tuning parameter 'select' was held constant at a value of FALSE

Tuning parameter 'method' was held constant at a value of GCV.Cp

> summary(b$finalModel)

Family: gaussian 
Link function: identity 

Formula:
.outcome ~ s(x0) + s(x1) + s(x2) + s(x3)

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   7.9150     0.1049   75.44   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Approximate significance of smooth terms:
        edf Ref.df       F  p-value    
s(x0) 5.173  6.287   4.564 0.000139 ***
s(x1) 2.357  2.927 103.089  < 2e-16 ***
s(x2) 8.517  8.931  84.308  < 2e-16 ***
s(x3) 1.000  1.000   0.441 0.506929    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

R-sq.(adj) =  0.726   Deviance explained = 73.7%
GCV =  4.611  Scale est. = 4.4029    n = 400

在 mgcv 库 pdf 中它说;

“给定由 gam 模型公式指定的模型结构,gam() 尝试使用预测误差标准或基于似然的方法为每个适用的模型项找到适当的平滑度。使用的预测误差标准是广义(近似)交叉验证(GCV 或GACV)当规模参数未知时或无偏风险估计量(UBRE)已知时。”

“mgcv 中的 gam 通过使用广义交叉验证 (GCV) 标准解决了平滑参数估计问题:nD/(n - DoF)2

或者

无偏风险估计量(UBRE)标准:D/n + 2sDoF/n - s"