2
votes

I'm having issues loading a random forest model and applying it to a raster with raster::predict.

Normally, when I create a random forest model in an R session, type its name and hit enter I receive the following print out:

> rf_model
Call:
 randomForest(formula = AGB_mean ~ B1_med + B2_med + B4_med +      B5_med + B6_med + B7_med + B1_sd + B2_sd + B4_sd + B5_sd +      B6_sd + B7_sd + NDVI + EVI + EVI2, data = all.training, importance = TRUE, na.action = na.roughfix) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 5

          Mean of squared residuals: 4866.287
                    % Var explained: 52.48

When I apply this in-session model to a raster using predict, I can make successful predictions.

When I instead load a saved random forest model using readRDS and type the model name like so:

> rf_model <- readRDS('model.rds')
> rf_model

I receive a full print out of all the information in rf_model (i.e. rf_model$call, rf_model$type... rf_model$terms), and when I try to make predictions I receive the following error:

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('randomForest.formula', 'randomForest')"

Is there something I'm missing here on properly loading a random forest object?

2
What code you have used for predict function, show that in your question also. - Bappa Das
Hi @GeoCat333, I read the updated question.. how come you are using raster::predict on a randomForest object? - StupidWolf

2 Answers

2
votes

For example:

library(randomForest)
rf_model <- randomForest(Species ~ .,data=iris)
saveRDS(rf_model,'model.rds')
quit()

If I start R again, I need to load the library:

rf_model <- readRDS('model.rds')
predict(rf_model)
Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('randomForest.formula', 'randomForest')"

library(randomForest)
head(predict(rf_model))

     1      2      3      4      5      6 
setosa setosa setosa setosa setosa setosa 
Levels: setosa versicolor virginica
0
votes

You need to import the random forest library so that the predict method for randomForest objects will be available, like so:

library(randomForest)
rf_model <- readRDS('model.rds')
predict(rf_model)

Even though you have saved a randomForest instance in your RDS file, the function-methods associated with a randomForest instance are not saved in that RDS file, and need to be loaded from the library itself.