使用R,有没有办法训练和交叉验证F1分数的随机森林算法?

问题描述

我有类不平衡的数据(响应变量有两个类,其中一个类比另一个类更为常见)。在这种情况下,准确度似乎并不是训练模型的好指标(我可以获得99%的准确度,并对少数群体完全错误分类)。我认为使用F1分数会更有益。

有没有人尝试使用F1分数作为R中的训练指标? 我尝试修改虹膜数据集以使物种成为二进制变量并运行随机森林。有人可以帮我调试一下吗?

library(caret)
library(randomForest) 

data(iris)

iris$Species = ifelse(iris$Species == "setosa","a","b") 

iris$Species = as.factor(iris$Species) 

f1 <- function (data,lev = NULL,model = NULL) {
                precision <- posPredValue(data$pred,data$obs,positive = "pass")
                recall <- sensitivity(data$pred,postive = "pass") 
                f1_val <- (2 * precision * recall) / (precision + recall) 
                names(f1_val) <- c("F1")
                f1_val }


train.control <- trainControl(method = "repeatedcv",number = 10,repeats = 3,classprobs = TRUE,#sampling = "smote",summaryFunction = f1,search = "grid")
tune.grid <- expand.grid(.mtry = seq(from = 1,to = 10,by = 1)) 

random.forest.orig <- train(Species ~ .,data = iris,method = "rf",tuneGrid = tune.grid,metric = "F1",trControl = train.control)

给出以下错误

Something is wrong; all the F1 metric values are missing:
       F1     
 Min.   : NA  
 1st Qu.: NA  
 Median : NA  
 Mean   :NaN  
 3rd Qu.: NA  
 Max.   : NA  
 NA's   :10   
Error: Stopping
In addition: There were 50 or more warnings (use warnings() to see the first 50)
5: stop("Stopping",call. = FALSE)
4: train.default(x,y,weights = w,...)
3: train(x,...)
2: train.formula(Species ~ .,trControl = train.control)
1: train(Species ~ .,trControl = train.control)
> warnings()
Warning messages:
1: In randomForest.default(x,mtry = param$mtry,...) :
  invalid mtry: reset to within valid range

来源:Training Model in Caret Using F1 Metric

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)