Skip to Content
Python Machine Learning Cookbook
book

Python Machine Learning Cookbook

by Prateek Joshi, Vahid Mirjalili
June 2016
Beginner to intermediate
304 pages
6h 24m
English
Packt Publishing
Content preview from Python Machine Learning Cookbook

Achieving model persistence

When we train a model, it would be nice if we could save it as a file so that it can be used later by simply loading it again.

How to do it…

Let's see how to achieve model persistence programmatically:

  1. Add the following lines to regressor.py:
    import cPickle as pickle
    
    output_model_file = 'saved_model.pkl'
    with open(output_model_file, 'w') as f:
        pickle.dump(linear_regressor, f)
  2. The regressor object will be saved in the saved_model.pkl file. Let's look at how to load it and use it, as follows:
    with open(output_model_file, 'r') as f:
        model_linregr = pickle.load(f)
    
    y_test_pred_new = model_linregr.predict(X_test)
    print "\nNew mean absolute error =", round(sm.mean_absolute_error(y_test, y_test_pred_new), 2)
  3. Here, we just loaded the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Machine Learning Cookbook - Second Edition

Python Machine Learning Cookbook - Second Edition

Giuseppe Ciaburro, Prateek Joshi
Python: Real World Machine Learning

Python: Real World Machine Learning

Prateek Joshi, John Hearty, Bastiaan Sjardin, Luca Massaron, Alberto Boschetti

Publisher Resources

ISBN: 9781786464477Supplemental Content