Saving a machine learning Model
In machine learning, while working with scikit learn library, we need to save the trained models in a file and restore them in order to reuse it to compare the model with other models, to test the model on a new data. The saving of data is called Serialization, while restoring the data is called Deserialization.
Also, we deal with different types and sizes of data. Some datasets are easily trained i.e- they take less time to train but the datasets whose size is large (more than 1GB) can take very large time to train on a local machine even with GPU. When we need the same trained data in some different project or later sometime, to avoid the wastage of the training time, store trained model so that it can be used anytime in the future.
There are two ways we can save a model in scikit learn:
- Pickle string: The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.
Pickle model provides the following functions –
pickle.dump to serialize an object hierarchy, you simply use dump().
pickle.load to deserialize a data stream, you call the loads() function.
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.
- Example: Let’s apply K Nearest Neighbor on iris dataset and then save the model.
- Save model to string using pickle –
- Pickled model as a file using joblib: Joblib is the replacement of pickle as it is more efficient on objects that carry large numpy arrays. These functions also accept file-like object instead of filenames.
joblib.dump to serialize an object hierarchy
joblib.load to deserialize a data stream
- Save to pickled file using joblib –