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.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 14 views 0 copies

Requires third-party packages — install first
pip install joblib

Python code

34 lines
Python 3.9+
import 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

stdout
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

  1. Use the standard library pickle module with pickle.dump and pickle.load for objects that do not rely on heavy NumPy arrays.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from ML engineering pipelines

Related tutorials and quizzes for this topic.