没有提供数据,但代码可能很容易理解。我正在使用嵌套for循环,并希望保存结果。我们怎么可能做到呢?
library(ranger)
n_folds = 10
hyper_grid <- expand.grid(
mtry = seq(5, 30, 15),
min.node.size = seq(1, 4, 4)
)
for (i in 1:n_folds) {
select <- cv_ind!=i
data.train <- train_data[select,]
data.test <- train_data[!select,]
for (j in unique(hyper_grid$mtry)) {
for (k in unique(hyper_grid$min.node.size)) {
rf_mod <- ranger(target~., num.trees = 500, mtry = j, min.node.size =k,
data = data.train, classification = TRUE, replace = FALSE,
importance = "permutation", oob.error = TRUE,
splitrule = "gini", keep.inbag = TRUE)
pred <- predict(rf_mod, data = data.test[,-data.test$target], type = "response")
accur <- sum(diag(table(pred$predictions, data.test$target)))/25
x[i,] <- accur
}
}
}
您可以使用mapply 尝试此解决方案
n_folds <- 10
hyper_grid <- expand.grid(
mtry = seq(5, 30, 15),
min.node.size = seq(1, 4, 4),
# add folds to hypergrid
fold_index = c(1:n_folds)
)
# putting a complete smallest iteration in one function for easier
# understanding
make_model_list <- function(mtry,
min.node.size,
i){
select <- cv_ind!=i
data.train <- train_data[select,]
data.test <- train_data[!select,]
rf_mod <- ranger(target~., num.trees = 500, mtry = j, min.node.size =k,
data = data.train, classification = TRUE, replace = FALSE,
importance = "permutation", oob.error = TRUE,
splitrule = "gini", keep.inbag = TRUE)
pred <- predict(rf_mod, data = data.test[,-data.test$target], type = "response")
accur <- sum(diag(table(pred$predictions, data.test$target)))/25
# put the results you want to keep in the res list
# i put all in there as an example
res <- list(mtry = mtry,
min.node.size=min.node.size,
fold_index=i,
model= rf_mod
prediction = pred,
accur = accur)
return(res)
}
result <- mapply(make_model_list,
hyper_grid$mtry,
hyper_grid$min.node.size,
hyper_grid$fold_index,
SIMPLIFY = FALSE)
# result is then readable like this for example
result[[1]]$min.node.size
您可以根据需要更改make_model_list
的输出。使用此解决方案的好处是,您可以使用Pbapply
轻松添加进度条