0

I am working with a classification tree model that allows me to classify raster images (to create maps). I would like to reapply this classification tree to a new raster dataset, in another script. I tried to save the model as .rda or .RData file but I have the same problem it's impossible to predict the model on the new dataset.

no applicable method for 'predict' applied to an object of class "character"

I'm pretty sure the problem is due to the save function of the model since it does not appear entirely:

summary(model)
#   Length     Class      Mode 
#        1 character character

I'm saving my model with this code :

save(cuttreedown.training, file =("Artmac.rda")

and load it with :

model <- load("Artmac.rda")

And this is my predict function where satImage is my raster file (the function is working well on another script) :

predict(satImage, model, filename="test.tif", progress='text', datatype='INT1U', type='prob', overwrite=TRUE)

I just want to apply my model on a new raster dataset as it is done in the training script.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
J.Cpa
  • 3
  • 1

2 Answers2

1

You can use saveRDS/loadRDS for such a task. Here is a full example:

library(rpart)

data(iris)
fit <- rpart(Species~., data = iris)

saveRDS(fit, "fit.rds")
load_fit <- readRDS("fit.rds")

all.equal(predict(load_fit, iris),
          predict(fit, iris))
#output
TRUE
missuse
  • 19,056
  • 3
  • 25
  • 47
0

simply save and load the model without an extension. Also, don't create a new object when loading, it will automatically populate the model object into the environment. Try:

save(cuttreedown.training, file="Artmac")

load("Artmac")

summary(Artmac)
jlab
  • 252
  • 2
  • 18
  • No it's not working I have exactly the same problem, it's like it's not really saving my model. But thanks for the answer. – J.Cpa Feb 08 '18 at 12:37
  • Providing a [minimal](https://stackoverflow.com/help/mcve) and [reproducible](https://stackoverflow.com/q/5963269/3250126) example would help the troubleshooting process. – jlab Feb 08 '18 at 12:38