分享

R数据分析:逐步回归的做法和原理,案例剖析

 CodewarCodewar 2021-02-16

做回归的时候经常头痛的一个问题就是变量的选择,好多人一放一大堆变量但是结果做出来都没意义,这个时候你可以试试让算法给你选择最优的自变量组合哟。

那么今天要写的就是回归时筛选变量的逐步法:

The stepwise regression (or stepwise selection) consists of iteratively adding and removing predictors, in the predictive model, in order to find the subset of variables in the data set resulting in the best performing model, that is a model that lowers prediction error.

逐步法又分三种策略:

  1. 前进:就是把变量按照贡献大小一个一个的往回归模型中放,直到所有自变量都是显著的为止。

  2. 后退:就是把所有的自变量都放进去然后把贡献小的自变量一个一个的往出来取,直到所有的自变量都显著。

  3. 逐步Stepwise selection这个就是把两种方法结合起来,先是把贡献大的变量一个一个放(前进),所有变量放完了又把没有贡献的取出来(后退)。

R语言实操

在R中能做逐步回归的方法有很多,比如:

  • stepAIC() [MASS 包]

  • regsubsets() [leaps 包]

  • train() [caret 包]

今天我还是给大家写一个例子,这个例子我们用train来做,train()有一个可选参数 method,这个参数可以有以下3个选择

  • "leapBackward", to fit linear regression with backward selection后退

  • "leapForward", to fit linear regression with forward selection前进

  • "leapSeq", to fit linear regression with stepwise selection 逐步

我们用到的数据为R自带的Swiss数据集,里面有6个变量:

我想用其余5个变量来预测Fertility,但是5个有点多,我想用逐步回归选一选

我要选出一个最好的自变量组合来预测Fertility:

step.model <- train(Fertility ~., data = swiss,
method = "leapSeq",
tuneGrid = data.frame(nvmax = 1:5),
trControl = train.control
)
step.model$results

运行上面的代码就可以输出如下结果:

我们把自变量的最大个数nvmax规定为5,所以我们会跑出来不同自变量个数的最佳自变量组合的模型结果:

the function starts by searching different best models of different size, up to the best 5-variables model. That is, it searches the best 1-variable model, the best 2-variables model, …, the best 5-variables models.

我们需要根据模型的RMSE和MAE对模型进行选择,可以看到模型5的RMSE和MAE是最小的,所以最好的模型就是5个变量都放进去,当然了,你不愿意自己选,也可以直接输出最好的模型:

step.model$bestTune

结果显示依然是模型5最好。

那么模型到底怎么选出来的呢?

summary(step.model$finalModel)

从输出结果可以看到自变量的选择过程,如果只要一个变量那么最好的选择就是Education,如果放两个自变量,那么最好的选择就是Education和Catholic。以此类推。。

那么模型的系数是多少呢?

coef(step.model$finalModel, 5)

还有,既然变量都给你选好了,我们直接用lm法也可以得到模型系数的呀:

lm(Fertility ~ Agriculture +Examination+ Education + Catholic + Infant.Mortality,
data = swiss)

模型系数一摸一样。

小结

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多