Analytics Vidhya
Published in

Analytics Vidhya

Photo by Olia Gozha on Unsplash

Want to Save and Reuse a model later?

Steps to do it:

  1. Save the model as a file
  2. Load the model from the saved file
  3. Use the loaded model to make predictions

Using Pickle to save it as a File:

import pickle as pkl
filenm = 'LR_AdmissionPrediction.pickle'
#Step 1: Create or open a file with write-binary mode and save the model to it
pickle = pkl.dump(lr, open(filenm, 'wb'))
#Step 2: Open the saved file with read-binary mode
lr_pickle = pkl.load(open(filenm, 'rb'))
#Step 3: Use the loaded model to make predictions
lr_pickle.predict([[300,85,5,5,5,8,1]])
array([0.61745881])
#Step 1: Save the model as a pickle string. 
saved_model = pkl.dumps(lr)

#Step 2: Load the saved model
lr_from_pickle = pkl.loads(saved_model)

#Step 3: Use the loaded model to make predictions
lr_from_pickle.predict([[300,85,5,5,5,8,1]])
array([0.61745881])

Using joblib to save it as a File:

from sklearn.externals import joblib 

#Step 1: Save the model as a pickle in a file
joblib.dump(lr, 'filename.pkl')

#Step 2: Load the model from the file
lr_from_joblib = joblib.load('filename.pkl')

#Step 3: Use the loaded model to make predictions
lr_from_joblib.predict([[300,85,5,5,5,8,1]])
array([0.61745881])

Conclusion:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store