9

The svm model is created with the package e1071 in R. To use the model, I need to save it and read as needed. The package has write.svm, but does not have read.svm. If I use

model <- svm(x, y)

save(model, 'modelfile.rdata')
M <- load('modelfile.rdata')

object M contains just the word 'model'.

How to save the svm model and read back later, to apply to some new data?

Señor O
  • 17,049
  • 2
  • 45
  • 47
Marina
  • 333
  • 1
  • 3
  • 9

2 Answers2

9

Look at the return value for the function load in the help file:

Value:

 A character vector of the names of objects created, invisibly.

So "model" is indeed the expected value of M. Your svm has been restored under its original name, which is model.

If you find it a bit confusing that load does not return the object loaded but instead restores it under the name used in saving it, consider using saveRDS and readRDS.

saveRDS(model, 'modelfile.rds')
M <- readRDS('modelfile.rds')

and M should contain your svm model.

I prefer saveRDS and readRDS because with them I know what objects I'm creating in my workspace - see the blog post of Gavin Simpson (linked in his answer) for a detailed discussion.

James King
  • 6,229
  • 3
  • 25
  • 40
  • It works, except the function is called not 'loadRDS', but 'readRDS'. Thanks! – Marina Jun 12 '14 at 23:18
  • @user3276530 Oops, fixed now. If your issue has been resolved please consider accepting one of the answer by clicking the check mark next to it. – James King Jun 12 '14 at 23:28
  • I'm getting `no applicable method for 'predict' applied to an object of class "tune"` error with the below line of code: `svm.pred <- predict(get("svm.model"), testData[,-17])`, pls suggest. – Ram Dwivedi Jun 20 '15 at 15:45
5

You misunderstand what load does. It restores an object to the same name it had when you save()d it. What you are seeing in M is the return value of the load() function. Calling load() has the additional side effect of loading the object back under the same name that it was saved with.

Consider:

require("e1071")
data(iris)

## classification mode
# default with factor response:
model <- svm (Species~., data=iris)
## Save it
save(model, file = "my-svm.RData")
## delete model
rm(model)
## load the model
M <- load("my-svm.RData")

Now look at the workspace

> ls()
[1] "iris"  "M"     "model"

Hence model was restored as a side effect of load().

From ?load we see the reason M contains the name of the objects created (and hence saved originally)

Value:

     A character vector of the names of objects created, invisibly.

If you want to restore an object to a new name, use saveRDS() and readRDS():

saveRDS(model, "svm-model.rds")
newModel <- readRDS( "svm-model.rds")
ls()

> ls()
 [1] "iris"     "M"        "model"    "newModel"

If you want to know more about saveRDS() and readRDS() see the relevant help ?saveRDS() and you might be interested in a blog post I wrote on this topic.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453