gpt4 book ai didi

r - 使用变量在 R 中的预测函数中定义训练列

转载 作者:行者123 更新时间:2023-12-04 18:02:14 25 4
gpt4 key购买 nike

假设我们有以下代码(此问题的训练/测试分区无关紧要)。

library(caret)
data(iris)
train( Species ~ .,data=iris, method="rf" )

现在运行良好。我想要做的是提供我试图使用变量预测的列(因为我要从 GUI 中获取它)。让我们使用下面的示例代码:

library(caret)
data(iris)
colName <- 'Species'
train( colName ~ .,data=iris, method="rf" )

这不起作用,因为 colName 不是数据集中的列之一。那么有没有办法做到这一点?我到处搜索,一无所获。有人请帮助我:(。

最佳答案

这是一个足够简单的案例,所以按以下方式使用 paste 应该没问题:

library(caret)
data(iris)
colName <- 'Species'

#create the formula using as.formula and paste
formula <- as.formula(paste(colName, ' ~ .' ))

#run model
train(formula, data=iris, method="rf" )

输出:

> train( formula,data=iris, method="rf" )
Random Forest

150 samples
4 predictor
3 classes: 'setosa', 'versicolor', 'virginica'

No pre-processing
Resampling: Bootstrapped (25 reps)

Summary of sample sizes: 150, 150, 150, 150, 150, 150, ...

Resampling results across tuning parameters:

mtry Accuracy Kappa Accuracy SD Kappa SD
2 0.9481249 0.9216819 0.02790700 0.04200793
3 0.9473557 0.9205465 0.02893104 0.04347956
4 0.9466284 0.9194525 0.02920803 0.04388548

Accuracy was used to select the optimal model using the largest value.
The final value used for the model was mtry = 2.

关于r - 使用变量在 R 中的预测函数中定义训练列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33215077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com