【问题标题】:What do xtest= and ytest= do in the randomForest algorithm in R?xtest= 和 ytest= 在 R 中的 randomForest 算法中做了什么?
【发布时间】:2015-02-21 20:37:54
【问题描述】:

我正在拟合一个随机森林,并使用以下代码将我的数据分成训练集和测试集:

train <- sample( 1:nrow(Boston), (nrow(Boston))/2) ) 编辑:在这里,train 显然只是一个索引,因此测试集如下:

testB <- Boston[-train,]; head(test); length(test) 响应变量名称为 medy,位于第十四列。

我的随机森林也有以下代码(实际上我在这里装袋,因为我的数据集中的变量总数为 13):

bag.boston1 <- randomForest(medv~., data=Boston, subset=train, mtry=13, importance=TRUE, ytest=testB$medv, xtest= )

我对 ytest= 选项的论证是否正确?我假设是因为它只是测试数据集中的响应变量。

另外,我应该为 xtest= 选项使用什么参数?

我的一个想法是从我的测试数据集中消除响应变量,从而创建一个仅测试数据集中预测变量的数据框,然后我可以让 xtest 参数成为结果 x 矩阵:

`x <- testB`

x[14] <- NULL  # because the 14th column is the response variable

bag.boston1 <- randomForest(medv~., data=Boston, subset=train, mtry=13,
                        importance=TRUE, ytest=testB$medv, xtest=x)

【问题讨论】:

  • 我建议将下面的答案标记为解决方案

标签: r random-forest


【解决方案1】:

来自randomForest的文档:

如果给定xtest,则测试集的预测将在树木生长时“就地”完成。如果还给出了ytest,并且do.trace 设置为某个正整数,那么对于每个do.trace 树,都会打印测试集错误。测试集的结果在生成的randomForest 对象的测试组件中返回。对于分类,投票组件(用于训练或测试集数据)包含为类收到的案例的投票。如果norm.votes=TRUE,则给出分数,可以作为类的预测概率。

从这里可以理解,仅将响应变量传递给ytest 参数,并不会改变randomForest 的工作方式。

如果您希望randomForest 函数“就地”做出预测,即当树木生长时,您必须将不带预测变量的测试数据传递给xtest 参数,如下所示:

bag.boston1 <- randomForest(medv~., data=Boston, subset=train, mtry=13, importance=TRUE, 
                            xtest=subset(testB, select=-medv))

预测结果可以通过:bag.boston1$test$predicted访问

由于在这种情况下您还有测试数据的响应变量,您可以使用 ytest 变量传递它:

bag.boston2 <- randomForest(medv~., data=Boston, subset=train, mtry=13, importance=TRUE, 
                            xtest=subset(testB, select=-medv), ytest=testB$medv)

在这种情况下,除了预测之外,我们还获得了一些附加值。它们是,mse 表示均方误差,rsq 表示 r-squared,两者都适用于在regression 的情况下生长的每一棵树。对于classification,它们是:err.rate,即每棵树的测试错误率,confusion 用于混淆矩阵,votes 给出每个输出类的投票数(或标准化投票数)。

以上所有值都可以使用:bag.boston2$test

【讨论】:

    猜你喜欢
    • 2014-08-03
    • 2016-11-19
    • 2011-11-11
    • 1970-01-01
    • 2019-04-14
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多