随机森林的动态响应变量
Dynamic response variable for random forest
我正在尝试创建一个动态 ML 应用程序,它允许用户使用随机森林模型上传数据集以获得数据集中第一列的预测。
我在使用 randomforest()
函数时遇到问题,特别是当我尝试将响应变量指定为数据集的第一列时。对于下面的示例,我使用了 iris 数据集 并且我已经将响应变量 Species 移动到第一列中。
这是我的尝试:
model <- randomForest(names(DATA[1]) ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
但是,这不起作用。
我得到的错误是:
错误:变量长度不同(找到 'Species')
只有当我像这样手动指定响应变量时,应用程序和功能才有效:
model <- randomForest(Species ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
我曾尝试使用 paste()
函数来施展魔法,但没有成功。
我应该如何编写代码才能使其正常工作?
您似乎想从字符串构建公式。您可以使用 eval
和 parse
来做到这一点。这样的事情应该有效:
model <- randomForest(eval(parse(text = paste(names(DATA)[1], "~ ."))),
data = DATA, ntree = 500, mtry = 3, importance = TRUE)
使用原始鸢尾花数据集的示例:
model <- randomForest(eval(parse(text = paste(names(iris)[5], "~ ."))),
data = iris, ntree = 500, mtry = 3, importance = TRUE)
model
Call:
randomForest(formula = eval(parse(text = paste(names(iris)[5], "~ ."))), data = iris,
ntree = 500, mtry = 3, importance = TRUE)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 3
OOB estimate of error rate: 4%
Confusion matrix:
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 47 3 0.06
virginica 0 3 47 0.06
我正在尝试创建一个动态 ML 应用程序,它允许用户使用随机森林模型上传数据集以获得数据集中第一列的预测。
我在使用 randomforest()
函数时遇到问题,特别是当我尝试将响应变量指定为数据集的第一列时。对于下面的示例,我使用了 iris 数据集 并且我已经将响应变量 Species 移动到第一列中。
这是我的尝试:
model <- randomForest(names(DATA[1]) ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
但是,这不起作用。 我得到的错误是:
错误:变量长度不同(找到 'Species')
只有当我像这样手动指定响应变量时,应用程序和功能才有效:
model <- randomForest(Species ~ ., data = DATA, ntree = 500, mtry = 3, importance = TRUE)
我曾尝试使用 paste()
函数来施展魔法,但没有成功。
我应该如何编写代码才能使其正常工作?
您似乎想从字符串构建公式。您可以使用 eval
和 parse
来做到这一点。这样的事情应该有效:
model <- randomForest(eval(parse(text = paste(names(DATA)[1], "~ ."))),
data = DATA, ntree = 500, mtry = 3, importance = TRUE)
使用原始鸢尾花数据集的示例:
model <- randomForest(eval(parse(text = paste(names(iris)[5], "~ ."))),
data = iris, ntree = 500, mtry = 3, importance = TRUE)
model
Call:
randomForest(formula = eval(parse(text = paste(names(iris)[5], "~ ."))), data = iris,
ntree = 500, mtry = 3, importance = TRUE)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 3
OOB estimate of error rate: 4%
Confusion matrix:
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 47 3 0.06
virginica 0 3 47 0.06