【问题标题】:Illustrating a decision tree with splits using R使用 R 说明具有拆分的决策树
【发布时间】:2020-09-01 03:46:59
【问题描述】:

我在网上找到了一张我试图在 R 中复制的图形。我已经成功地创建了下图的第一个图形,现在我正在尝试构建决策树。它仅用于说明目的,因此不会构成某些模型的一部分。

生成第一个图的代码:

x1 <- sample(c(1:100), 100, replace = TRUE)
x2 <- sample(c(1:100), 100, replace = TRUE)

d <- data.frame(x1, x2)

d %>% 
  mutate(
    colours = case_when(
      x1 < 50 & x2 >= 60 ~ "green",
      x1 >= 50 & x2 >= 60 ~ "red",
      x1 < 70 & x2 < 60 ~ "red",
      x1 >= 70 & x2 < 20 ~ "red",
      x1 > 70 & x2 > 20 ~ "green"
    )
  ) %>% 
  ggplot(aes(x = x1, y = x2)) +
  geom_point(aes( color = colours)) +
  geom_line(data = data.frame(x = c(1, 100), y = c(60, 60)), aes(x = x , y = y), linetype = "dashed") +
  annotate("text", label = "Split 1", x = 105, y = 60) +
  geom_line(data = data.frame(x = c(50, 50), y = c(60, 100)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 2", x = 50, y = 101) +
  geom_line(data = data.frame(x = c(70, 70), y = c(1, 60)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 3", x = 70, y = 61) +
  geom_line(data = data.frame(x = c(70, 100), y = c(20, 20)), aes(x = x, y = y), linetype = "dashed") +
  annotate("text", label = "Split 4", x = 105, y = 20)

这给出了:

我现在如何创建决策树部分?我正在研究 igraph 包,但在生成决策树模型时不知道从哪里开始。

【问题讨论】:

标签: r igraph decision-tree


【解决方案1】:

也许您的问题更多是关于如何使用ggplot2 创建树。但是如果你只是想可视化决策树模型rpartrpart.plot 是一个很好的解决方案。

library(rpart)
library(rpart.plot)
# Create model
tree <- rpart(mpg~., data=mtcars, cp=.05)
# Visualize Tree
rpart.plot(tree, box.palette=c("green","red","blue"), shadow.col="gray", nn=TRUE)

还有很多方法可以自定义这个情节。通过设置rpart.plot 的参数,您可以使其看起来几乎与您的示例一模一样。

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 2015-02-18
    • 2020-04-15
    • 2022-07-19
    • 2018-07-24
    • 2015-07-14
    • 2014-08-20
    • 2016-07-29
    • 2012-05-06
    相关资源
    最近更新 更多