32 · Lab: package and test the churn pipeline
Run it in Colab View the .ipynb
You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.
- The project folder and the data
- Exercise 1 · the package skeleton
- Exercise 2 ·
config.py - Exercise 3 ·
features.py - Exercise 4 ·
train.py - Exercise 5 ·
cli.py - Exercise 6 · tests that protect the pipeline
- Exercise 7 · run it like production
- Quiz
- Reflection
- What to show in your portfolio
- Going further
- Record your progress
Week 8 · lab · about 100 minutes
The retention team liked your churn model from Week 5, and now they want it run every quarter without anyone
opening a notebook. Your job this week: turn the pipeline into churnkit, an installable package with a config
file, logging, a command-line tool and a test suite. When you are done, this is the whole “deployment”:
churnkit --config config.yaml --set seed=3
What you will practise: everything from notebooks 29-31: modules and a package (29), pyproject.toml and a
command (29), config, logging and run folders (31), and tests that catch real bugs (30). There are no new concepts.
What you need: notebooks 29, 30 and 31 open in other tabs. Copying your own code from them is encouraged.
How grading works: each exercise writes one or two files; the grader imports them freshly and checks their behaviour. Exercise 6 grades your tests by mutation, as in notebook 30.
# --- Setup: works in Google Colab AND on your own computer. Safe to re-run. ---
# In Colab this downloads the course (about 30 s) and installs what it needs (about a minute, once
# per session). On your computer it just finds the course folder.
import os, sys, subprocess
from pathlib import Path
if "google.colab" in sys.modules and not Path("/content/mlengineering").exists():
subprocess.run(["git", "clone", "--depth", "1",
"https://github.com/berdakh/mlengineering.git", "/content/mlengineering"], check=True)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r",
"/content/mlengineering/requirements.txt"], check=True)
REPO_ROOT = Path("/content/mlengineering") if "google.colab" in sys.modules else next(
p for p in [Path.cwd(), *Path.cwd().parents] if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
from mlcourse.grader import grade, quiz
print("Ready. Course folder:", REPO_ROOT)
The project folder and the data
The next cell creates the project folder LAB with empty src/churnkit/ and tests/ folders, and exports three
tables from the shop database as CSV files into LAB/data/: in production, data usually arrives as files like
these, not as a database the model can query.
from mlcourse.graders.w08 import work_dir, show_tree, load_module, export_lab_data
LAB = work_dir() / "churnkit"
(LAB / "src" / "churnkit").mkdir(parents=True, exist_ok=True)
(LAB / "tests").mkdir(exist_ok=True)
export_lab_data(LAB / "data")
show_tree(LAB)
Exercise 1 · the package skeleton
Write LAB/pyproject.toml and src/churnkit/__init__.py:
[build-system]as in notebook 29;[project]:name = "churnkit",version = "0.1.0",requires-python = ">=3.9", anddependencieslistingpandas,scikit-learnandpyyaml;[project.scripts]: a commandchurnkitthat runsmainfromchurnkit/cli.py;[tool.pytest.ini_options]withtestpaths = ["tests"]: this table makesLABthe root folder for pytest and tells it where the tests are;__init__.py: a docstring and__version__equal to the version above.
As in notebook 29, the TOML goes between the triple quotes of a Python string.
_ = (LAB / "pyproject.toml").write_text("""\
# YOUR CODE HERE
""")
%%writefile {LAB}/src/churnkit/__init__.py
"""churnkit: the shop's churn model as a package."""
__version__ = None # YOUR CODE HERE
grade("w08.lab_project", LAB)
Exercise 2 · config.py
Write src/churnkit/config.py with
- a dataclass
Configwith fieldsdata_dir: str,cutoff: str(both required),horizon_days: int = 90,test_size: float = 0.25,seed: int = 0,runs_dir: str = "runs",log_file: str = "churnkit.log"; load_config(path, overrides=()): read the YAML file, raiseValueErrorfor unknown or missing keys, turncutoffinto a string, apply thekey=valueoverrides (converted to the field’s type;ValueErrorfor a bad one) and return aConfig.
Notebook 31’s load_config and apply_overrides do almost all of this. A useful detail: for a field f from
dataclasses.fields(Config), f.type is the class written in the annotation (int, float or str), so
f.type("3") converts text to that type.
%%writefile {LAB}/src/churnkit/config.py
"""Configuration: a dataclass, and a loader with key checks and command-line overrides."""
from dataclasses import MISSING, dataclass, fields
import yaml
@dataclass
class Config:
data_dir: str
# YOUR CODE HERE: the other six fields
def load_config(path, overrides=()):
# YOUR CODE HERE
raise NotImplementedError()
grade("w08.lab_config", LAB)
Exercise 3 · features.py
Write src/churnkit/features.py with
FEATURES = ["n_orders", "total_spent", "days_since_last_order", "tenure_days", "segment"];load_data(data_dir): readorders.csv(parseorder_date),order_items.csvandcustomers.csv(parsesignup_date) from the folder and return(orders, items, customers);build_table(orders, items, customers, cutoff, horizon_days=90): a DataFrame indexed bycustomer_id(sorted), one row per active customer (at least one non-cancelled order on or before the cutoff), with
| column | meaning |
|---|---|
n_orders |
non-cancelled orders on or before the cutoff |
total_spent |
their total value, quantity × unit_price × (1 − discount) |
days_since_last_order |
days from the last of them to the cutoff |
tenure_days |
days from signup_date to the cutoff |
segment |
from customers |
churned |
1 if the customer has no non-cancelled order with cutoff < order_date ≤ cutoff + horizon_days, else 0 |
This is notebook 29’s customer_summary plus Week 4’s label. The grader compares your table with a reference on
a small hand-made dataset and on the shop data at two cutoffs.
%%writefile {LAB}/src/churnkit/features.py
"""Load the shop CSVs and build the churn table: features from on/before the cutoff, label after it."""
from pathlib import Path
import pandas as pd
FEATURES = ["n_orders", "total_spent", "days_since_last_order", "tenure_days", "segment"]
def load_data(data_dir):
# YOUR CODE HERE
raise NotImplementedError()
def build_table(orders, items, customers, cutoff, horizon_days=90):
# YOUR CODE HERE
raise NotImplementedError()
grade("w08.lab_features", LAB)
features = load_module(LAB, "churnkit.features")
try:
lab_table = features.build_table(*features.load_data(LAB / "data"), "2025-06-30")
print(lab_table.shape, "churn rate", round(lab_table["churned"].mean(), 3))
display(lab_table.head())
except NotImplementedError:
print("Finish Exercise 3 to see the table.")
You should see 655 rows, 6 columns and a churn rate of 0.472, the same as mlcourse.churn.build_churn_table() in
notebook 31: two independent implementations agree, which is a test in itself.
Exercise 4 · train.py
Write src/churnkit/train.py with train(cfg) that
- sets up the logger named
"churnkit"(logging.getLogger("churnkit")) to write tocfg.log_file, removing old handlers first (as in notebook 31), level INFO; - loads the data from
cfg.data_dirand builds the table atcfg.cutoffwithcfg.horizon_days, then logs an INFO line with the number of customers and the churn rate; - splits
table[FEATURES]andtable["churned"]: stratified,test_size=cfg.test_size,random_state=cfg.seed; - fits this pipeline on the training rows: a
ColumnTransformerwithStandardScaler()on the four numeric features andOneHotEncoder(handle_unknown="ignore")onsegment, followed byLogisticRegression(max_iter=1000); - computes on the test rows:
accuracy,roc_auc(frompredict_proba(X_test)[:, 1]), andbaseline_accuracy: the accuracy of always predicting the most common class ofy_train; plusn_trainandn_test. All plainfloat/int; - creates a new, uniquely named folder in
cfg.runs_dirand writesconfig.json(asdict(cfg)) andmetrics.json; logs where it saved them; - returns the metrics dict with one extra key,
"run_dir": the run folder as a string.
%%writefile {LAB}/src/churnkit/train.py
"""Train and evaluate the churn model described by a Config, and save the run."""
import json
import logging
import time
import uuid
from dataclasses import asdict
from pathlib import Path
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from .features import FEATURES, build_table, load_data
logger = logging.getLogger("churnkit")
NUMERIC = ["n_orders", "total_spent", "days_since_last_order", "tenure_days"]
def train(cfg):
# YOUR CODE HERE
raise NotImplementedError()
grade("w08.lab_train", LAB)
Exercise 5 · cli.py
Write main(argv=None) in src/churnkit/cli.py: an argparse parser with a required --config option and a
repeatable --set option (action="append", default=[] collects every --set key=value into a list). Load the
config with the overrides, run train, print the returned metrics with json.dumps(metrics, indent=2), and
return 0.
%%writefile {LAB}/src/churnkit/cli.py
"""Command line: churnkit --config config.yaml [--set key=value ...]"""
import argparse
import json
from .config import load_config
from .train import train
def main(argv=None):
# YOUR CODE HERE
raise NotImplementedError()
grade("w08.lab_cli", LAB)
Exercise 6 · tests that protect the pipeline
Write tests/test_features.py and tests/test_config.py. The grader runs your suite against a correct churnkit
(it must pass) and against six copies, each with one bug that a real teammate could plausibly introduce (each must
make at least one test fail). Your tests should check these rules, using small hand-made tables (not the CSV
files):
- cancelled orders count for nothing (neither in
n_ordersnor intotal_spent); - discounts reduce
total_spent; - orders after the cutoff never change the features (and do not make a customer “active”);
- the label window is
cutoff < order_date <= cutoff + horizon_days: an order exactlyhorizon_daysafter the cutoff means the customer did not churn; load_configrejects an unknown key (pytest.raises(ValueError); write the YAML intotmp_path);- overrides are converted to the right type (
--set seed=3gives the int 3).
Rules for this exercise: tests import only churnkit.features and churnkit.config; keep helpers inside the
test_*.py files. Tip from notebook 30: give orders very different values (1, 10, 100, 1000) so a wrong total tells
you which order was miscounted.
%%writefile {LAB}/tests/test_features.py
import pandas as pd
import pytest
from churnkit.features import build_table
def test_build_table():
# YOUR CODE HERE
raise NotImplementedError()
%%writefile {LAB}/tests/test_config.py
import pytest
from churnkit.config import load_config
def test_load_config(tmp_path):
# YOUR CODE HERE
raise NotImplementedError()
!cd "{LAB}" && PYTHONPATH=src python -m pytest -q
grade("w08.lab_tests", LAB)
(PYTHONPATH=src lets this run find the package before you install it in the next step; after pip install -e,
plain python -m pytest works too.)
Exercise 7 · run it like production
Everything is in place. The next cells write the config file, install the package, run the command twice (the
second time with an override), run the test suite, and show the log. Read every output. Then set lab_run_dir to
the folder of the run with seed 0. Hint: (LAB / "runs").iterdir() lists the run folders, and each one has a
config.json you can read with json.loads(path.read_text()). (Sorting by name is not enough: two runs started
in the same second have names that differ only in their random part.)
%%writefile {LAB}/config.yaml
# Settings for one quarterly churn run. Paths are relative to the project folder.
data_dir: data
cutoff: "2025-06-30"
horizon_days: 90
test_size: 0.25
seed: 0
runs_dir: runs
log_file: churnkit.log
import shutil
from mlcourse.graders.w08 import install_project
shutil.rmtree(LAB / "runs", ignore_errors=True) # start from an empty runs/ folder
install_project(LAB) # = %pip install -q -e "{LAB}", once pyproject.toml is done
!cd "{LAB}" && churnkit --config config.yaml
!cd "{LAB}" && churnkit --config config.yaml --set seed=3
!cd "{LAB}" && python -m pytest -q
!tail -n 6 "{LAB}/churnkit.log"
lab_run_dir = None # YOUR CODE HERE
print(lab_run_dir)
grade("w08.lab_run", lab_run_dir)
show_tree(LAB)
Quiz
Q1. In churnkit, which split of responsibilities is right?
- a) Everything should stay in one notebook so it is easy to read.
- b) The config file should contain the feature logic, so it can change without code changes.
- c) The package holds the logic once, the config holds what changes between runs, the CLI connects them, the tests protect the logic, and each run folder records what happened.
- d) Tests replace evaluation, so
metrics.jsonis not needed.
answer = "?" # put your letter between the quotes
quiz("w08.32_q1", answer)
Q2. What did the grader of Exercise 6 measure?
- a) Whether your tests notice realistic bugs: they must pass on correct code and fail on each planted bug.
- b) The accuracy of your model.
- c) The percentage of lines your tests execute.
- d) How fast your tests run.
answer = "?" # put your letter between the quotes
quiz("w08.32_q2", answer)
Q3. A reviewer asks you to reproduce the ROC AUC in last quarter’s report. What makes that possible?
- a) Nothing: results with randomness cannot be reproduced.
- b) The metrics file alone.
- c) The log file alone.
- d) The run folder’s
config.json(with the seed), the code version, and the same data and library versions: rerun the command with that config and compare.
answer = "?" # put your letter between the quotes
quiz("w08.32_q3", answer)
Q4. A teammate changes <= label_end to < label_end in build_table. Which safeguard catches it?
- a) The ROC AUC: it will drop clearly.
- b) A unit test with an order exactly
horizon_daysafter the cutoff. - c) Python’s type checks.
- d) The INFO lines in the log.
answer = "?" # put your letter between the quotes
quiz("w08.32_q4", answer)
Reflection
Write a few sentences for yourself (not graded):
- Which planted bug in Exercise 6 did your first version of the tests miss, and why was it easy to miss?
- Run
churnkit --config config.yaml --set seed=1and--set seed=2. How much does the ROC AUC move between seeds? What does that tell you about reporting one number to three decimals? - What would you still need before a scheduler could run
churnkitevery quarter unattended? (Weeks 9-11 answer much of this.)
What to show in your portfolio
The churnkit folder is a small but complete ML package: a pyproject.toml with a command, a config file,
logging, run folders and a test suite that catches realistic bugs. Download it (or copy it to Google Drive), put it
in a Git repository (notebook 03), and write a short README: what it does, how to install it
(pip install -e .), how to run it (churnkit --config config.yaml), how to test it (python -m pytest), and the
metrics of one run next to the baseline. Never commit the data files of a real employer; here the data is
synthetic, so it is fine.
Going further
- Tool guides: Python packaging and environments and pytest.
- Next week: saving the trained model and serving predictions through an API, starting with 33 · Saving models and batch prediction.
Record your progress
from mlcourse.progress import mark
# mark("32", "reading")
# mark("32", "guided")