How to use pickle to save sklearn model

Question:

I want to dump and load my Sklearn trained model using Pickle. How to do that?

Asked By: Chittal

||

Answers:

Save:

import pickle

with open("model.pkl", "wb") as f:
    pickle.dump(model, f)

Load:

with open("model.pkl", "rb") as f:
    model = pickle.load(f)

In the specific case of scikit-learn, it may be better to use joblib’s
replacement of pickle (dump & load), which is more efficient on
objects that carry large numpy arrays internally as is often the case
for fitted scikit-learn estimators:

Save:

import joblib

joblib.dump(model, "model.joblib")

Load:

model = joblib.load("model.joblib")
Answered By: Mykola Zotko

Using pickle is same across all machine learning models irrespective of type i.e. clustering, regression etc.

To save your model in dump is used where ‘wb’ means write binary.

pickle.dump(model, open(filename, 'wb')) #Saving the model

To load the saved model wherever need load is used where ‘rb’ means read binary.

model = pickle.load(open(filename, 'rb')) #To load saved model from local directory

Here model is kmeans and filename is any local file, so use accordingly.

Answered By: Vaibhav Magon

One can also use joblib

from joblib import dump, load
dump(model, model_save_path) 
Answered By: sushmit
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.