AbtPst
AbtPst

Reputation: 8018

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 ?

Upvotes: 8

Views: 5276

Answers (2)

phiver
phiver

Reputation: 23608

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

Upvotes: 8

tcash21
tcash21

Reputation: 4995

Yes you can just use:

save(model, file="model.Rda")

and later:

load("model.Rda")

Upvotes: 3

Related Questions