-
-
Notifications
You must be signed in to change notification settings - Fork 25.9k
[MRG+2] Model persistence doc #3317
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8489c33
added a new section on model persistence
df27e26
model persistence doc, added improvements from ogrisel comments
be315ed
Move model persistence doc inside model selection section
pignacio 4c51809
Remove trailing whitespace
pignacio 78c0f61
Simplified security and maintenance section
pignacio 4b79f22
Metadata information for unpickling models in future versions
pignacio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
.. _model_persistence: | ||
|
||
================= | ||
Model persistence | ||
================= | ||
|
||
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. | ||
|
||
|
||
Persistence example | ||
------------------- | ||
|
||
It is possible to save a model in the scikit by using Python's built-in | ||
persistence model, namely `pickle <http://docs.python.org/library/pickle.html>`_:: | ||
|
||
>>> from sklearn import svm | ||
>>> from sklearn import datasets | ||
>>> clf = svm.SVC() | ||
>>> iris = datasets.load_iris() | ||
>>> X, y = iris.data, iris.target | ||
>>> clf.fit(X, y) # doctest: +NORMALIZE_WHITESPACE | ||
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, | ||
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]) | ||
array([0]) | ||
>>> y[0] | ||
0 | ||
|
||
In the specific case of the scikit, it may be more interesting to use | ||
joblib's replacement of pickle (``joblib.dump`` & ``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.pkl') # doctest: +SKIP | ||
|
||
Later you can load back the pickled model (possibly in another Python process) | ||
with:: | ||
|
||
>>> clf = joblib.load('filename.pkl') # doctest:+SKIP | ||
|
||
.. note:: | ||
|
||
joblib.dump returns a list of filenames. Each individual numpy array | ||
contained in the `clf` object is serialized as a separate file on the | ||
filesystem. All files are required in the same folder when reloading the | ||
model with joblib.load. | ||
|
||
|
||
Security & maintainability limitations | ||
-------------------------------------- | ||
|
||
pickle (and joblib by extension), has some issues regarding maintainability | ||
and security. Because of this, | ||
|
||
* Never unpickle untrusted data | ||
* Models saved in one version of scikit-learn might not load in another | ||
version. | ||
|
||
In order to rebuild a similar model with future versions of scikit-learn, | ||
additional metadata should be saved along the pickled model: | ||
|
||
* The training data, e.g. a reference to a immutable snapshot | ||
* The python source code used to generate the model | ||
* The versions of scikit-learn and its dependencies | ||
* The cross validation score obtained on the training data | ||
|
||
This should make it possible to check that the cross-validation score is in the | ||
same range as before. | ||
|
||
If you want to know more about these issues and explore other possible | ||
serialization methods, please refer to this | ||
`talk by Alex Gaynor <http://pyvideo.org/video/2566/pickles-are-for-delis-not-software>`_. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would add:
It is strongly advised to save metadata information along with the model pickle files about the training data (such as the reference to an immutable snapshot), the Python source of the code used to train the model, the versions of scikit-learn and its dependencies and finally the cross-validation score obtained on the training data. This should make it possible to rebuild a similar model with future versions of scikit-learn and check that the cross-validation score is still in the same range.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
+1 for more detail on bookkeeping with pickles.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@pignacio My phrasing is bad. Maybe rephrase that long conjunction as a 4 items bullet list to improve readability.