Pickle is an open-source Python module that is commonly used to serialize and deserialize objects. It actually helps to create a binary file of data that can be easily transferred remotely. One of the biggest use of the Pickle module in Machine Learning is to save the model. In this article, we will focus on how to save model in Pickle after creating and training the model.
How to Save Model in Pickle?
To save a model using Pickle, you first need to make sure that the Pickle module is installed correctly on your system. If not, then you can use the pip command to install the Pickle module on your system.
Here are some steps to save the model in the Pickle module.
- Install the Pickle module on your system
- Import the pickle module
- Then use the dump() method to save your model.
Let us assume that we have an ML-trained model named, ‘Model’ and we want to save the model in a Pickle file. We can use the following commands to save the model.
import pickle pickle.dump(Model, open('my_model.pkl', 'wb'))
- Model: The trained model
- ‘my_model.pkl’: It is the name of the pickle file that will be created
- ‘wb’: Write in binary mode
Example of Saving Model in Machine Learning
Now, we will take an example and see how we can train the model and then save it using the Pickle module. For the sake of understanding purposes, we will use the KNN algorithm.
Let us first call the KNN algorithm, initialize it and then we will train the model on the training dataset. We assume that we have a dataset and we already split it into testing and training parts.
# importing KNN algorithm from sklearn.neighbors import KNeighborsClassifier # K value set to be 3 classifer = KNeighborsClassifier(n_neighbors=3 ) # model training classifer.fit(X_train,y_train)
Once the model is trained, we can then use the model name (in this case classifer) to save the model into a Pickle file.
import pickle pickle.dump(classifer, open('model.pkl', 'wb'))
This will save the file in the same folder with the name model.pkl.
Also, check how to visualize the KNN model in Python.
Other Functions Available in Pickle Module
Apart from the dump() method which is used to load and open the saved Pickle file. The module also provides tons of other important methods as well. Here is a list of some of those methods:
- Highest protocol
Pickle is a Python module that is very popular among Machine Learning developers. The reason for this popularity is its ability to save and load the ML model in binary files. The dump() method in Pickle is used to save the model in a binary file in the specified directory.