如何在R中使用Caret软件包进行培训、验证和测试?
我是使用Caret软件包进行培训、验证和测试的初学者。我在网上进行了研究,发现它有点让人困惑(看起来大多数都是在没有验证的情况下进行训练和测试),你能给出一个代码示例来说明它是如何工作的吗?如何在R中使用Caret软件包进行培训、验证和测试?,r,R,我是使用Caret软件包进行培训、验证和测试的初学者。我在网上进行了研究,发现它有点让人困惑(看起来大多数都是在没有验证的情况下进行训练和测试),你能给出一个代码示例来说明它是如何工作的吗?train允许你进行验证和其他操作。您可以向trControl参数提供trainControl函数,该函数允许您指定培训过程的详细信息。默认情况下,train已将75%的数据拆分为用于培训的数据,将25%的数据拆分为用于验证的数据,您也可以在trainControl中对此进行更改 我建议您查阅train和tr
train
允许你进行验证和其他操作。您可以向trControl
参数提供trainControl
函数,该函数允许您指定培训过程的详细信息。默认情况下,train
已将75%的数据拆分为用于培训的数据,将25%的数据拆分为用于验证的数据,您也可以在trainControl
中对此进行更改
我建议您查阅train
和trainControl
文档,并了解有关您可以在培训程序中指定的详细信息
下面是一个简单的示例,使用5倍交叉验证训练随机林,并使用插入符号和train
函数对数据进行标准化,以更好地举例说明
(注意:我添加了一些不必要的东西,例如verbositer=TRUE
和classProbs=TRUE
只是为了向您展示使用插入符号获得的一些特性)
希望这对您有所帮助您应该遵循一个教程,例如:拆分为训练和验证。以后再测试。
library(caret)
library(datasets)
# Loading the iris dataset
data(iris)
# Specifying an 80-20 train-test split
train_idx = createDataPartition(iris$Species, p = .8, list = F)
# Creating the training and testing sets
train = iris[train_idx, ]
test = iris[-train_idx, ]
# Declaring the trainControl function
train_ctrl = trainControl(
method = "cv", #Specifying Cross validation
number = 5, # Specifying 5-fold
verboseIter = TRUE, # So that each iteration you get an update of the progress
classProbs = TRUE # So that you can obtain the probabilities for each example
)
rf_model = train(
Species ~., # Specifying the response variable and the feature variables
method = "rf", # Specifying the model to use
data = train,
trControl = train_ctrl,
preProcess = c("center", "scale") # Do standardization of the data
)
# Get the predictions of your model in the test set
predictions = predict(rf_model, newdata = test)
# See the confusion matrix of your model in the test set
confusionMatrix(predictions, test$Species)