【问题标题】:Calculating AUC on Random Forest Model in R在 R 中计算随机森林模型的 AUC
【发布时间】:2021-04-26 10:44:28
【问题描述】:

我正在尝试计算我的两个模型随机森林和朴素贝叶斯的 AUC 但得到相同的错误 ""$ operator is invalid for atomic vectors" 。 请问您有什么想法吗?

背景:目标变量“诊断”是非数值型,具有 B 和 M 值

这是射频模型的示例代码

fitControl <- trainControl(method="cv",number = 5,preProcOptions = list(thresh = 0.4),classProbs = TRUE,summaryFunction = twoClassSummary)

wdbc_model_rf <- train(Diagnosis~.,train_wdbc,method="ranger",metric="ROC",preProcess = c('center', 'scale'),trControl=fitControl)

【问题讨论】:

  • 如果您将诊断变量转换为虚拟变量(例如 B 为 1,M 为 0),您仍然会收到错误吗?
  • 嗨菲尔,是的,这可以解决问题,但随机森林需要我的目标变量的字符类型值。下面是代码的其余部分 wdbc_predicions_rf

标签: r random-forest r-caret auc


【解决方案1】:

下面是一个有效的 R 代码示例。请注意:您对 ROC 的兴趣意味着只有两个课程。

Predict <- function(class_obj, newdata, Param) {

if(Param$method == 'RF') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'prob')
} else if(Param$method == 'GBM') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'response', n.trees = Param$n.trees)[,,1]
} else if(Param$method == 'SVM') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'probabilities')
} else if(Param$method == 'logit') {
    Predicted_Probs         <- predict(class_obj, newdata = newdata, type = 'response')
    Predicted_Probs         <- cbind(1 - Predicted_Probs, Predicted_Probs)
} else { 
    cat('\nPredict(): unknown classification method.')
}

Predicted_Probs[,2]

}

@@@

AUC <- function(Truth, Predicted_Probs) {

###########################################################################################################
# SETTINGS

d_Prob              <- 0.01

###########################################################################################################
# CALCULATIONS

Prob_Grid               <- seq(1, 0, -d_Prob)
NP                  <- length(Prob_Grid)
True_Positive_Rate      <- c()
False_Positive_Rate     <- c()

for(Prob_Threshold in Prob_Grid) {
    Forecast                <- as.factor( c(0, 1, 1 * (Predicted_Probs >= Prob_Threshold)) )
    levels(Forecast)            <- c('0', '1')
    Forecast                <- Forecast[-c(1,2)]
    Table               <- xtabs(~Truth + Forecast)
    False_Positive_Rate     <- c(False_Positive_Rate, Table[1,2] / (Table[1,1] + Table[1,2]))
    True_Positive_Rate      <- c(True_Positive_Rate, Table[2,2] / (Table[2,1] + Table[2,2]))
}

AUC                 <- 0

for(i in 2:NP) {
    AUC                 <- AUC + True_Positive_Rate[i] * (False_Positive_Rate[i] - False_Positive_Rate[i-1])
}

AUC

}

请注意:代码非常通用,可以应用于许多方法,例如support vector machinesgradient boostingrandom forests 等。希望可以直接根据需要修改代码。

【讨论】:

  • 嗨斯坦斯,谢谢,但由于某种原因它对我不起作用。有什么方法可以轻松地将诊断输出转换为数字?尝试 as.matrix(Diagnosis) 但它没有工作 'wdbc_roc_rf
  • AUC 仅在分类设置中定义。所以你的因变量必须是分类的。您正在解决分类问题,而不是回归问题。如果您的因变量是“0”和“1”级别的因子,我的代码将起作用。
猜你喜欢
  • 2019-11-08
  • 2021-06-12
  • 2019-12-29
  • 2016-02-21
  • 2020-02-25
  • 2022-11-11
  • 1970-01-01
  • 2016-02-25
  • 2013-07-22
相关资源
最近更新 更多