pickle to save model code example

Example 1: model pickle file create

import pickle

# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))
 
# some time later...
 
# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)

Example 2: save machine learning model python

model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))
 
# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)

Example 3: sklearn save model

# save as object
import pickle

s = pickle.dumps(clf)
clf2 = pickle.loads(s)

# save to file
from joblib import dump

dump(clf, 'filename.joblib') 

# load from file
from joblib import load

clf = load('filename.joblib')