Finding an accurate machine learning model is not the end of the project. In this chapter you will discover how to save and load your machine learning model in Python using scikit-learn. This allows you to save your model to file and load it later in order to make predictions. After completing this lesson you will know:
- The importance of serializing models for reuse.
- How to use pickle to serialize and deserialize machine learning models.
- How to use Joblib to serialize and deserialize machine learning models.
1.1 Finalize Your Model with pickle
Pickle is the standard way of serializing objects in Python. You can use the pickle operation to serialize your machine learning algorithms and save the serialized format to a file. Later you can load this file to deserialize your model and use it to make new predictions. The example below demonstrates how you can train a logistic regression model on the Pima Indians onset of diabetes dataset, save the model to file and load it to make predictions on the unseen test set.
# Example of using pickle to serialize and deserialize a model
# Save Model Using Pickle
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from pickle import dump
from pickle import load
filename = 'pima-indians-diabetes.data.csv'
names = ['preg','plas','pres','skin','test','mass','pedi','age','class']
dataframe = read_csv(filename,names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
X_train,X_test, Y_train,Y_test = train_test_split(X, Y, test_size=0.33, random_state=7)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train,Y_train)
# save the model to disk
filename = 'finalized_model.sav'
dump(model, open(filename,'wb'))
# some time later...
# load the model from disk
loaded_model = load(open(filename,'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)
Running the example saves the model to finalized model.sav in your local working directory. Load the saved model and evaluating it provides an estimate of accuracy of the model on unseen data.

1.2 Finalize Your Model with Joblib
The Joblib library is part of the SciPy ecosystem and provides utilities for pipelining Python jobs. It provides utilities for saving and loading Python objects that make use of NumPy data structures, efficiently. This can be useful for some machine learning algorithms that require a lot of parameters or store the entire dataset (e.g. k-Nearest Neighbors). The example below demonstrates how you can train a logistic regression model on the Pima Indians onset of diabetes dataset, save the model to file using Joblib and load it to make predictions on the unseen test set.
# Save Model Using joblib
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from joblib import dump
from joblib import load
filename = 'pima-indians-diabetes.data.csv'
names = ['preg','plas','pres','skin','test','mass','pedi','age','class']
dataframe = read_csv(filename,names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
X_train,X_test, Y_train,Y_test = train_test_split(X, Y, test_size=0.33, random_state=7)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train,Y_train)
# save the model to disk
filename = 'finalized_model.sav'
dump(model, open(filename,'wb'))
# some time later...
# load the model from disk
loaded_model = load(open(filename,'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)
Running the example saves the model to file as finalized model.sav and also creates one file for each NumPy array in the model (four additional files). After the model is loaded an estimate of the accuracy of the model on unseen data is reported.

1.3 Tips for Finalizing Your Model
This section lists some important considerations when finalizing your machine learning models.
- Python Version. Take note of the Python version. You almost certainly require the same major (and maybe minor) version of Python used to serialize the model when you later load it and deserialize it.
- Library Versions. The version of all major libraries used in your machine learning project almost certainly need to be the same when deserializing a saved model. This is not limited to the version of NumPy and the version of scikit-learn.
- Manual Serialization. You might like to manually output the parameters of your learned model so that you can use them directly in scikit-learn or another platform in the future. Often the techniques used internally by machine learning algorithms to make predictions are a lot simpler than those used to learn the parameters can may be easy to implement in custom code that you have control over.
Take note of the version so that you can re-create the environment if for some reason you cannot reload your model on another machine or another platform at a later time.
1.4 Summary
In this chapter you discovered how to persist your machine learning algorithms in Python with scikit-learn. You learned two techniques that you can use:
- The pickle API for serializing standard Python objects.
- The Joblib API for efficiently serializing Python objects with NumPy arrays.
152

被折叠的 条评论
为什么被折叠?



