Saving & Loading Models (joblib, pickle)
Part of the Machine Learning Roadmap
In short
A model that only lives inside your notebook dies when the kernel restarts. Saving it to a file is the first step to using it in an app, an API or a teammate's laptop.
After training, you save the model, ideally the whole preprocessing pipeline, to a file so it can be loaded later to make predictions. joblib and pickle work for scikit-learn, and PyTorch saves a model's state_dict.

Think of it like this
Making mango pickle
In summer, your nani cuts raw mangoes, adds spices and seals them in a jar. Months later anyone can open it and eat, no cutting or spicing needed. Saving a model is the same: all the training work, sealed in a file, ready to open later.
Watch it happen
From notebook to a separate app
1/4Train the whole pipeline, scaler and model together.
The big ideas
What you need to know
joblib for scikit-learn
joblib handles big NumPy arrays inside models more efficiently than plain pickle. Both use pickle's format underneath.
Save the whole pipeline
Save preprocessing and model together, so new data gets the exact same scaling and encoding.
Pin library versions
A model saved with one scikit-learn version may not load in another. Record versions in requirements.txt.
Only load trusted files
Loading a pickle can run hidden code. Never load model files from unknown sources.
See it in code
Walk through the code
1import joblib2from sklearn.datasets import load_iris3from sklearn.ensemble import RandomForestClassifier4from sklearn.pipeline import make_pipeline5from sklearn.preprocessing import StandardScaler6 7X, y = load_iris(return_X_y=True)8pipe = make_pipeline(StandardScaler(), RandomForestClassifier(random_state=0)).fit(X, y)9 10joblib.dump(pipe, "iris_model.joblib") # save11 12loaded = joblib.load("iris_model.joblib") # later, in another process13print(loaded.predict(X[:3]))1/3Fit a pipeline so scaling travels with the model.
One line to save, one to load. Deep learning frameworks have their own formats, like model.save() in Keras.
Save yourself the pain
Common mistakes
Oops
Saving only the model and rebuilding the scaler by hand in the app.
Do this instead
Save the full Pipeline. Hand-rebuilt preprocessing almost always drifts from what training used.
Oops
Downloading a .pkl model from a random forum and loading it.
Do this instead
Treat pickle files like programs. Load only files you or your team created, or use a safer format such as skops.
Your mission
Save, restart, load
Quick check
Why is it risky to load a pickle file from an unknown source?
Go deeper
- 1Save a fitted scikit-learn Pipeline with joblib.dump and load it in a fresh script.
- 2Record library versions next to the saved file, since loading across versions can break.
- 3Never load pickle files from untrusted sources, because they can run code.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.