【问题标题】:Conditional execution in R based on decision treeR中基于决策树的条件执行
【发布时间】:2014-07-03 12:22:08
【问题描述】:

我有一个 CSV 文件,其中包含血压 (BP)、心率 (HR)、体重、体表面积 (BSA)、体重指数 (BMI)、年龄和性别等预测变量。

这些变量有一个基于决策树的算法,可将这些患者分为高风险是/否类别。所以 HIGH_RISK 是 CSV 的最后一列,目前它是空的。现在,即使我可以对单个主题(CSV 文件中的单个行)使用该算法来填充 HIGH_RISK 列,但是由于行太多,手动执行该操作是不切实际的。

如果是简单的加法、减法、乘法等,我会在 R 甚至 Excel 中完成。但由于该算法涉及分叉决策树,我不知道该怎么做。但我确信这是可能的,因为 R 是如此强大。有什么建议吗?

决策树类似这样:http://www.scielo.br/img/revistas/sa/v70n6/a01fig04.jpg

【问题讨论】:

  • 多少行?为什么这是不切实际的?你试过什么?

标签: r decision-tree conditional-execution


【解决方案1】:

你可以使用我为你写的这个辅助函数:

decisionTree <- function(dataframe, lst) {
  if (!is.recursive(lst)) return(lst)
  values <- numeric(nrow(dataframe))
  indices <- eval(parse(text = names(lst)[1]), dataframe)
  values[indices] <- decisionTree(dataframe[indices, ], lst[[1]])
  values[!indices] <- decisionTree(dataframe[!indices, ], lst[[2]])
  values
}

一般格式是将data.frame 作为第一个参数,将表示决策树的嵌套列表作为第二个参数传递,格式如下:

 list("first_variable > 0.3" = 
         list("second_variable > 0.5" = 1,
              "second_variable <= 0.5" = list(
                 "third_variable > 0.3" = 0,
                 1) # naming the negated condition is optional
              ),
      "first_variable <= 0.3" = 0)

示例

iris$foo <- decisionTree(iris, list("Sepal.Length > 5" = list("Petal.Length > 1.3" = 1, 0), 0))
head(iris) # All entries with Sepal.Length > 5 and Petal.Length > 1.3 will contain a 1.
#      Sepal.Length Sepal.Width Petal.Length Petal.Width Species foo
#    1          5.1         3.5          1.4         0.2  setosa   1
#    2          4.9         3.0          1.4         0.2  setosa   0
#    3          4.7         3.2          1.3         0.2  setosa   0
#    4          4.6         3.1          1.5         0.2  setosa   0
#    5          5.0         3.6          1.4         0.2  setosa   0
#    6          5.4         3.9          1.7         0.4  setosa   1

对于您提供的图表,第二个参数如下所示:

list("Ts_Armpit > 35.1" = 1,
  list("Ts_Breast <= 0.39" = list("Ts_Croup <= 28.9" = 1, 0),
    list("Ts_Groin <= 35.1" = 1, list("Ts_Armpit <= 33.7" = 1, 0))))

其中1 表示不适,0 表示舒适。

【讨论】:

  • 非常感谢!我会在家里检查我的数据,现在就让你看看。再次感谢。
  • 再次感谢,效果很好!!但是在决策树的某一点上,存在三叉,而不是分叉。因此,例如,如果您将 first_variable 分为三个类别 0.3 6。那你会怎么处理呢?
猜你喜欢
  • 2011-08-05
  • 2016-05-18
  • 2014-08-21
  • 2019-01-25
  • 2020-10-18
  • 1970-01-01
  • 2015-07-14
  • 2014-05-27
  • 2014-08-20
相关资源
最近更新 更多