Course contentsShow
← Machine Learning and Deep Learning
Lesson 186 of 3,5382. Machine Learning Mindset and Core ConceptsFree lesson

Saving and Loading Models with Joblib

Persisting trained models to disk using joblib for reuse without retraining on the same data.

Saving and Loading Models with Joblib

What You'll Learn

You'll learn how to save your trained machine learning models to disk and reload them later, so you don't have to retrain them every time you want to make predictions.

Why Save Models?

Training a model takes time and computational resources. Imagine spending hours training a model on a large dataset—you wouldn't want to repeat that process every time you need to make a prediction! Just like saving a document so you can open it later, you can save your trained ML models to disk.

The Joblib Solution

Joblib is a library designed specifically for efficiently saving and loading Python objects, particularly large NumPy arrays (which is exactly what ML models contain). Scikit-learn recommends joblib over Python's standard pickle because it handles large data more efficiently.

How It Works

After training a model with scikit-learn, saving it is simple:

from sklearn.linear_model import LogisticRegression
import joblib

# Train your model (assuming you have X_train and y_train)
model = LogisticRegression()
model.fit(X_train, y_train)

# Save the trained model to disk
joblib.dump(model, 'my_model.pkl')

Later, you can load it back without retraining:

# Load the saved model
loaded_model = joblib.load('my_model.pkl')

# Use it immediately for predictions
predictions = loaded_model.predict(X_test)

Think of It Like This

Saving a model is like freezing a meal after cooking. You did all the hard work once (training/cooking), then preserved it (saved to disk). Later, you can reheat and serve (load and predict) without starting from scratch.

Key Takeaway: Joblib lets you persist trained models to disk as files, enabling you to reuse them for predictions without repeating the entire training process—essential for deploying models in real-world applications.