Lab: One Pipeline from Raw Rows to Predictions
Build one Pipeline with a ColumnTransformer and a custom transformer that turns raw mixed-type rows into predictions, cross-validate it correctly, save it with joblib, reload it, predict on rows with an unseen category and missing values, and prove that behaviour with a pytest test.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the raw data
- Step 2: Write the preprocessing module
- Step 3: Cross-validate the whole pipeline
- Step 4: Fit, score once and save
- Step 5: Reload and predict raw rows
- Step 6: Break it on purpose
- Step 7: Prove it with a test
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Data Preparation & Feature Engineering
- Auditing Raw Data Before You Model Concept · 20 min
- Imputation, Encoding and Scaling, Chosen by Model Family Concept · 25 min
- Worked Example: Features from Timestamps, Text and Group Aggregates Worked example · 25 min
- Lab: One Pipeline from Raw Rows to Predictions Lab · 30 min
- Worked Example: Building a Point-in-Time-Correct Training Set Worked example · 20 min
- Check: Preparing Data the Same Way Twice Knowledge check · 8 questions
What you will learn
- Choose and apply imputation, categorical encoding (one-hot, ordinal, target) and scaling strategies appropriate to the model family.
- Package all preprocessing in a Pipeline with a ColumnTransformer that is fit on training data only and handles unseen categories and missing values at inference.
01. Goal and setup
In this lab you build one scikit-learn Pipeline that takes parcel bookings exactly as the export writes them (text timestamps, a -1 code for unknown distances, gaps, rare depots, free-text notes) and returns the probability of a late delivery. You cross-validate it correctly, fit it, save it with joblib, load it in a separate script, and predict on raw rows with a depot the model has never seen and gaps in columns that had none in training. A pytest test then proves that behaviour, so a later change cannot silently break it.
The design rule: every transformation lives inside the pipeline. If cleaning happens in a notebook and is written again in the serving code, the two versions drift apart: training-serving skew. When the saved object holds every step from raw row to prediction, the serving code has nothing to reimplement.
You need Python 3.12 and four packages: scikit-learn, pandas, joblib and pytest. The lab was tested with scikit-learn 1.9.1, pandas 3.1.1, NumPy 2.5.4, joblib 1.6.0 and pytest 9.2.0. All files go into one folder; run every command from it.
fe-lab/
├── make_data.py step 1: writes parcels.csv
├── features.py step 2: the custom transformer and build_pipeline()
├── check_features.py step 2
├── evaluate.py step 3: cross-validation, writes train.csv and test.csv
├── train.py step 4: fits, scores once, writes model.joblib
├── raw_rows.py step 5: raw rows as serving receives them
├── predict.py step 5
├── break_it.py step 6
└── test_pipeline.py step 7mkdir fe-lab && cd fe-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*" joblib pytest02. Step 1: Create the raw data
The generator writes 3,000 bookings with the defects from lesson 1: about 5% of weights missing, a distance of -1 in about 4% of rows, four depots with under 30 parcels, and many empty notes. items and service have no gaps, which matters in step 6. Lateness depends on distance, weight, service, booking hour and some note phrases.
"""Write parcels.csv: 3,000 raw parcel bookings exactly as the export delivers them."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
n = 3_000
NOTES = ["", "", "", "Please call on arrival", "Gate code 4417 at the side door",
"Leave in the porch if out", "Fragile glass, handle with care"]
NOTE_EFFECT = {"Please call on arrival": 0.9, "Gate code 4417 at the side door": 0.7,
"Leave in the porch if out": -0.6}
depots = [f"D{i:02d}" for i in range(14)]
depot_p = np.r_[np.full(10, 0.096), np.full(4, 0.01)] # D10 to D13 are rare
booked = pd.Timestamp("2026-01-05") + pd.to_timedelta(
rng.integers(0, 120 * 24 * 60, n), unit="min")
df = pd.DataFrame({
"parcel_id": [f"P{i:05d}" for i in range(n)],
"booked_at": booked.strftime("%Y-%m-%d %H:%M"),
"weight_kg": rng.lognormal(0.8, 0.6, n).round(2),
"distance_km": rng.gamma(2.0, 9.0, n).round(1),
"items": rng.integers(1, 6, n),
"service": rng.choice(["standard", "express", "economy"], n, p=[0.6, 0.25, 0.15]),
"depot": rng.choice(depots, n, p=depot_p / depot_p.sum()),
"note": rng.choice(NOTES, n),
})
hour = booked.hour + booked.minute / 60
logit = (-2.0 + 0.03 * df["distance_km"] + 0.15 * df["weight_kg"]
+ 0.8 * (df["service"] == "economy") - 0.5 * (df["service"] == "express")
+ 1.0 * np.cos(2 * np.pi * (hour - 23) / 24)
+ df["note"].map(NOTE_EFFECT).fillna(0.0))
df["late"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# The export's defects: gaps in weight, and -1 when an address was not geocoded
df.loc[rng.random(n) < 0.05, "weight_kg"] = np.nan
df.loc[rng.random(n) < 0.04, "distance_km"] = -1.0
df.to_csv("parcels.csv", index=False)
raw = pd.read_csv("parcels.csv")
print(raw.shape, "| late share", round(raw["late"].mean(), 3))
print("missing per column:", raw.isna().sum()[lambda s: s > 0].to_dict())
print("distance_km == -1:", int((raw["distance_km"] == -1).sum()))
print("rarest depots:", raw["depot"].value_counts().tail(4).to_dict())python make_data.py(3000, 9) | late share 0.325
missing per column: {'weight_kg': 155, 'note': 1270}
distance_km == -1: 123
rarest depots: {'D10': 28, 'D12': 27, 'D13': 24, 'D11': 21}The CSV reader turns the 1,270 empty notes into NaN; to pandas the -1 codes are still numbers. The pipeline handles both.
03. Step 2: Write the preprocessing module
features.py holds everything that turns a raw row into model inputs. A ColumnTransformer sends each group of columns through its own steps and joins the results side by side:
- numeric: a
FunctionTransformerturns the -1 code intoNaN, a medianSimpleImputerwith missing indicators fills the gaps, andStandardScalerscales the columns for the logistic regression. The imputer sits in an innerColumnTransformeronly so that step 6 can switch it off for some columns. - categorical: an imputer writes
'missing'for absent labels, thenOneHotEncoder(handle_unknown='infrequent_if_exist', min_frequency=30). Categories with fewer than 30 training rows share one "infrequent" column, and a category never seen in training is mapped to that column too. Had no category been infrequent, an unknown one would get all zeros, exactly likehandle_unknown='ignore'. - date:
DateParts, a custom transformer, turns the timestamp text into the cyclical hour from lesson 3 plus a weekend flag. - text: the note goes through TF-IDF. The column is named as the string
"note", not the list["note"], becauseTfidfVectorizerexpects a one-dimensional sequence of strings.
DateParts subclasses BaseEstimator, which provides get_params and set_params so that clone, cross-validation and grid search can copy it, and TransformerMixin, which provides fit_transform. Its fit learns nothing and returns self. Keep these definitions in an importable module: joblib stores a class or function by its module and name, not its code, so the serving process must import the same features.py.
"""All preprocessing for the parcel model. Training and serving both import this."""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler
NUMERIC = ["weight_kg", "distance_km", "items"]
CATEGORICAL = ["service", "depot"]
RAW_COLUMNS = ["booked_at", *NUMERIC, *CATEGORICAL, "note"]
def sentinels_to_nan(X: pd.DataFrame) -> pd.DataFrame:
"""The export writes -1 when an address could not be geocoded."""
return X.replace({"distance_km": {-1.0: np.nan}})
def fill_text(notes: pd.Series) -> pd.Series:
return notes.fillna("").astype(str)
class DateParts(BaseEstimator, TransformerMixin):
"""booked_at text -> hour of day on a circle, plus a weekend flag."""
def fit(self, X, y=None):
return self # nothing to learn: every row is converted on its own
def transform(self, X):
t = pd.to_datetime(X.iloc[:, 0], format="%Y-%m-%d %H:%M", errors="coerce")
hour = t.dt.hour + t.dt.minute / 60
return pd.DataFrame({
"hour_sin": np.sin(2 * np.pi * hour / 24),
"hour_cos": np.cos(2 * np.pi * hour / 24),
"weekend": (t.dt.day_of_week >= 5).astype(float).where(t.notna()),
}, index=X.index)
def get_feature_names_out(self, input_features=None):
return np.array(["hour_sin", "hour_cos", "weekend"], dtype=object)
def build_pipeline(unknown="infrequent_if_exist", impute=tuple(NUMERIC)) -> Pipeline:
"""unknown and impute are parameters only so that the lab can break them."""
numeric = ColumnTransformer([
("gaps", SimpleImputer(strategy="median", add_indicator=True), list(impute)),
], remainder="passthrough")
prep = ColumnTransformer([
("num", make_pipeline(
FunctionTransformer(sentinels_to_nan, feature_names_out="one-to-one"),
numeric, StandardScaler()), NUMERIC),
("cat", make_pipeline(
SimpleImputer(strategy="constant", fill_value="missing"),
OneHotEncoder(handle_unknown=unknown, min_frequency=30)), CATEGORICAL),
("date", make_pipeline(DateParts(), SimpleImputer(strategy="median")),
["booked_at"]),
("text", make_pipeline(
FunctionTransformer(fill_text, feature_names_out="one-to-one"),
TfidfVectorizer(min_df=5)), "note"), # a string, not a list: 1-D input
])
return Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])import pandas as pd
from features import DateParts, build_pipeline
times = pd.DataFrame({"booked_at": ["2026-05-02 23:00", "2026-05-04 07:30", "oops"]})
print(DateParts().fit_transform(times).round(3))
print([name for name, _, _ in build_pipeline()["prep"].transformers])python check_features.py hour_sin hour_cos weekend
0 -0.259 0.966 1.0
1 0.924 -0.383 0.0
2 NaN NaN NaN
['num', 'cat', 'date', 'text']23:00 on Saturday 2 May gets the same hour pair as in lesson 3 and a weekend flag of 1. The unparseable "oops" becomes NaN instead of an error, which the imputer after DateParts will fill.
04. Step 3: Cross-validate the whole pipeline
First split off a 20% test set; leave it alone until step 4. Then compare two ways of cross-validating the training rows. The first fits the preprocessing once on all training rows and cross-validates only the model. The second passes the whole pipeline to cross_val_score, which refits every step inside each training fold.
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from features import RAW_COLUMNS, build_pipeline
df = pd.read_csv("parcels.csv")
train, test = train_test_split(df, test_size=0.2, stratify=df["late"], random_state=2)
train.to_csv("train.csv", index=False)
test.to_csv("test.csv", index=False)
X, y = train[RAW_COLUMNS], train["late"]
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Wrong: preprocessing learns medians, categories and vocabulary from every row,
# including the rows each fold will later be validated on
X_prep = build_pipeline()["prep"].fit_transform(X)
wrong = cross_val_score(LogisticRegression(max_iter=1000), X_prep, y, cv=folds,
scoring="roc_auc")
# Right: the whole pipeline is refitted inside each training fold
right = cross_val_score(build_pipeline(), X, y, cv=folds, scoring="roc_auc")
print(f"train rows {len(train)}, test rows {len(test)} (test is not touched here)")
print(f"preprocess, then CV AUC {wrong.mean():.4f} ± {wrong.std():.4f}")
print(f"CV of the pipeline AUC {right.mean():.4f} ± {right.std():.4f}")
# What the wrong version let the validation rows decide, in the first fold
fit_idx, val_idx = next(folds.split(X, y))
for name, rows in [("fit rows only", X.iloc[fit_idx]), ("all rows", X)]:
num = build_pipeline()["prep"].fit(rows).named_transformers_["num"]
medians = num[1].named_transformers_["gaps"].statistics_.round(2).tolist()
print(f"{name:<14} medians of weight, distance, items: {medians}")python evaluate.pytrain rows 2400, test rows 600 (test is not touched here)
preprocess, then CV AUC 0.7540 ± 0.0170
CV of the pipeline AUC 0.7540 ± 0.0170
fit rows only medians of weight, distance, items: [2.23, 15.1, 3.0]
all rows medians of weight, distance, items: [2.22, 15.1, 3.0]The two scores agree to four decimal places here, which is no reason to use the first form. In it, each fold's validation rows helped choose their own fill values (2.22 instead of 2.23), and likewise scaler means, category lists and the TF-IDF vocabulary. These steps learn little from 2,400 rows, so the effect is small this time. Steps that learn from labels, such as target encoding or feature selection, pass validation labels into the features this way, and the optimism can be large. The second form also gives you one object that is both what you evaluated and what you deploy.
05. Step 4: Fit, score once and save
Fit the pipeline on all training rows, score the test set once, and save it. The script also writes reference.csv: five test rows with the probabilities predicted at training time, which step 7 uses to check that the reloaded model gives the same answers.
import joblib
import pandas as pd
import sklearn
from sklearn.metrics import roc_auc_score
from features import RAW_COLUMNS, build_pipeline
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
model = build_pipeline().fit(train[RAW_COLUMNS], train["late"])
proba = model.predict_proba(test[RAW_COLUMNS])[:, 1]
print(f"held-out test AUC {roc_auc_score(test['late'], proba):.3f} (scored once)")
names = model["prep"].get_feature_names_out()
print(len(names), "model inputs, including:")
for i in [0, 3, 4, 18, 19, 25]:
print(" ", names[i])
joblib.dump(model, "model.joblib")
# Record a few predictions so that serving can be checked against training
test.head(5).assign(expected=proba[:5]).to_csv("reference.csv", index=False)
print("saved model.joblib with scikit-learn", sklearn.__version__)python train.pyheld-out test AUC 0.754 (scored once)
43 model inputs, including:
num__gaps__weight_kg
num__gaps__missingindicator_weight_kg
num__gaps__missingindicator_distance_km
cat__depot_infrequent_sklearn
date__hour_sin
text__call
saved model.joblib with scikit-learn 1.9.1The test AUC, 0.754, matches the cross-validated estimate, as an honest evaluation should. The feature names show the structure: prefixes name the transformer, there are indicators for weight and distance (the columns with gaps after cleaning) but not for items, and the four rare depots share cat__depot_infrequent_sklearn.
Record the library versions with the model: loading it with another scikit-learn version raises an InconsistentVersionWarning and is not supported. joblib uses Python's pickle format, so loading a file can run code; load only files you trust, or consider skops.io, a more secure format.
06. Step 5: Reload and predict raw rows
Serving receives rows as JSON. raw_rows.py builds three: an ordinary booking, a booking at a depot that opened after training, and a row with gaps everywhere, including items and service, which never had gaps in training.
"""Raw rows as serving receives them. predict.py, break_it.py and the test use them."""
import numpy as np
import pandas as pd
def messy_rows() -> pd.DataFrame:
return pd.DataFrame([
# 0: an ordinary booking
{"booked_at": "2026-05-04 10:15", "weight_kg": 2.1, "distance_km": 12.0,
"items": 2, "service": "standard", "depot": "D03",
"note": "Leave in the porch"},
# 1: a depot that opened after training
{"booked_at": "2026-05-04 22:40", "weight_kg": 2.1, "distance_km": 12.0,
"items": 2, "service": "standard", "depot": "D99", "note": None},
# 2: gaps everywhere, the -1 code, and items/service missing for the first time
{"booked_at": None, "weight_kg": np.nan, "distance_km": -1.0,
"items": np.nan, "service": None, "depot": "D03", "note": None},
])import joblib
from raw_rows import messy_rows
model = joblib.load("model.joblib") # load only files you trust: this runs pickle
print(model.predict_proba(messy_rows())[:, 1].round(3))python predict.py[0.044 0.407 0.404]All three rows get a probability. Depot D99 falls into the infrequent column. In the third row the time features, weight, items and the -1 distance get training medians, indicators flag the weight and distance gaps, service becomes 'missing' and then all zeros, and the empty note an all-zero TF-IDF vector.
07. Step 6: Break it on purpose
To see what those choices protect against, fit two broken variants on the same data: one with the encoder's default handle_unknown='error', and one with imputers only on the columns that had gaps in training.
import pandas as pd
from features import NUMERIC, RAW_COLUMNS, build_pipeline, sentinels_to_nan
from raw_rows import messy_rows
train = pd.read_csv("train.csv")
gaps = sentinels_to_nan(train[RAW_COLUMNS]).isna().sum()
print("training gaps after cleaning:", gaps[gaps > 0].to_dict())
variants = {
"OneHotEncoder(handle_unknown='error')": build_pipeline(unknown="error"),
"imputers only where training had gaps": build_pipeline(
impute=[c for c in NUMERIC if gaps[c] > 0]),
}
rows = messy_rows()
for name, pipe in variants.items():
pipe.fit(train[RAW_COLUMNS], train["late"]) # fitting works in both cases
print(name)
for i in [1, 2]:
try:
pipe.predict_proba(rows.iloc[[i]])
print(f" row {i}: ok")
except ValueError as e:
print(f" row {i}: ValueError: {str(e).splitlines()[0]}")python break_it.pytraining gaps after cleaning: {'weight_kg': 118, 'distance_km': 99, 'note': 1001}
OneHotEncoder(handle_unknown='error')
row 1: ValueError: Found unknown categories ['D99'] in column 1 during transform
row 2: ValueError: Found unknown categories ['missing'] in column 0 during transform
imputers only where training had gaps
row 1: ok
row 2: ValueError: Input X contains NaN.Both variants fit fine and fail only on rows that production will send. With 'error', the unseen depot fails, and so does the missing service: training had no gaps in that column, so the imputer's 'missing' is itself a category the encoder never saw. In the second variant, items had no gaps in training, so it got no imputer, the scaler passes its NaN through, and the logistic regression rejects it. Production data can have gaps where training data had none, so give every column a fitted strategy for them.
08. Step 7: Prove it with a test
Turn steps 5 and 6 into a test that fails if an imputer is removed or handle_unknown changes. The tests check that messy raw rows get valid probabilities, that the number of feature columns stays what the model was fitted on, that a -1 distance is treated exactly like a missing one, and that the reloaded model reproduces the predictions recorded at training time. If you skipped pytest during setup, install it now with python -m pip install pytest.
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import pytest
from features import RAW_COLUMNS
from raw_rows import messy_rows
HERE = Path(__file__).parent
@pytest.fixture(scope="module")
def model():
return joblib.load(HERE / "model.joblib")
def test_predicts_on_unseen_category_and_missing_values(model):
proba = model.predict_proba(messy_rows())[:, 1]
assert proba.shape == (3,)
assert np.all((proba > 0) & (proba < 1))
def test_feature_columns_are_stable(model):
features = model["prep"].transform(messy_rows())
assert features.shape[1] == model["model"].n_features_in_
def test_sentinel_is_treated_as_missing(model):
rows = messy_rows().iloc[[0, 0]].reset_index(drop=True)
rows.loc[0, "distance_km"] = -1.0
rows.loc[1, "distance_km"] = np.nan
p = model.predict_proba(rows)[:, 1]
assert p[0] == pytest.approx(p[1])
def test_reloaded_model_matches_training_run(model):
ref = pd.read_csv(HERE / "reference.csv")
got = model.predict_proba(ref[RAW_COLUMNS])[:, 1]
np.testing.assert_allclose(got, ref["expected"], rtol=1e-9)python -m pytest -q test_pipeline.py.... [100%]
4 passed in 2.85sFour dots: four passing tests. To see a failure, change unknown="infrequent_if_exist" to unknown="error" in build_pipeline, rerun train.py and the test: the first two tests fail on the D99 row. Run it automatically whenever the pipeline changes.
09. Troubleshooting
10. Check your understanding
11. Apply it: stretch tasks
- Your own data. Adapt
features.pyto your practice dataset: one branch per column type, at least two engineered features from lesson 3, and an imputer for every column. Cross-validate it as in step 3 and keep the test of step 7, rewritten with raw rows from your domain. - A second model family. Add
build_tree_pipeline()withHistGradientBoostingClassifier, ordinal encoding (OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)) and no scaler, and compare both pipelines on the same folds. - Tune inside the pipeline. Run
GridSearchCVoverprep__text__tfidfvectorizer__min_dfandmodel__C, and check with a test that the best estimator still passes all four tests.
12. Review prompt
Without looking back, answer in your own words:
- Why must the sentinel conversion and the imputers live inside the pipeline rather than in a cleaning script?
- What does
handle_unknown='infrequent_if_exist'do with an unseen category, with and without infrequent categories? - Why can a column with no gaps in training still break the model in production?
- What is wrong with fitting the preprocessing on all rows and then cross-validating the model, even when the scores barely differ?
- What must be true of
features.pyforjoblib.loadto work in the serving process?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.