美文网首页
R-建模 randomForest

R-建模 randomForest

作者: 倪桦 | 来源:发表于2023-05-16 14:40 被阅读0次

    随机森林(Random Forest)是一种基于 决策树 的集成学习算法,它通过构建多个决策树,并将它们组合起来进行分类或回归。随机森林的基本思想是,通过随机选择样本和特征,构建多个决策树,然后将它们的结果进行投票或平均,得到最终的分类或回归结果。广泛应用用于分类、回归、特征选择等多个领域。

    随机森林的构建过程:

    • 随机选择样本:从原始数据集中随机选择一部分样本,用于构建决策树。
    • 随机选择特征:从所有特征中随机选择一部分特征,用于构建决策树。
    • 构建决策树:使用随机选择的样本和特征,构建一棵决策树。
    • 重复步骤1-3,构建多棵决策树。
    • 投票或平均:将多棵决策树的结果进行投票或平均,得到最终的分类或回归结果。

    随机森林的特点:

    • 随机性:随机森林中的每个决策树都是基于随机样本和随机特征进行构建的,这种随机性可以减少过拟合的风险,提高模型的泛化能力。
    • 集成性:随机森林将多个决策树组合起来进行分类或回归,可以减少单个决策树的误差,提高模型的准确性。
    • 可扩展性:随机森林可以处理大量的特征和样本,适用于各种规模的数据集。

    随机森林的优点:

    • 随机森林可以处理高维数据,一般数据工程可以不需要进行特征选择。
    • 随机森林可以 评估特征的重要性,帮助进行特征选择。
    • 随机森林可以并行计算,加快模型训练的速度。
    #### 构建随机森林分类模型
    library(randomForest);library(caret);library(dplyr);library(pROC)
    
    ### Train/Test Split
    dat <- MASS::fgl %>% mutate(type = as.factor(type))
    sample_init <- caret::createDataPartition(dat$type,p = .75,list = F)
    dat.train <- dat[ sample_init,]
    dat.tests <- dat[-sample_init,]
    
    #### Build Formular 
    cur_formular <- as.formula(paste0("type~",paste0(colnames(dat)[2:9],collapse = "+")))
    
    #### Build model 
    bestmtry <- tuneRF(x = dat.train,y = dat.train$type,plot = F,trace = T) ### 基于OOB(Out-of-Bag)误差来评估随机森林的泛化能力   
    RF_model <- randomForest(cur_formular,data= dat.train,mtry=6,nodesize = 6,ntree = 1000,importance= T) ### mtry控制每次分裂节点的选择范围,nodesize = 最小叶子节点大小(控制树的深度),ntree决策树数量
    
    ### 模型分析
    plot(RF_model) ### 模型(类别)误差与决策树数量的关系,输出的是数据框 RF_model$err.rate(袋外误差率) 的结果,。在实际应用中,还需要考虑其他指标,如准确率、召回率、F1值等。
    
    #####  MeanDecreaseAccuracy,衡量一个变量在多大程度上提高了森林预测分类的准确性,较高的值意味着该变量改进了预测。
    #####  MeanDecreaseGini,    衡量一个变量在多大程度上影响生成的随机森林中节点和叶子的同质性的指标,较高的值意味着该变量改进了预测。
    RF_model[["importance"]] ### 返回特征重要性评估数据框,行为特征名,列为响应变量和MeanDecreaseAccuracy/MeanDecreaseGini
    varImpPlot(RF_model) ### MeanDecreaseAccuracy和 MeanDecreaseGini 两指标的散点图
    partialPlot(RF_model,pred.data = dat.train,x.var = "Mg",which.class = "WinF") ### 偏相关图,展示选定变量对相应变量类型的分类贡献
    
    ### 训练集预测
    ###### 调整分类概率截断点:
    train_prob <- predict(RF_model,newdata = dat.train,type = "prob") %>% data.frame()
    train_response <- predict(RF_model,newdata = dat.train,type = "response")
    #### 计算多分类AUC,该方法不输出 ROC 曲线
    multi.train_roc <- pROC::multiclass.roc(response = dat.train[["type"]], predictor = train_prob) ### 计算多分类AUC,该方法不输出 ROC 曲线
    # plot.roc(multi.train_roc[["rocs"]][[1]])
    # sapply(2:length(multi.train_roc[["rocs"]]),function(i) lines.roc(multi.train_roc[["rocs"]][[i]],col=i))
    confusionMatrix(data = train_response,reference = dat.train$type,mode = 'everything') ### 设置mode = “everything”才有F1指标,统计了模型的总体准确率,kappa一致度等指标
    
    ### 测试集预测...
    test_response <- predict(RF_model,newdata = dat.tests,type = "response")
    caret::confusionMatrix(data = test_response,reference = dat.tests$type,mode = 'everything')
    
    
    


    Reference Matiral

    Random forest regression in R - Projectpro
    machine learning - What does "node size" refer to in the Random Forest? - Cross Validated (stackexchange.com)
    GitHub - WandeRum/multiROC: Calculating and Visualizing ROC and PR Curves Across Multi-Class Classifications
    r - plot.roc for multiclass.roc in pROC package? - Stack Overflow
    How to Calculate F1 Score in R (Including Example) - Statology

    相关文章

      网友评论

          本文标题:R-建模 randomForest

          本文链接:https://www.haomeiwen.com/subject/mbcbsdtx.html