After training a scikit-learn model, it is desirable to have a way to persist the model for future use without having to retrain. The following section gives you an example of how to persist a model with pickle. We’ll also review a few security and maintainability issues when working with pickle serialization.
It is possible to save a model in scikit-learn by using Python’s built-in persistence model, namely pickle:
>>> from sklearn import svm >>> from sklearn import datasets >>> clf = svm.SVC(gamma='scale') >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target >>> clf.fit(X, y) SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='scale', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> import pickle >>> s = pickle.dumps(clf) >>> clf2 = pickle.loads(s) >>> clf2.predict(X[0:1]) array() >>> y 0
In the specific case of scikit-learn, it may be better to use joblib’s replacement of pickle (
joblib.load), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:
>>> from sklearn.externals import joblib >>> joblib.dump(clf, 'filename.joblib')
Later you can load back the pickled model (possibly in another Python process) with:
>>> clf = joblib.load('filename.joblib')
joblib.load functions also accept file-like object instead of filenames. More information on data persistence with Joblib is available here.
pickle (and joblib by extension), has some issues regarding maintainability and security. Because of this,
In order to rebuild a similar model with future versions of scikit-learn, additional metadata should be saved along the pickled model:
This should make it possible to check that the cross-validation score is in the same range as before.
Since a model internal representation may be different on two different architectures, dumping a model on one architecture and loading it on another architecture is not supported.
If you want to know more about these issues and explore other possible serialization methods, please refer to this talk by Alex Gaynor.
© 2007–2018 The scikit-learn developers
Licensed under the 3-clause BSD License.