随机森林分类
#载入包
library(randomForest)
library(caret)
#读取数据.数据链接:https://github.com/Kuntal-G/Machine-Learning/blob/master/R-machine-learning/data/banknote-authentication.cs
bn<-read.csv("C:\\Users\\Administrator\\desktop\\banknote.csv")
#将相应变量转换为因子
bn$class<-factor(bn$class)
#选择数据的一个子集来建模。在建立每一棵树的时候,随机森林会保留一部分数据用作交叉验证。
在此保留一部分样本仅是为了举例说明用模型来预测整个过程。
set.seed(1000)
sub.idx<-createDataPartition(bn$class,p=0.7,list=FALSE)
#创建随机森林.randomForest函数建立的模型不会保留树的信息,因此无法用这个模型预测未来的样本,
如要强制保留创建的的森林,可以使用keep.forest=TRUE.
mod<-randomForest(x=bn[sub.idx,1:4],y=bn[sub.idx,5],ntree=500,keep.forest=TRUE)
#用上述保留的数据样本做预测
pred<-predict(mod,bn[-sub.idx,])
#建立误差矩阵
table(bn[-sub.idx,"class"],pred,dnn=c("Actual","Predicted"))
Predicted
Actual 0 1
0 22