← Lesson
BitWithBite
AI & Machine Learning · Quick Reference

1.4 Saving and Loading Models Cheat Sheet

AI & Machine Learning
In one line: Python has a built-in serialization module, pickle, that can save almost any Python object to disk as bytes. scikit-learn also ships a tool built specifically for this: joblib. ...

Key Ideas

1pickle vs joblib. Python has a built-in serialization module, pickle, that can save almost any Python object to disk as bytes. scikit-learn also ships a tool built specifically for this...
2Always Save the Whole Pipeline, Not Just the Model. This was emphasized in lesson 1.3, but it's worth repeating because it's the #1 mistake in production ML code:
3The Version Mismatch Problem. scikit-learn's internal model format can change slightly between versions. If you save a model with scikit-learn 1.3 and load it with 1.5, you might see a warning — or...
4What Actually Gets Saved. When you pickle/joblib-dump a fitted pipeline, you're saving:
5A Minimal Production Loading Pattern. Here's how this typically looks inside a FastAPI app — load once at startup, reuse for every request:

Code Examples

import pickle # Save with open('model.pkl', 'wb') as f: pickle.dump(trained_pipeline, f) # Load with open('model.pkl', 'rb') as f: loaded_pipeline = pickle.load(f)
import joblib # Save — one line, no context manager needed joblib.dump(trained_pipeline, 'model_pipeline.joblib') # Load — one line loaded_pipeline = joblib.load('model_pipeline.joblib') # Optional: compress to save disk space joblib.dump(traine...
# Saving ONLY the model, not the preprocessing joblib.dump(model, 'model_only.joblib') # Now, in production, someone has to remember: # - which columns were scaled # - what encoder was used for categoricals # - what the imputation strategy was # - t...