代码之家  ›  专栏  ›  技术社区  ›  user3115933

如何使用R在随机森林中生成决策树图和可变重要性图?

  •  2
  • user3115933  · 技术社区  · 7 年前

    我是数据科学的新手,我正在使用随机森林算法进行机器学习分析以执行分类。我的数据集中的目标变量称为损耗(是/否)。

    我有点搞不懂如何用随机的方法生成这两个图:

    (1) Feature Importance Plot
    
    (2) Decision Tree Plot
    

    假设我的训练数据集是 TrainDf 我的测试数据集叫做 TestDf ,如何在R中创建这两个图?

    更新:从这两个帖子来看,它们似乎无法完成,或者我在这里遗漏了什么? Why is Random Forest with a single tree much better than a Decision Tree classifier?

    How would you interpret an ensemble tree model?

    2 回复  |  直到 7 年前
        1
  •  2
  •   RSK    7 年前

    要绘制变量重要性,可以使用以下代码。

    mtcars.rf <- randomForest(am ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
                          importance=TRUE)
    varImpPlot(mtcars.rf)
    
        2
  •  2
  •   Sandipan Dey    7 年前

    具有 ggplot2 ,

    library(randomForest)
    library(ggplot2)
    mtcars.rf <- randomForest(vs ~ ., data=mtcars)
    imp <- cbind.data.frame(Feature=rownames(mtcars.rf$importance),mtcars.rf$importance)
    g <- ggplot(imp, aes(x=reorder(Feature, -IncNodePurity), y=IncNodePurity))
    g + geom_bar(stat = 'identity') + xlab('Feature')
    

    enter image description here

    决策树图 具有 igraph

    tree <- randomForest::getTree(mtcars.rf, k=1, labelVar=TRUE) # get the 1st decision tree with k=1
    tree$`split var` <- as.character(tree$`split var`)
    tree$`split point` <- as.character(tree$`split point`)
    tree[is.na(tree$`split var`),]$`split var` <- ''
    tree[tree$`split point` == '0',]$`split point` <- ''
    
    library(igraph)
    gdf <- data.frame(from = rep(rownames(tree), 2),
                              to = c(tree$`left daughter`, tree$`right daughter`))
    g <- graph_from_data_frame(gdf, directed=TRUE)
    V(g)$label <- paste(tree$`split var`, '\r\n(', tree$`split point`, ',', round(tree$prediction,2), ')')
    g <- delete_vertices(g, '0')
    print(g, e=TRUE, v=TRUE)
    plot(g, layout = layout.reingold.tilford(g, root=1), vertex.size=5, vertex.color='cyan')
    

    从下图可以看出,决策树中每个节点的标签表示在该节点上选择要拆分的变量名(拆分值,带有标签1的类的比例)。

    enter image description here

    同样,第100棵树也可以通过 k=100 randomForest::getTree() 函数,如下所示

    enter image description here

    推荐文章