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 ?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With