So after using the model, how to save our trained model. So in this recipe we will save our trained model and we will also load the saved model.
So this is the recipe on how we can save trained model in Python.
from sklearn import model_selection, datasets from sklearn.tree import DecisionTreeClassifier from sklearn.externals import joblib import pickle
We have imported model_selection, datasets, joblib, DecisionTreeClassifier and pickel which will be needed for the dataset.
We have loaded inbuilt wine dataset and stored data in x and target in y. We have used test_train_split to split the dataset such that 30% of data is for testing the model.
dataset = datasets.load_wine()
X = dataset.data; y = dataset.target
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3)
We are using DecisionTreeClassifier as a model. We have trained the model by training data. We can save the model by using joblib.dump in which we have passed the parameter as model and the filename.
model = DecisionTreeClassifier()
filename = "Completed_model.joblib"
So here we are loading the saved model by using joblib.load and after loading the model we have used score to get the score of the pretrained saved model.
loaded_model = joblib.load(filename)
result = loaded_model.score(X_test, y_test)
So the output comes as: