Why does load (...) return the symbol name of the object instead of the object itself?

The svm model is created with the e1071 package in R. To use this model, I need to save and read it 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 only the word "model".

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

+6
source share
2 answers

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

Value:

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

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

If you are a little confused that load does not return the loaded object, but instead restores it under the name used to save 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 create in my workspace - see Gavin Simpson's blog post (linked in his answer) for a detailed discussion.

+4
source

You misunderstand what load does. It restores an object with the same name as with save() d. What you see in M is the return value of the load() function. The load() call has an additional side effect of returning the object back under the same name with which it was saved.

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 let's look at the workspace

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

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

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

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

If you want to restore the object for 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 related help ?saveRDS() , and you might be interested in a blog post that I wrote on this topic .

+3
source

Source: https://habr.com/ru/post/970784/


All Articles