Learning path: Ship Your First Model: From Notebook to a FastAPI Service · Step 1 of 9
Saving and Loading Models with joblib: One Pipeline, One File
Train the rain pipeline once, seal it in a 4,298-byte file with joblib.dump, load it in a fresh program with the same 0.831 accuracy, avoid the 2D-array error and pin the versions in requirements.txt.
What you will learn
- Save a whole fitted scikit-learn pipeline to one file with joblib.dump
- Load it back with joblib.load and get the same test score without retraining
- Predict one new example as a one-row DataFrame instead of a flat list
- Pin library versions in requirements.txt so the file loads later
Before you start
- Pipelines and ColumnTransformer
- Train-Test Split and Data Leakage
You've trained a model in a notebook. It scores well. Now close the notebook, and the model is gone. Nobody else can use it, and tomorrow you'd have to train it again.
So the first step of deploying any model is simple: save it to a file. Train once, save once, and load it anywhere you like.
Seal the meal, keep the recipe
Imagine you cook a nice meal once and vacuum seal it. You tape the recipe card to the pack, with the exact steps. Anyone can carry the pack to another kitchen, reheat it, and it tastes exactly the same. It wasn't cooked again, only reheated.
Here's how that maps to code:
| Kitchen | Machine learning |
|---|---|
| The cooked meal | The trained pipeline |
| Sealing it | joblib.dump |
| Reheating it | joblib.load |
| The recipe card | requirements.txt |
Save the pipeline, not just the model
What goes inside the file? The old way was to save the model in one file and the scaler in another. Two files that must always stay in step. People often refit the scaler on new data, the numbers drift, and the predictions quietly go wrong.
The better way: one pipeline, one file. It holds the gap filler, the scaler, the encoder and the model, all already fitted on the training rows.
Five inputs, split first
We'll use the Rain in Australia data (will it rain tomorrow?) with five inputs: rainfall, humidity at 3 pm, cloud at 9 am, cloud at 3 pm and whether it rained today.
import os
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("weatherAUS.csv")
df = df.dropna(subset=["RainTomorrow"])
features = ["Rainfall", "Humidity3pm", "Cloud9am",
"Cloud3pm", "RainToday"]
df[features].sample(3, random_state=42)
Rainfall Humidity3pm Cloud9am Cloud3pm RainToday
56320 8.8 98.0 8.0 8.0 Yes
124136 0.0 73.0 NaN NaN No
117063 0.0 25.0 0.0 0.0 No
Notice the blanks in the middle row. The pipeline will have to fill those. As always, we split first, 80/20, with stratify=y to keep the same share of rainy days in both parts:
X, y = df[features], df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(113754, 5) (28439, 5)
Build and fit one pipeline
The number lane fills gaps with the median and then scales. The text lane fills gaps with the most frequent value and then one-hot encodes. ColumnTransformer sends each column to its own lane, and make_pipeline joins the prep and the logistic regression into one object.
num = make_pipeline(
SimpleImputer(strategy="median"),
StandardScaler())
cat = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder())
prep = ColumnTransformer([
("num", num, features[:4]),
("cat", cat, ["RainToday"])])
clf = LogisticRegression(max_iter=1000)
model = make_pipeline(prep, clf)
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
print("test accuracy:", round(acc, 3))
test accuracy: 0.831
One fit, on the training days only. This is the pipeline we want to keep.
One call saves, one call loads
joblib.dump takes the object and a file name:
joblib.dump(model, "model.joblib")
print(os.path.getsize("model.joblib"), "bytes")
4298 bytes
The whole pipeline, all four fitted steps, fits in 4,298 bytes. About 4 KB.
Now imagine it's tomorrow, in a fresh program. joblib.load with the same file name brings the pipeline back:
loaded = joblib.load("model.joblib")
print(type(loaded).__name__)
acc = loaded.score(X_test, y_test)
print("test accuracy:", round(acc, 3))
Pipeline
test accuracy: 0.831
It's a Pipeline, and it scores 0.831 on the test days, exactly as before. Nothing was trained again.
One day is still a table
Here's the mistake everybody makes once. You have one day, so you put its five values in a plain list:
try:
loaded.predict([0.0, 85, 7, 8, "No"])
except ValueError as err:
print("ValueError:", str(err).splitlines()[0])
ValueError: Expected 2D array, got 1D array instead:
The model learned from a table, rows and columns, so a flat list doesn't work. Give it a pandas DataFrame with one row and the five column names:
today = pd.DataFrame([{
"Rainfall": 0.0, "Humidity3pm": 85,
"Cloud9am": 7, "Cloud3pm": 8,
"RainToday": "No"}])
print(today.shape)
print(loaded.predict(today))
print(loaded.predict_proba(today).round(2))
(1, 5)
['Yes']
[[0.37 0.63]]
Shape (1, 5): one row, five columns. The answer is Yes, and predict_proba gives 37% for No and 63% for Yes. Even one day must be a table. The column names matter too, because the ColumnTransformer picks its columns by name.
Pin the versions
Now the recipe card. Read the version of each library from the running notebook and write them into requirements.txt:
import sklearn, numpy
reqs = [f"scikit-learn=={sklearn.__version__}",
f"pandas=={pd.__version__}",
f"numpy=={numpy.__version__}",
f"joblib=={joblib.__version__}"]
with open("requirements.txt", "w") as f:
print(*reqs, sep="\n", file=f)
print(*reqs, sep="\n")
scikit-learn==1.9.1
pandas==3.0.6
numpy==2.5.3
joblib==1.6.0
The double equals sign pins that exact version. Why does it matter? A saved model is only safe with the same library versions. Load it with other versions and you may get a warning, or it may not load at all. Anyone who wants to use your file runs pip install -r requirements.txt first.
Common mistakes
- Saving only the model. Without the fitted imputer, scaler and encoder, the raw input can't be turned into the numbers the model expects. Save the whole pipeline.
- Refitting a step on new data. Load and predict. Never call
fitagain on the loaded pipeline unless you mean to retrain. - Passing a flat list for one example. Wrap it in a one-row DataFrame with the same column names you trained on.
- Forgetting the versions. Ship
requirements.txtwith the.joblibfile, always together.
Quick recap
| Step | Code | Result here |
|---|---|---|
| Train once | model.fit(X_train, y_train) | test accuracy 0.831 |
| Save | joblib.dump(model, "model.joblib") | one file, 4,298 bytes |
| Load | joblib.load("model.joblib") | a Pipeline, still 0.831 |
| Predict one day | one-row DataFrame | Yes, 63% chance |
| Pin versions | requirements.txt | scikit-learn 1.9.1, pandas 3.0.6, numpy 2.5.3, joblib 1.6.0 |
The classification master template ends with the same joblib.dump call, so this is how any of your projects can leave the notebook.
Try it yourself
Load model.joblib and predict a dry day: Rainfall 0, Humidity3pm 30, Cloud9am 1, Cloud3pm 2, RainToday "No". What chance of rain do you get?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.