How to use pickle to save sklearn model

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


Save:

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

Load:

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

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.


One can also use joblib

from joblib import dump, load
dump(model, model_save_path)