===
因变量lpsa是连续数据,所以接下来进行的是随机森林回归预测,本例我们的主要目的是进行自变量重要性的排序。
set.seed(123)randfit <- randomForest(lpsa~lcavol+lweight+age+lbph+svi+lcp+gleason+pgg45, mtry=3, nodesize=5, replace=T, localImp=T, nPerm=10, data = prostate) 设定随机种子便于重复。主动指定树的特征变量数量为3个,每次随机3个变量进行生长。 Type of random forest: regressionNo. of variables tried at each split: 3 Mean of squared residuals: 0.5988957 默认生成500棵树,按我们指定的每次树的分裂都是随机3个特征自变量,均方差0.599,解释了54.59%的变异来源。
plot(randfit,main="Random Forest") 优选一下tree的数量。结果反馈是196棵树。然后重新建模,创建196棵树的随机森林。randfit2 <- randomForest(lpsa~lcavol+lweight+age+lbph+svi+lcp+gleason+pgg45, ntree=197, mtry=3, nodesize=5, replace=5, localImp=T, nPerm=10, data = prostate) 现在来看优化过的随机森林模型中自变量的重要性排序。
varImpPlot(randfit2,main = "Variable Importance Plot") incnodepurity和%incmse这两个指标都是越大说明变量越重要。综合来看,lcavol、lweight、svi这三个最重要排在前三位置。可以根据研究的需要,选择重要的自变量进行后续的分析。
|