This is Module 2 of the Machine Learning Engineer path. Module 1 was about knowing whether a model is good. This one is about making sure the model you evaluated is the model that runs in production. The most common way that breaks is preprocessing: the steps that clean and encode data before the model sees it.
You’ll build: a churn model as one scikit-learn pipeline that takes raw records, handles missing values and new categories, is saved as a single file, and comes with tests.
You need: Python with scikit-learn, pandas, joblib and pytest (pip install scikit-learn pandas joblib pytest).
Setup: customer data
Save this as make_data.py and run it once:
# Synthetic customer data: will a customer cancel next month? Fixed seed, so your numbers match.
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 2_000
plan = rng.choice(["basic", "pro", "team"], size=n, p=[0.5, 0.35, 0.15])
tenure = rng.integers(1, 60, size=n)
tickets = rng.poisson(1.5, size=n)
spend = np.round(np.select([plan == "basic", plan == "pro"], [19, 49], 99) * rng.uniform(0.8, 1.2, size=n), 2)
logit = -1.0 + 0.45 * tickets - 0.05 * tenure + np.where(plan == "basic", 0.8, 0.0)
churned = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df = pd.DataFrame({"plan": plan, "tenure_months": tenure, "support_tickets": tickets,
"monthly_spend": spend, "churned": churned})
df.loc[rng.random(n) < 0.05, "monthly_spend"] = np.nan # 5% missing, as real exports often are
df.to_csv("customers.csv", index=False)
print(f"wrote customers.csv: {n} rows, churn rate {churned.mean():.1%}")
wrote customers.csv: 2000 rows, churn rate 23.8%
1. The notebook way, and how it breaks
Here’s a typical notebook model: one-hot encode the plan with pd.get_dummies, fill missing spend with the median, train. Then a new customer arrives in production. Save this as manual.py:
# The notebook way: preprocessing done by hand, model trained on the result.
import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("customers.csv")
X = pd.get_dummies(df.drop(columns="churned"), columns=["plan"])
X["monthly_spend"] = X["monthly_spend"].fillna(X["monthly_spend"].median())
model = LogisticRegression(max_iter=1000).fit(X, df["churned"])
print("trained on columns:", list(X.columns))
# Production: one new customer arrives as a raw record.
new = pd.DataFrame([{"plan": "pro", "tenure_months": 3, "support_tickets": 4, "monthly_spend": 52.0}])
X_new = pd.get_dummies(new, columns=["plan"])
print("serving columns: ", list(X_new.columns))
try:
print(model.predict_proba(X_new)[:, 1])
except ValueError as e:
print("ValueError:", str(e).splitlines()[0])
trained on columns: ['tenure_months', 'support_tickets', 'monthly_spend', 'plan_basic', 'plan_pro', 'plan_team']
serving columns: ['tenure_months', 'support_tickets', 'monthly_spend', 'plan_pro']
ValueError: The feature names should match those that were passed during fit.
get_dummies creates one column per value it sees. The training data had three plans; a single new record has one, so the columns don’t match. This failure is loud, which is lucky. Patch it by hand and you have to re-create, in the serving code, every choice the notebook made: the column order, the median used for missing spend, any scaling. Each copy is a chance for the two to drift apart. scikit-learn’s guide calls this inconsistent preprocessing: transforms used in training “also must be used on subsequent datasets, whether it’s test data or data in a production system”, or “the feature space will change, and the model will not be able to perform effectively”.
2. One pipeline: fitted once, saved once
The fix is to make preprocessing part of the model. A ColumnTransformer applies the right steps to each kind of column, and a Pipeline chains it to the model, so fit, predict and saving all cover both. Save this as pipeline.py:
# The same model as one pipeline: every step that learns from data is fitted together and saved together.
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.read_csv("customers.csv")
X, y = df.drop(columns="churned"), df["churned"]
numeric = ["tenure_months", "support_tickets", "monthly_spend"]
categorical = ["plan"]
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=1000))])
# Cross-validation refits the imputer, scaler and encoder inside each fold: no leakage.
auc = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(f"cross-validated ROC AUC: {auc.mean():.3f} (+/- {auc.std():.3f})")
model.fit(X, y)
joblib.dump(model, "churn_model.joblib")
print("saved churn_model.joblib")
cross-validated ROC AUC: 0.761 (+/- 0.012)
saved churn_model.joblib
Three things changed:
- The median, the scaling and the plan categories are learned by
fitand stored inside the pipeline. Nothing is re-computed by hand at serving time. - Cross-validation is honest. Because the whole pipeline is passed to
cross_val_score, the imputer, scaler and encoder are refitted on each training fold, the rule from Module 1’s leakage experiment. handle_unknown="ignore"tells the encoder what to do with a category it never saw: per the scikit-learn documentation, its one-hot columns are all zeros instead of an error.
3. Serving raw records
Production code now has one job: load the file and pass records as they arrive. Save this as serve.py:
# Production: load the saved pipeline and score raw records, exactly as they arrive.
import joblib
import pandas as pd
model = joblib.load("churn_model.joblib")
records = [
{"plan": "pro", "tenure_months": 3, "support_tickets": 4, "monthly_spend": 52.0},
{"plan": "basic", "tenure_months": 40, "support_tickets": 0, "monthly_spend": None}, # missing value
{"plan": "enterprise", "tenure_months": 12, "support_tickets": 1, "monthly_spend": 250.0}, # unseen plan
]
for r, p in zip(records, model.predict_proba(pd.DataFrame(records))[:, 1]):
print(f"{r['plan']:>10}: churn probability {p:.2f}")
pro: churn probability 0.64
basic: churn probability 0.11
enterprise: churn probability 0.27
The missing spend was filled with the training median, and the unseen “enterprise” plan scored without crashing. Whether scoring it is right is a product decision: an unseen category is also a sign the world has changed, which Module 5 turns into monitoring.
4. Tests that protect the shipped model
A saved model can still change behind your back: a library upgrade, a retrain on different data, someone editing the feature list. Two small tests catch most of that. Save this as test_pipeline.py and run pytest test_pipeline.py:
# Tests that fail if the saved model stops behaving as it did when you shipped it. Run: pytest test_pipeline.py
import joblib
import pandas as pd
model = joblib.load("churn_model.joblib")
def test_known_customer_scores_as_recorded():
# A "golden" record: its score was written down when the model was approved.
record = pd.DataFrame([{"plan": "pro", "tenure_months": 3, "support_tickets": 4, "monthly_spend": 52.0}])
assert abs(model.predict_proba(record)[0, 1] - 0.64) < 0.01
def test_missing_value_and_new_plan_still_score():
record = pd.DataFrame([{"plan": "enterprise", "tenure_months": 12, "support_tickets": 1, "monthly_spend": None}])
assert 0.0 <= model.predict_proba(record)[0, 1] <= 1.0
2 passed
The first is a golden-record test: a known customer’s score, written down when the model was approved. If it moves, someone has to decide whether that was intended. The second checks that awkward inputs still produce a valid probability.
A checklist before you ship a model
- Every step that learns from data is inside one pipeline object.
- Cross-validation runs on the whole pipeline, not on pre-transformed data.
- The serving code loads that one file and does no feature work of its own.
- Missing values and unseen categories have a deliberate behaviour, not a crash.
- A golden-record test runs in CI.
Project
Take a model from one of your own notebooks and rebuild it as a single pipeline that loads raw data, transforms it and predicts, with no manual steps. Add a golden-record test. Then change one preprocessing choice (say, mean instead of median) and check that the test catches it.
Next: Module 3: Model Families You’ll Actually Use, comparing linear models, random forests and gradient boosting.