R:如何使用随机森林来预测使用字符串变量的二进制结果?

R: how to use random forests to predict binary outcome using string variables?

考虑以下数据框

outcome <- c(1,0,0,1,1)
string <- c('I love pasta','hello world', '1+1 = 2','pasta madness', 'pizza madness')

df = df=data.frame(outcome,string)


> df
  outcome        string
1       1  I love pasta
2       0   hello world
3       0       1+1 = 2
4       1 pasta madness
5       1 pizza madness

这里我想用随机森林来理解string变量包含的句子中哪些词是outcome变量的强预测因子 .

在 R 中有(简单的)方法吗?

您想要的是 randomForest 生成的变量重要性度量。这是从 importance 函数获得的。下面是一些可以帮助您入门的代码:

outcome <- c(1,0,0,1,1)
string <- c('I love pasta','hello world', '1+1 = 2','pasta madness', 'pizza madness')

第 1 步: 我们希望 outcome 成为一个因素,以便 randomForest 进行 分类 并且string 作为字符向量。

df <- data.frame(outcome=factor(outcome,levels=c(0,1)),string, stringsAsFactors=FALSE)

步骤 2:string 列标记为单词。在这里,我使用 dplyrtidyr 只是为了方便。关键是只使用您想要的单词标记作为预测变量。

library(dplyr)
library(tidyr)
inp <- df %>% mutate(string=strsplit(string,split=" ")) %>% unnest(string)
##   outcome  string
##1        1       I
##2        1    love
##3        1   pasta
##4        0   hello
##5        0   world
##6        0     1+1
##7        0       =
##8        0       2
##9        1   pasta
##10       1 madness
##11       1   pizza
##12       1 madness

第 3 步: 构建模型矩阵并将其提供给 randomForest

library(randomForest)
mm <- model.matrix(outcome~string,inp)
rf <- randomForest(mm, inp$outcome, importance=TRUE)
imp <- importance(rf)
##                     0        1 MeanDecreaseAccuracy MeanDecreaseGini
##(Intercept)   0.000000 0.000000             0.000000        0.0000000
##string1+1     0.000000 0.000000             0.000000        0.3802400
##string2       0.000000 0.000000             0.000000        0.4514319
##stringhello   0.000000 0.000000             0.000000        0.4152465
##stringI       0.000000 0.000000             0.000000        0.2947108
##stringlove    0.000000 0.000000             0.000000        0.2944955
##stringmadness 4.811252 5.449195             5.610477        0.5733814
##stringpasta   4.759957 5.281133             5.368852        0.6651675
##stringpizza   0.000000 0.000000             0.000000        0.3025495
##stringworld   0.000000 0.000000             0.000000        0.4183821

如您所见,意大利面和疯狂是预测 outcome 的关键词。

请注意: randomForest 有许多参数与解决实际规模问题相关。这绝不是您问题的完整解决方案。它只是为了说明 importance 函数在回答您的问题时的用法。您可能想在 Cross Validated 上询问有关使用 randomForest.

的详细信息的适当问题