【问题标题】:Using a FOR-loop to calculate AUC of multiple dataframes使用 FOR 循环计算多个数据帧的 AUC
【发布时间】:2021-08-26 10:12:09
【问题描述】:

对于某个问题,我想对多个数据集执行 RandomForest 分类器并比较所述数据集的 AUC。我想使用“惰性”方法,因此我不想对多个数据集进行 n 次分类,而是想使用 for 循环来代替。

因此,一个循环遍历多个数据集的 for 循环,执行随机森林分类,计算 AUC 并将该 AUC 存储在一个空矩阵/数据帧中。结果应该是一个表格/矩阵,它向我显示每个数据集的列和显示每个数据集的 AUC 的行。

我使用 Iris 数据集准备了一些代码以开始使用,但没有任何使用 for 循环解决此类问题的经验。希望有人可以帮助我,甚至让我朝着正确的方向思考!?

例子:

require(pROC)
require(randomForest)

#use the Iris dataset as example
data(iris)

#make a simple 2-class outcome over the Iris dataset
iris <- iris[-which(iris$Species=="setosa"),]
iris$Species<-as.factor(as.character(iris$Species))

#create list of dataframes we want to use
df1 <- iris
df2 <- iris
df_list <- list(df1, df2)

#create empty matrix to store results in
results_matrix <- matrix(ncol=2, nrow=1)

#create a for loop to calculate and store AUC of each dataframe 
for(df in df_list){
  rf_model <- randomForest::randomForest(Species ~., data = df)
  rf_model_roc <- roc(iris$Species,rf_model$votes[,2])
  df_auc <- auc(rf_model_roc)
  
  #store df_auc of each df in results_matrix
    }

【问题讨论】:

    标签: r for-loop


    【解决方案1】:

    您可以创建一个向量来存储来自 AUC 的值。

    例如,

    #create list of dataframes we want to use
    df1 <- iris
    df2 <- iris
    df_list <- list(df1, df2)
    
    results_vec <- numeric(length(df_list))
    
    #create a for loop to calculate and store AUC of each dataframe 
    for(i in seq_along(df_list)) {
      data <- df_list[[i]]
      rf_model <- randomForest::randomForest(Species ~., data = data)
      rf_model_roc <- roc(data$Species,rf_model$votes[,2])
      results_vec[i] <- as.numeric(auc(rf_model_roc))
    }
    
    results_vec
    

    【讨论】:

    • 谢谢,这就是我想要的输出!只需将 df_auc[i] 更改为 results_vec[i] ,然后您的脚本就可以正常运行了。
    猜你喜欢
    • 2021-06-18
    • 2022-06-24
    • 2023-03-19
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2021-10-15
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多