【问题标题】:Predict using randomForest package in R在 R 中使用 randomForest 包进行预测
【发布时间】:2017-01-11 13:05:36
【问题描述】:

如何使用 R 中 randomForrest 调用的结果来预测一些未标记数据(例如要分类的真实世界输入)上的标签?
代码:

train_data = read.csv("train.csv")
input_data = read.csv("input.csv")
result_forest = randomForest(Label ~ ., data=train_data)
labeled_input = result_forest.predict(input_data) # I need something like this

train.csv:

a;b;c;label;
1;1;1;a;
2;2;2;b;
1;2;1;c;

输入.csv:

a;b;c;
1;1;1;
2;1;2;

我需要这样的东西

a;b;c;label;
1;1;1;a;
2;1;2;b;

【问题讨论】:

  • predict(result_forest, newdata=input_data).
  • @eipi10,非常感谢。那是我使用 R 的第一天。您可以将您的评论重写为答案,让我接受它
  • Stack Overflow 上有很多与predict 相关的问题,所以我猜这个问题可能是重复的。不需要我添加答案。要记住以备将来参考的关键是,几乎每个建模函数都是 R 有一个predict“方法”,这意味着如果您在模型对象上运行predict,它将默认返回训练数据的预测,如果您使用 newdata 参数,则可以预测新数据。

标签: r machine-learning random-forest


【解决方案1】:

如果这就是你的意思,请告诉我。

你用你的训练数据训练你的随机森林:

# Training dataset
train_data <- read.csv("train.csv")
#Train randomForest
forest_model <- randomForest(label ~ ., data=train_data)

现在随机森林已经过训练,您想为其提供新数据,以便它可以预测标签是什么。

input_data$predictedlabel <- predict(forest_model, newdata=input_data)

上面的代码向您的 input_data 添加了一个新列,显示了预测的标签。

【讨论】:

    【解决方案2】:

    你可以使用预测功能

    例如:

    data(iris)
    set.seed(111)
    ind <- sample(2, nrow(iris), replace = TRUE, prob=c(0.8, 0.2))
    iris.rf <- randomForest(Species ~ ., data=iris[ind == 1,])
    iris.pred <- predict(iris.rf, iris[ind == 2,])
    

    这是来自http://ugrad.stat.ubc.ca/R/library/randomForest/html/predict.randomForest.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-23
      • 2016-04-24
      • 1970-01-01
      • 2016-11-11
      • 2013-10-18
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      相关资源
      最近更新 更多