In this article, we’ll learn how to save and load ML models using Joblib. Training a machine learning model is time consuming, especially for large datasets it is better to save the trained model and load it later whenever needed. It is faster and efficient approach.
What is Joblib?
It is a Python library used for saving and loading machine learning models efficiently. It provides fast and optimized storage of models.
Why to use it?
- It is faster than pickle when saving the ML models and is more optimized for handling large datasets.
- It compresses the data and reduces file size and saves disk space.
How to use it to save and load models?
- Installing joblib:-
Firstly, if it is not installed on system then it is installed using pip install command.
pip install joblib
- Saving model:-
After the model is trained it is saved using joblib.dump().
import joblib from sklearn.ensemble import RandomForestClassifier X,y = [[0,0],[1,1],[1,0],[0,1]],[0,1,1,0] model = RandomForestClassifier() model.fit() joblib.dump(model,'random_forest_model.pkl') print("Model Saved Successfully")
- Loading a saved model:-
Whenever we need to use saved model we can use it using joblib.load(). Then, model can be used directly without training it again.
loaded_model = joblib.load('random_forest_model.pkl')
Also read,