插入符号中的训练函数返回错误消息

问题描述 投票:2回答:1

我正在使用caret train()函数为通过自定义函数采用F1作为度量标准的CART决策树找到最佳cp值。 train()函数返回我无法理解的错误。也许问题出在我定义可复制示例的方式上?

> library(data.table)
> library(ROSE)
> data(hacide)
> train <- hacide.train
> test <- hacide.test
> numFolds = trainControl(method = "cv" , number = 10)
> cpGrid = expand.grid(.cp = seq(0.01, 0.5, 0.01))
> f1 <- function(data, lev = NULL, model = NULL) {
+   f1_val <- F1_Score(y_pred = data$pred, y_true = data$obs, positive = lev[1])
+   c(F1 = f1_val)
+ }
> set.seed(12)
> train(cls ~ ., data = train,
+              method = "rpart",
+              tuneLength = 5,
+              metric = "F1",
+              trControl = trainControl(summaryFunction = f1, 
+                                       classProbs = TRUE))
Error in train.default(x, y, weights = w, ...) : 
  At least one of the class levels is not a valid R variable name; This will cause errors when class probabilities are generated because the variables names will be converted to  X0, X1 . Please use factor levels that can be used as valid R variable names  (see ?make.names for help).
> levels(train$cls)
[1] "0" "1"
> class(train$cls)
[1] "factor"
r r-caret
1个回答
0
投票

您可以尝试这个:

levels(train$cls) <- make.names(levels(train$cls)) 

然后运行模型,这应该可以解决您的问题,不幸的是,您的示例无法重现,因为您在问题中错过了F1_Score函数定义。看看是否可行。

© www.soinside.com 2019 - 2024. All rights reserved.