0
votes

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.

1
I assume reading multiple .rds models is not working properlyhanzgs
I am not sure if do.call("rbind") does good things here. Why don't you use a simple lapply here?pat-s

1 Answers

0
votes

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)
}