【问题标题】:Train function in caret returns error message插入符号中的训练函数返回错误消息
【发布时间】:2017-07-21 15:21:18
【问题描述】:

我正在使用 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】:

    你可以试试这个:

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

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

    以下内容对我有用:

    levels(train$cls) <- make.names(levels(train$cls)) 
    set.seed(12)
    train(cls ~ ., data = train,method = "rpart",tuneLength = 5,
                         metric = "ROC", trControl = trainControl(summaryFunction = twoClassSummary,  classProbs = TRUE))
    

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 2018-09-19
      • 2017-03-01
      • 1970-01-01
      • 2021-01-22
      • 2019-09-06
      • 2011-09-19
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多