Once you create a trained model, you need to save it for production use. Python makes this very easy, you just pickle()
it.
pickle
library:import pickle
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_lr_classifier_09.27.15.dat" pickle.dump(logClassifier, open(hearts_classifier_file, "wb"))
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_rf_classifier_09.27.15.dat" pickle.dump(rfClassifier, open(hearts_classifier_file, "wb"))
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_svm_classifier_09.27.15.dat" pickle.dump(svmClassifier, open(hearts_classifier_file, "wb"))
model_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_lr_classifier_09.27.15.dat" logClassifier2 = pickle.load(open(model_file, "rb")) print(logClassifier2)
To begin, we import the pickle
library. Pickle is a part of the standard Python libraries.
import pickle
Next, we create a variable to hold the full path to the pickle file of the logistic regression model, and specify the name of the file as the end of the string. Note that the file extension is .dat
. We use the pickle.dump()
method to create the file. The arguments we pass to it are as follows:
logClassifier
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_lr_classifier_09.27.15.dat" pickle.dump(logClassifier, open(hearts_classifier_file, "wb"))
The second line of code allows us to open the previously specified file for binary writing (the "wb"
argument) in one line, and then dump the contents of the logClassifier
into it.
Next, we do the same for the random forest model:
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_rf_classifier_09.27.15.dat" pickle.dump(rfClassifier, open(hearts_classifier_file, "wb"))
After that, we pickle the SVM model:
hearts_classifier_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_svm_classifier_09.27.15.dat" pickle.dump(svmClassifier, open(hearts_classifier_file, "wb"))
Did it work? Reconstitute the logistic regression model as a test, and print out the contents of the variable:
model_file = "/Users/robertdempsey/Dropbox/private/Python Business Intelligence Cookbook/Models/hearts_lr_classifier_09.27.15.dat" logClassifier2 = pickle.load(open(model_file, "rb")) print(logClassifier2)
The model looks the same as the model we previously trained. Success!!