Select tuneGrid 取决于插入符 R 中的模型

Select tuneGrid depending on the model in caret R

我尝试使用“knn”和“rpart”算法在鸢尾花数据集上应用机器学习。这是我的代码:

library(tidyverse)
library(caret)

dataset <- iris
tt_index <- createDataPartition(dataset$Sepal.Length, times = 1, p = 0.9, list = FALSE)
train_set <- dataset[tt_index, ]
test_set <- dataset[-tt_index, ]

models <- c("knn","rpart")

fits <- lapply(models, function(model){ 
  print(model)
  train(Species ~ ., 
        data = train_set, 
        tuneGrid = case_when(model == "knn" ~ data.frame(k = seq(3,50,1)),
                             model == "rpart" ~ data.frame(cp = seq(0,0.1,len = 50))),
        method = model)
})

我想根据内部模型设置 tuneGrid 参数 lapply。但是我收到这个错误:

Error in `[.data.frame`(value[[1]], rep(NA_integer_, m)) : 
  undefined columns selected 

任何帮助将不胜感激。

我们可以使用 if/else

library(caret)    
out <- lapply(models, function(model)
   train(Species ~ ., data = train_set, 
     tuneGrid = if(model == "knn") data.frame(k = seq(3,50,1)) else 
         data.frame(cp = seq(0,0.1,len = 50)), method = model))

根据?case_when

A vector of length 1 or n, matching the length of the logical input or output vectors, with the type (and attributes) of the first RHS. Inconsistent lengths or types will generate an error.