How to Save and Load a Mock Model with Pickle and joblib in Python
Serialize a custom machine learning model to a .joblib file with joblib.dump, reload it, and run a prediction with joblib.load.
pip install joblib
Python code
34 linesimport joblib
from pathlib import Path
class MockModel:
def __init__(self, weights):
self.weights = weights
def predict(self, features):
return sum(w * f for w, f in zip(self.weights, features))
def save_model_pickle(model, filepath):
with open(filepath, "wb") as f:
joblib.dump(model, f)
print(f"Model saved to {filepath}")
def load_model_pickle(filepath):
with open(filepath, "rb") as f:
return joblib.load(f)
if __name__ == "__main__":
model = MockModel([0.5, -1.2, 0.8])
path = "mock_model.joblib"
save_model_pickle(model, path)
loaded = load_model_pickle(path)
sample = [1.0, 2.0, 3.0]
prediction = loaded.predict(sample)
print(f"Prediction: {prediction}")
Path(path).unlink()
Output
Model saved to mock_model.joblib
Prediction: 0.5
How it works
joblib.dump writes the model object to the specified binary file, preserving its class and attributes. joblib.load reads the file back and reconstructs the object, so you can call its methods like predict. Using a with open block ensures the file is properly closed. This approach works for any Python object that can be pickled, including scikit-learn estimators.
Common mistakes
- Mixing up pickle and joblib — they have different file formats and can be incompatible.
- Forgetting to open the file in binary mode ('wb' or 'rb') when using joblib.dump/load.
- Not closing the file if you don't use a context manager, leading to resource leaks.
Variations
- Use the standard library pickle module with pickle.dump and pickle.load for objects that do not rely on heavy NumPy arrays.
- Use joblib.dump with compression, e.g., joblib.dump(model, 'model.joblib.z', compress=3), to save disk space.
Real-world use cases
- Saving a trained scikit-learn pipeline (e.g., RandomForestClassifier) after training so you can load it in a web service for inference.
- Persisting a preprocessed vectorizer or feature extractor to disk to reuse it consistently in training and prediction scripts.
- Caching a heavy ML model artifact between runs of a batch inference job to avoid retraining costs.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.