Caret package Custom metric

后端 未结 2 1049
清酒与你
清酒与你 2020-12-24 09:07

I\'m using the caret function \"train()\" in one of my project and I\'d like to add a \"custom metric\" F1-score. I looked at this url caret package But I cannot understand

相关标签:
2条回答
  • 2020-12-24 09:36

    You should look at The caret Package - Alternate Performance Metrics for details. A working example:

    library(caret)
    library(MLmetrics)
    
    set.seed(346)
    dat <- twoClassSim(200)
    
    ## See https://topepo.github.io/caret/model-training-and-tuning.html#metrics
    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(35)
    mod <- train(Class ~ ., data = dat,
                 method = "rpart",
                 tuneLength = 5,
                 metric = "F1",
                 trControl = trainControl(summaryFunction = f1, 
                                          classProbs = TRUE))
    
    0 讨论(0)
  • 2020-12-24 10:01

    For the two-class case, you can try the following:

    mod <- train(Class ~ ., 
                 data = dat,
                 method = "rpart",
                 tuneLength = 5,
                 metric = "F",
                 trControl = trainControl(summaryFunction = prSummary, 
                                          classProbs = TRUE))
    

    or define a custom summary function that combines both twoClassSummary and prSummary current favorite which provides the following possible evaluation metrics - AUROC, Spec, Sens, AUPRC, Precision, Recall, F - any of which can be used as the metric argument. This also includes the special case I mentioned in my comment on the accepted answer (F is NA).

    comboSummary <- function(data, lev = NULL, model = NULL) {
      out <- c(twoClassSummary(data, lev, model), prSummary(data, lev, model))
    
      # special case missing value for F
      out$F <- ifelse(is.na(out$F), 0, out$F)  
      names(out) <- gsub("AUC", "AUPRC", names(out))
      names(out) <- gsub("ROC", "AUROC", names(out))
      return(out)
    }
    
    mod <- train(Class ~ ., 
                 data = dat,
                 method = "rpart",
                 tuneLength = 5,
                 metric = "F",
                 trControl = trainControl(summaryFunction = comboSummary, 
                                          classProbs = TRUE))
    
    
    
    0 讨论(0)
提交回复
热议问题