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 ...

Get Python Machine Learning Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.