Save And Finalize Your Machine Learning Model in R

Finding an accurate machine learning is not the end of the project.

In this post you will discover how to finalize your machine learning model in R including: making predictions on unseen data, re-building the model from scratch and saving your model for later use.

Let’s get started.

Finalize Your Machine Learning Model in R

Finalize Your Machine Learning Model in R.
Photo by Christian Schnettelker, some rights reserved.

Finalize Your Machine Learning Model

Once you have an accurate model on your test harness you are nearly, done. But not yet.

There are still a number of tasks to do to finalize your model. The whole idea of creating an accurate model for your dataset was to make predictions on unseen data.

There are three tasks you may be concerned with:

  1. Making new predictions on unseen data.
  2. Creating a standalone model using all training data.
  3. Saving your model to file for later loading and making predictions on new data.

Once you have finalized your model you are ready to make use of it. You could use the R model directly. You could also discover the key internal representation found by the learning algorithm (like the coefficients in a linear model) and use them in a new implementation of the prediction algorithm on another platform.

In the next section, you will look at how you can finalize your machine learning model in R.

Need more Help with R for Machine Learning?

Take my free 14-day email course and discover how to use R on your project (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

Start Your FREE Mini-Course Now!

Finalize Predictive Model in R

Caret is an excellent tool that you can use to find good or even best machine learning algorithms and parameters for machine learning algorithms.

But what do you do after you have discovered a model that is accurate enough to use?

Once you have found a good model in R, you have three main concerns:

  1. Making new predictions using your tuned caret model.
  2. Creating a standalone model using the entire training dataset.
  3. Saving/Loading a standalone model to file.

This section will step you through how to achieve each of these tasks in R.

1. Make Predictions On New Data

You can make new predictions using a model you have tuned using caret using the predict.train() function.

In the recipe below, the dataset is split into a validation dataset and a training dataset. The validation dataset could just as easily be a new dataset stored in a separate file and loaded as a data frame.

A good model of the data is found using LDA. We can see that caret provides access to the best model from a training run in the finalModel variable.

We can use that model to make predictions by calling predict using the fit from train which will automatically use the final model. We must specify the data one which to make predictions via the newdata argument.

Running the example, we can see that the estimated accuracy on the training dataset was 76.91%. Using the finalModel in the fit, we can see that the accuracy on the hold out validation dataset was 77.78%, very similar to our estimate.

2. Create A Standalone Model

In this example, we have tuned a random forest with 3 different values for mtry and ntree set to 2000. By printing the fit and the finalModel, we can see that the most accurate value for mtry was 2.

Now that we know a good algorithm (random forest) and the good configuration (mtry=2, ntree=2000) we can create the final model directly using all of the training data. We can lookup the “rf” random forest implementation used by caret in the Caret List of Models and note that it is using the randomForest package and in turn the randomForest() function.

The example creates a new model directly and uses it to make predictions on the new data, this case simulated as the verification dataset.

We can see that the estimated accuracy of the optimal configuration was 85.07%. We can see that the accuracy of the final standalone model trained on all of the training dataset and predicting for the validation dataset was 82.93%.

Some simpler models, like linear models can output their coefficients. This is useful, because from these, you can implement the simple prediction procedure in your language of choice and use the coefficients to get the same accuracy. This gets more difficult as the complexity of the representation increases.

3. Save and Load Your Model

You can save your best models to a file so that you can load them up later and make predictions.

In this example we split the Sonar dataset into a training dataset and a validation dataset. We take our validation dataset as new data to test our final model. We train the final model using the training dataset and our optimal parameters, then save it to a file called final_model.rds in the local working directory.

The model is serialized. It can be loaded at a later time by calling readRDS() and assigning the object that is loaded (in this case a random forest fit) to a variable name. The loaded random forest is then used to make predictions on new data, in this case the validation dataset.

We can see that the accuracy on the validation dataset was 82.93%.

Summary

In this post you discovered three recipes for working with final predictive models:

  1. How to make predictions using the best model from caret tuning.
  2. How to create a standalone model using the parameters found during caret tuning.
  3. How to save and later load a standalone model and use it to make predictions.

You can work through these recipes to understand them better. You can also use them as a template and copy-and-paste them into your current or next machine learning project.

Next Step

Did you try out these recipes?

  1. Start your R interactive environment.
  2. Type or copy-paste the recipes above and try them out.
  3. Use the built-in help in R to learn more about the functions used.

Do you have a question. Ask it in the comments and I will do my best to answer it.


Frustrated With Your Progress In R Machine Learning?

Master Machine Learning With R

Develop Your Own Models in Minutes

…with just a few lines of R code

Discover how in my new Ebook:
Machine Learning Mastery With R

Covers self-study tutorials and end-to-end projects like:
Loading data, visualization, build models, tuning, and much more…

Finally Bring Machine Learning To
Your Own Projects

Skip the Academics. Just Results.

Click to learn more.


30 Responses to Save And Finalize Your Machine Learning Model in R

  1. John ford November 1, 2016 at 3:07 pm #

    Hi. I’ve been working through the examples, and some models of my own, and i have a question on preprocessing my data.

    When training my models, I used the preProcess argument to center and scale the data.

    When I have a new data set to run through my model after training, does the model know to preprocess that data as well? Or do i have to manually scale and center the new data set before applying the model to it? What about after saving and reloading the final model?

    this is one of the less-clear points in the docs.

    • Jason Brownlee November 2, 2016 at 9:07 am #

      Hi John, great question.

      The safest way is to managing data scaling separately and save scaled versions of your data as well as the coefficients needed to scale new data in the future.

      According to the caret doco, any preprocessing applied during training will be applied to later calls to predict() on new data:
      http://topepo.github.io/caret/model-training-and-tuning.html#preproc

      I would expect this to be preserved if you saved the trained model, but I would suggest testing this out (do pre-save and post-save results match for a model with preprocessing).

  2. Hans June 7, 2017 at 9:41 pm #

    Are there concerns about applying this to non-classification-problems?
    What would be the differences?

    • Jason Brownlee June 8, 2017 at 7:42 am #

      No difference of note.

      • Hans June 9, 2017 at 6:47 am #

        Hm…

        Error: Metric Accuracy not applicable for regression models
        Error in [.data.frame(validation, , 1:60) : undefined columns selected

        • Hans June 9, 2017 at 7:24 am #

          1. & 2. fixed, Still getting errors:
          Error in confusionMatrix.default(final_predictions, validation$n5) :
          the data cannot have more levels than the reference

  3. Hans June 9, 2017 at 7:47 am #

    If I do a print(final_predictions), I get:

    3 6 9 11 18 19 21 26 29 39 47 50 61 63 74 92 94 95 97 99 101 104 111 114
    M R M R R R M R M R M R R R R R R R R M M R M M
    117 120 126 129 137 138 145 146 148 155 160 164 170 171 173 191 206
    M M M M M M M M M M M M M R M M M

    The last data point has a row index of 206. The original data from Sonar has an end index of 208.
    So where is the unseen data here? Are the row indexes in depended from each other?

  4. Hans June 9, 2017 at 7:57 am #

    How to predict one step of unseen data in the future with example 2?

  5. Ste June 20, 2017 at 10:05 pm #

    Dear Jason, thanks for the precious post.

    I’m going a bit too far maybe, but I’ve been wondering recently if it is possible to save a trained model in some kind of standard format so that it can be (1) sent over a network and (2) parsed even by a different language (I dunno, Java for example).

    Are you aware of anything similar, for R or (possibly) other machine learning / statistics suites?

    Apologies if the question is considered off-topic.

  6. Chandra July 25, 2017 at 11:55 pm #

    Hi Jason – Thanks for the example! This came in very handy and just in time for me.

  7. Christian Ruiz September 7, 2017 at 7:39 pm #

    Hi Jason
    Great website! Thank you for the very valuable information.

    I have a short question concerning the “standalone model”. Why is it necessary to use it after using the caret one? I though bought would be equivalent (i.e. caret using the randomForest one in this example of “rf”-method) and am now a bit confused.

    Cheers,
    Chris

    • Jason Brownlee September 9, 2017 at 11:41 am #

      Caret is a wrapper for the models that can help us find which model to use.

      Once we know which model to use, we can use it directly without the caret wrapper – if we want.

      • Christian Ruiz May 24, 2018 at 12:08 am #

        Thanks!

  8. SUMANTA September 19, 2017 at 3:39 pm #

    Hi Jason,

    Excellent work and quite helpful for us who is in learning mode. Just one question here. Suppose, I’ve 100 data-points and I divide into train & test (80 & 20). I fit the model and see accuracy as 75%. My question is how do I implement this model so that when 101st and 102nd data arrives, this model runs and provides me some classification?

  9. Monte September 23, 2017 at 4:15 am #

    Hi Jason.

    The “finalize machine learning models” article above is helpful, and I can’t wait to try it out. However, I notice that it’s making one prediction. Is here a way to get multiple predictions at once, based on criteria, and give them as a list? Like this:

    Item 1…result
    Item 2…result

    • Jason Brownlee September 23, 2017 at 5:44 am #

      Yes, the predict function will support this by default.

  10. Zalak November 3, 2017 at 6:14 pm #

    Dear Sir,
    I am doing dissertation in load balancing in distributed computing system in which I want to predict the future incoming jobs on the basis of past load information given in the real time dataset.So how can I apply this technique in my work?

  11. Martín Solís November 6, 2017 at 2:32 am #

    Hello Jason , I have a question, maybe you can help me.

    I am using caret, and I need to print the function of a ramdom forest best model, I am talking about all the trees, that are 100.
    I know with model$finalModel I can print the function of neuronal network or tree with rpart, but this command don’t print all the trees of random forest or the function of boosted trees
    Do you Know how I can do it

    Thanks

    • Jason Brownlee November 6, 2017 at 4:54 am #

      Sorry, I have not printed all of the trees from a random forest before. Perhaps there is a third party tool to help?

  12. Srini April 9, 2018 at 10:56 pm #

    Hey Jason! Thanks for the post. I have a question to you.

    I have a built a highly accurate random forest model for a student enrollment prediction project ,let’s say, for this year. Now I have saved the model and want to use this model for data belonging to ,let’s assume, last year. But the number of variables in my last year’s data has changed. How to approach this situation? Is there any way to scale this model to fit the new case?

    Thank you!

  13. Ken July 30, 2018 at 7:27 am #

    Hello guys! What ML tool (regression model) would be appropriate for predicting call center call volume

  14. Griffin November 28, 2018 at 12:57 pm #

    Hi Jason,

    many thanks for this superb post!

    Would like to know if the following process (essentially what you did in this post) is considered best practice or common practice in ML and DS:
    1. Perform cross-validation to tune hyperparameters
    2. using optimised hyperparameters to train the ENTIRE training dataset to arrive at an optimal accuracy?

    And also, in part 3 on saving and loading the model, I am encountering problems with the doMC package in R and I understand that doMC is not usable in windows. Could you suggest alternative workaround for this?

    Thank you so much

Leave a Reply