Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathShip Your First Model: From Notebook to a FastAPI Service
  1. 1
    Saving and Loading Models with joblib: One Pipeline, One File
  2. 2
    FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  3. 3
    Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
  4. 4
    Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
  5. 5
    Python Virtual Environments: One Project, One Toolbox
  6. 6
    Git and GitHub Fundamentals: Commits, Branches, Push and Pull
  7. 7
    Testing a FastAPI App with pytest: Three Small Tests
  8. 8
    Config and Logging Instead of Hard-Coded Values in ML Training
  9. 9
    SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. MLOps and Production ML

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.

Chaand Sheikh

·27 November 2026Serving Models

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:

KitchenMachine learning
The cooked mealThe trained pipeline
Sealing itjoblib.dump
Reheating itjoblib.load
The recipe cardrequirements.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.

Two files that drift apart, or one pipeline in one file Old way: two files model file scaler file Refit the scaler on new data and the predictions drift Better way: one file, model.joblib SimpleImputer (fills gaps) StandardScaler OneHotEncoder LogisticRegression
Save the whole pipeline. Every fitted step travels together, so nothing can drift apart.

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.

dump today, load tomorrow Today Tomorrow, fresh program model accuracy 0.831 model.joblib 4298 bytes loaded (Pipeline) accuracy 0.831 joblib.dump joblib.load
Cook once, seal it, reheat it anywhere. Same pipeline, same score.

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 fit again 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.txt with the .joblib file, always together.

Quick recap

StepCodeResult here
Train oncemodel.fit(X_train, y_train)test accuracy 0.831
Savejoblib.dump(model, "model.joblib")one file, 4,298 bytes
Loadjoblib.load("model.joblib")a Pipeline, still 0.831
Predict one dayone-row DataFrameYes, 63% chance
Pin versionsrequirements.txtscikit-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 →
Next →
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • Seal the meal, keep the recipe
  • Save the pipeline, not just the model
  • Five inputs, split first
  • Build and fit one pipeline
  • One call saves, one call loads
  • One day is still a table
  • Pin the versions
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.