Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Machine Learning models in R

I am using R to create some basic machine learning models. I use the klar, caret and e1071 packages. Here is the code that generates my model

library(e1071)
library(klaR)
library(caret)



x = iris[,-5]

y = iris$Species

model = train(x,y,'nb',trControl = trainControl(method='cv',number=10))

i was wondering,is it possible to save this model somewhere and reference it later ? For example, in python we can use the pickle package to do

nbClassifier = nltk.NaiveBayesClassifier.train(featureSets)

saveNBClassifier = open("abtNBClassifier.pickle","wb")

pickle.dump(nbClassifier, saveNBClassifier)

saveNBClassifier.close()

and later

open_file = open("abtNBClassifier.pickle", "rb")

classifier = pickle.load(open_file)

open_file.close()

is something similar possible in R ?

like image 927
AbtPst Avatar asked Aug 24 '15 14:08

AbtPst


People also ask

How do I save a model object in R?

There are two ways to save and load the model: using save(), load(): When we use save(), we will have to load it using the same name. using saveRDS(), loadRDS(): saveRDS() does not save the model name and we have the flexibilty to load the model in any other name.

How can we save our machine learning model?

In machine learning, while working with scikit learn library, we need to save the trained models in a file and restore them in order to reuse them to compare the model with other models, and to test the model on new data. The saving of data is called Serialization, while restoring the data is called Deserialization.


1 Answers

If you only want to save a single object, you can also use:

saveRDS(model, file = "model.rds")

Afterwards you can use

loadedModel <- readRDS(model.rds)

ReadRDS() does not load the object as it was named when you saved it, but can be loaded in a new name.

For more information on the difference between save() and saveRDS() see this link

like image 88
phiver Avatar answered Sep 29 '22 11:09

phiver