How to save any trained machine learning model to use it for prediction later?

Hi, I am using number of machine learning models which include inbuilt models in MATLAB like fitrsvm, fitrgp, fitrensemble etc. and some models using functions in external toolbox like 'dacefit.m' for kriging model etc.
Is there a common way to save my models which I have trained on a dataset, so that I could use the same trained models on different test data later?
If not, kindly help me with saving a trained fitrensemble (Regression Tree Ensemble) model so that I could just use it for predictions in future.
Thanks in advance!

 Accepted Answer

The standard calling syntax, e.g.
Mdl = fitrensemble(Tbl,ResponseVarName);
stores everything you need in the model object named Mdl.
You can see in the first example in the documentation for fitrensemble how to then make predictions from the model.

7 Comments

Thanks, I understand this. But my question is what if I train my model on a dataset, and I want to predict using the same trained model later. I would close MATLAB or run other codes after training, but would need to use the previously trained model for predictions. So is there any way to create a copy or save in that context?
You can save the model (and any supporting data you need) into a file using the save command.
Then you can load it back into the workspace using the load command.
Could you please help me with a sample code. I am not able to do this. I am using the following code to create a model Mdl.
Mdl = fitrensemble(trainset(:, 2:12), trainset(:, 13));
save('checks.mat','Mdl');
When I clear my workspace, and load('checks.mat','Mdl') from command window, the following message pops up.
Warning: Variable 'Mdl' not found.
Strange. The following works for me.
load carsmall
Tbl = table(Cylinders,Displacement,Horsepower,Weight,MPG);
Mdl = fitrensemble(Tbl,'MPG');
save('checks.mat','Mdl')
clear
load('checks.mat','Mdl')
Loading still works if I quit MATLAB completely.
What version of MATLAB are you using? (I am on the latest -- R2019b.) Do you get any kind of warning when you save?
You might want to contact support.
I see the issue now! When I ran your sample code, it worked but was failing for my code. Actually I am using multiple models and was saving each model separately. Hence on loading, I was only able to load the last saved model.
On saving all models using single save command as
save('checks.mat','Mdl1','Mdl2',....);
it works! Thanks though.
Glad to hear it worked. Rather than saving models as Mdl1, Mdl2, etc, you could consider saving them all in a single cell array:
Mdl{1} = fitrensemble(...);
Mdl{2} = fitrensemble(...);
...
Mdl{n} = fitrensemble(...);
Then you can just save the single cell array Mdl, which has all your models.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!