简单的说,随机森林就是用随机的方式建立一个森林,森林里面有很多的决策树,并且每棵树之间是没有关联的。得到一个森林后,当有一个新的样本输入,森林中的每一棵决策树会分别进行一下判断,进行类别归类(针对分类算法),最后比较一下被判定哪一类最多,就预测该样本为哪一类。
随机森林算法有两个主要环节:决策树的生长和投票过程。
随机森林采用Bagging方法生成多个决策树分类器。
寻找最优参数mtry,即指定节点中用于二叉树的最佳变量个数
library("randomForest") n<-length(names(train_data)) #计算数据集中自变量个数,等同n=ncol(train_data) rate=1 #设置模型误判率向量初始值 for(i in 1:(n-1)){ set.seed(1234) rf_train<-randomForest(as.factor(train_data$IS_LIUSHI)~.,data=train_data,mtry=i,ntree=1000) rate[i]<-mean(rf_train$err.rate) #计算基于OOB数据的模型误判率均值 print(rf_train) } rate #展示所有模型误判率的均值 plot(rate)
寻找最佳参数ntree,即指定随机森林所包含的最佳决策树数目
set.seed(100) rf_train<-randomForest(as.factor(train_data$IS_LIUSHI)~.,data=train_data,mtry=12,ntree=1000) plot(rf_train) #绘制模型误差与决策树数量关系图 legend(800,0.02,"IS_LIUSHI=0",cex=0.9,bty="n") legend(800,0.0245,"total",cex=0.09,bty="n")
set.seed(100) rf_train<-randomForest(as.factor(train_data$IS_LIUSHI)~.,data=train_data,mtry=12,ntree=400,importance=TRUE,proximity=TRUE)
输出变量重要性:分别从精确度递减和均方误差递减的角度来衡量重要程度。
importance<-importance(rf_train) write.csv(importance,file="E:/模型搭建/importance.csv",row.names=T,quote=F) barplot(rf_train$importance[,1],main="输入变量重要性测度指标柱形图") box()
提取随机森林模型中以准确率递减方法得到维度重要性值。type=2为基尼系数方法
importance(rf_train,type=1) varImpPlot(x=rf_train,sort=TRUE,n.var=nrow(rf_train$importance),main="输入变量重要性测度散点图")
信息展示
print(rf_train) #展示随机森林模型简要信息 hist(treesize(rf_train)) #展示随机森林模型中每棵决策树的节点数 max(treesize(rf_train));min(treesize(rf_train)) MDSplot(rf_train,train_data$IS_OFF_USER,palette=rep(1,2),pch=as.numeric(train_data$IS_LIUSHI)) #展示数据集在二维情况下各类别的具体分布情况
检测
pred<-predict(rf_train,newdata=test_data) pred_out_1<-predict(object=rf_train,newdata=test_data,type="prob") #输出概率 table <- table(pred,test_data$IS_LIUSHI) sum(diag(table))/sum(table) #预测准确率 plot(margin(rf_train,test_data$IS_LIUSHI),main=观测值被判断正确的概率图)
randomForest包可以实现随机森林算法的应用,主要涉及5个重要函数,语法和参数请见下
randomForest(formula, data=NULL, ..., subset, na.action=na.fail) randomForest(x, y=NULL, xtest=NULL, ytest=NULL, ntree=500, mtry=if (!is.null(y) && !is.factor(y)) max(floor(ncol(x)/3), 1) else floor(sqrt(ncol(x))), replace=TRUE, classwt=NULL, cutoff, strata, sampsize = if (replace) nrow(x) else ceiling(.632*nrow(x)), nodesize = if (!is.null(y) && !is.factor(y)) 5 else 1, maxnodes = NULL, importance=FALSE, localImp=FALSE, nPerm=1, proximity, oob.prox=proximity, norm.votes=TRUE, do.trace=FALSE, keep.forest=!is.null(y) && is.null(xtest), corr.bias=FALSE, keep.inbag=FALSE, ...)
importance(x, type=NULL, class="NULL", scale=TRUE, ...)
MDSplot(rf, fac, k=2, palette=NULL, pch=20, ...)
rfImpute(x, y, iter=5, ntree=300, ...) rfImpute(x, data, ..., subset)
treesize(x, terminal=TRUE)