1 Goal


The goal of this tutorial is to save a model in a file to be read afterwards. This process will allow us to save all the training time if the model is trained over a really big table.


2 Data import


# First we load the libraries
library(ggplot2)
library(caret)
## Loading required package: lattice
# In this example we will use the open repository of plants classification Iris. 
data("iris")
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

3 Creating the model


# We are trying to predict the petal length using the petal width
my_linear_model <- lm(Petal.Length ~ Petal.Width, data = iris)

# Plotting the model
ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) + geom_point(aes(color = Species)) + stat_smooth(method = "lm")


4 Saving and loading the model


# We can save the model in a file using saveRDS
saveRDS(my_linear_model, "my_linear_model.RDS")

# Now we can read the model from file saving all the time used in training the model
model_from_file <- readRDS("my_linear_model.RDS")

# Now we can check if the two models are the same
print(my_linear_model$coefficients)
## (Intercept) Petal.Width 
##    1.083558    2.229940
print(model_from_file$coefficients)
## (Intercept) Petal.Width 
##    1.083558    2.229940

5 Conclusion


In this tutorial we have learnt how to write any algorithm into a file. This will save us a lot of time if the model we are training is going to be always the same.