简体   繁体   中英

Read multiple rds models and use predict function in lapply?

I have bunch of models saved as .rds, after reading all models and I use the predict function in loop on test data, showing error on predict method, but using individual model is working. (model are built using mlr package)

I read all models from a folder and use lapply on the test data,

files = list.files(path = 'C:/rf_models', pattern = '\\.rds$', full.names = TRUE)
read_models <- do.call("rbind", lapply(files, readRDS))
print(lapply(read_models, function (x) predict(x, newdata = as.data.frame(test_data))))

its showing below Error and opening a Browse[1]> in console

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('FilterWrapper', 'BaseWrapper', 'Learner')"
Called from: predict(x, newdata = as.data.frame(test_data))
Browse[1]>

Even if I use for loop

for (i in 1:80){
  pred_models <- predict(read_models[[i]], newdata = as.data.frame(test_data))
}

also showing

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('FilterWrapper', 'BaseWrapper', 'Learner')"

All done in same R script where mlr library I already loaded

if I read model individually, it is working

model <- readRDS("C:/rf_models/rf_models_31.rds")
prediction <- predict(model, newdata = as.data.frame(test_data))
prediction
Prediction: 1 observations
predict.type: prob
threshold: 0=0.50,1=0.50
time: 0.03
  truth prob.0 prob.1 response
1     0   0.12   0.88        1

I expect the pred_models to have all the predictions stored.

just loading using the file names it worked

files = list.files(path = 'C:/rf_models', pattern = '.rds$', full.names = TRUE)
for (i in 1:80){
  model <- readRDS(files[i])
  prediction <- predict(model, newdata = as.data.frame(test_data))
  print(prediction)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM