TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Mini Project: Your Own Capstone

Mini Project: Your Own Capstone

The fifteen projects of this course were chosen for you. The capstone is the one you choose yourself: a problem you care about, framed, built, evaluated and shipped with the workflow of the course, and written up so that someone else can judge it. This lesson has two parts. Part A is a complete worked capstone on a problem none of the fifteen projects covers, predictive maintenance for a fleet of pumps, so you can see the whole workflow once more with every decision explained. Part B gives you the proposal template, the milestones and the rubric for your own.

Part A: predictive maintenance for a pump fleet

A water utility runs 60 pumps. When a pump fails, a district loses pressure and an emergency crew is called out. Each pump reports a daily average of three sensors: bearing temperature, vibration and outlet pressure. The maintenance team can inspect three pumps a day, and a repair needs two days to plan. The question: which three pumps should they inspect today?

Framing and success criteria

Question Answer
User and decision the maintenance planner picks 3 pumps a day to inspect
Input at decision time each pump's daily readings up to and including today
Target the pump fails within the next 7 days; known a week later, from the work-order system
Cost of errors a missed failure: an outage and an emergency call-out; a useless inspection: a crew's half day
Metric failures caught: share of failures whose pump was on the list 2 to 7 days before (enough time to plan the repair)
Success criteria at least 0.50 of the test-period failures caught, and at least 0.15 more than the current rule "inspect the pumps with the highest vibration"
Constraints daily batch, explainable to the planners, runs on a laptop

The metric is chosen for the decision, not for the model: a fixed budget of 3 inspections a day means what matters is the ranking within each day, not a probability threshold (log loss and thresholds, classification metrics).

Step 1: the data

The generator simulates a year of daily readings. Every pump has its own baseline level for each sensor plus daily noise. Failures come in two modes: a bearing failure announces itself for 10 to 25 days with rising vibration and temperature; a seal failure shows only a pressure drop over the last 2 to 5 days. After a failure the pump is repaired and its readings return to its baseline. Features are rolling means over 3, 7 and 28 days and their differences (a trend: the last week against the last four), computed per pump from past readings only (lag, rolling and group features).

python · try it yourself
import numpy as np
import pandas as pd

def make_fleet(seed=0, n_machines=60, n_days=365):
    """Daily sensor readings of a pump fleet with two failure modes; returns readings and failures."""
    rng = np.random.default_rng(seed)
    frames, failures = [], []
    for m in range(n_machines):
        temp = rng.normal(60, 3) + rng.normal(0, 1.0, n_days)
        vib = rng.normal(2.0, 0.2) + rng.normal(0, 0.15, n_days)
        pres = rng.normal(5.0, 0.2) + rng.normal(0, 0.1, n_days)
        day = int(rng.integers(15, 150))
        while day < n_days:
            mode = "bearing" if rng.random() < 0.6 else "seal"
            ramp = int(rng.integers(10, 26)) if mode == "bearing" else int(rng.integers(2, 6))
            k = np.arange(max(0, day - ramp), day)
            w = ((k - (day - ramp) + 1) / ramp) ** 2
            if mode == "bearing":
                vib[k] += 0.6 * w
                temp[k] += 3.0 * w
            else:
                pres[k] -= 0.6 * w
            failures.append((m, day, mode, ramp))
            day += int(rng.integers(60, 200))
        frames.append(pd.DataFrame({"machine": m, "day": np.arange(n_days),
                                    "temp": temp.round(2), "vib": vib.round(3), "pres": pres.round(3)}))
    return pd.concat(frames, ignore_index=True), pd.DataFrame(failures, columns=["machine", "day", "mode", "ramp"])

def add_features_and_label(df, fails, horizon=7):
    """Features use only readings up to and including the day; label = a failure in the next `horizon` days."""
    df = df.sort_values(["machine", "day"]).copy()
    g = df.groupby("machine")
    for col in ("temp", "vib", "pres"):
        df[f"{col}_7"] = g[col].transform(lambda s: s.rolling(7, min_periods=1).mean())
        df[f"{col}_28"] = g[col].transform(lambda s: s.rolling(28, min_periods=1).mean())
        df[f"{col}_trend"] = df[f"{col}_7"] - df[f"{col}_28"]
        df[f"{col}_3"] = g[col].transform(lambda s: s.rolling(3, min_periods=1).mean())
    df["pres_drop"] = df["pres_28"] - df["pres_3"]
    df["y"] = 0
    for m, d, _, _ in fails.itertuples(index=False):
        df.loc[(df.machine == m) & (df.day >= d - horizon) & (df.day < d), "y"] = 1
    return df

readings, fails = make_fleet()
df = add_features_and_label(readings, fails)
print(f"{len(readings)} daily readings, {readings.machine.nunique()} machines, {len(fails)} failures")
print(fails["mode"].value_counts().to_string())
print(f"rows labelled 'fails within 7 days': {df.y.mean():.1%}")
for name, lo, hi in [("train", 0, 233), ("validation", 240, 300), ("test", 300, 358)]:
    print(f"{name:10} days {lo:3}-{hi - 1:3}: failures {((fails.day > lo) & (fails.day <= hi)).sum():3}")
print(df.loc[df.y == 1, ["vib_7", "pres_drop"]].mean().round(3).to_dict(), "(about to fail)")
print(df.loc[df.y == 0, ["vib_7", "pres_drop"]].mean().round(3).to_dict(), "(healthy)")
21900 daily readings, 60 machines, 171 failures
mode
bearing    97
seal       74
rows labelled 'fails within 7 days': 5.5%
train      days   0-232: failures 107
validation days 240-299: failures  27
test       days 300-357: failures  26
{'vib_7': 2.124, 'pres_drop': 0.025} (about to fail)
{'vib_7': 1.974, 'pres_drop': -0.001} (healthy)

In a real utility the readings come from the SCADA historian and the labels from work orders, which are often late, vague ("pump noisy, replaced bearing") or missing, so label quality would be the first thing to check (label quality). Here, 5.5 % of pump-days are labelled positive, and the averages already show the signal: vibration is higher before a failure (2.124 against 1.974), and the pressure drop is small but positive.

Step 2: a time split with a gap

Rows of the same pump on consecutive days are strongly related, and the model will always predict the future, so the split is by time. One subtlety: a label looks 7 days ahead, so the last training rows "know" about failures in the first validation days. A gap of 7 days between the periods removes this leak (time-series backtesting, leakage rules).

train: days 0-232 val 240-299 test 300-357 gapno labels yet day 0labels look 7 days ahead, so each period ends 7 days before the next one starts

Before the test period, the final model is refitted on everything up to day 292, again with a gap. The test period has only 26 failures; any score on it will carry a wide interval, which the write-up must say.

Step 3: the baseline ladder, on validation

The ladder has four rungs: a random list (the no-skill floor), the planners' current rule, a logistic regression and gradient boosting (logistic regression, gradient boosting).

python · try it yourself
import numpy as np
import pandas as pd

def make_fleet(seed=0, n_machines=60, n_days=365):
    """Daily sensor readings of a pump fleet with two failure modes; returns readings and failures."""
    rng = np.random.default_rng(seed)
    frames, failures = [], []
    for m in range(n_machines):
        temp = rng.normal(60, 3) + rng.normal(0, 1.0, n_days)
        vib = rng.normal(2.0, 0.2) + rng.normal(0, 0.15, n_days)
        pres = rng.normal(5.0, 0.2) + rng.normal(0, 0.1, n_days)
        day = int(rng.integers(15, 150))
        while day < n_days:
            mode = "bearing" if rng.random() < 0.6 else "seal"
            ramp = int(rng.integers(10, 26)) if mode == "bearing" else int(rng.integers(2, 6))
            k = np.arange(max(0, day - ramp), day)
            w = ((k - (day - ramp) + 1) / ramp) ** 2
            if mode == "bearing":
                vib[k] += 0.6 * w
                temp[k] += 3.0 * w
            else:
                pres[k] -= 0.6 * w
            failures.append((m, day, mode, ramp))
            day += int(rng.integers(60, 200))
        frames.append(pd.DataFrame({"machine": m, "day": np.arange(n_days),
                                    "temp": temp.round(2), "vib": vib.round(3), "pres": pres.round(3)}))
    return pd.concat(frames, ignore_index=True), pd.DataFrame(failures, columns=["machine", "day", "mode", "ramp"])

def add_features_and_label(df, fails, horizon=7):
    """Features use only readings up to and including the day; label = a failure in the next `horizon` days."""
    df = df.sort_values(["machine", "day"]).copy()
    g = df.groupby("machine")
    for col in ("temp", "vib", "pres"):
        df[f"{col}_7"] = g[col].transform(lambda s: s.rolling(7, min_periods=1).mean())
        df[f"{col}_28"] = g[col].transform(lambda s: s.rolling(28, min_periods=1).mean())
        df[f"{col}_trend"] = df[f"{col}_7"] - df[f"{col}_28"]
        df[f"{col}_3"] = g[col].transform(lambda s: s.rolling(3, min_periods=1).mean())
    df["pres_drop"] = df["pres_28"] - df["pres_3"]
    df["y"] = 0
    for m, d, _, _ in fails.itertuples(index=False):
        df.loc[(df.machine == m) & (df.day >= d - horizon) & (df.day < d), "y"] = 1
    return df

FEATURES = ["temp_7", "vib_7", "pres_7", "temp_trend", "vib_trend", "pres_trend", "pres_drop"]

def daily_top_k(df, score, k=3):
    """The k machines with the highest score on each day: the inspection list."""
    d = df.assign(score=score)
    return d.sort_values(["day", "score"], ascending=[True, False]).groupby("day").head(k)[["machine", "day"]]

def catch_rate(df, score, fails, k=3, horizon=7, lead=2):
    """Share of failures whose machine was on the inspection list 2 to 7 days before (2 days to plan the repair)."""
    lists = daily_top_k(df, score, k)
    days = set(df.day)
    inspected = set(zip(lists.machine, lists.day))
    fl = fails[fails.day - 1 >= min(days)]
    fl = fl[fl.day - 1 <= max(days)]
    hit = [any((m, t) in inspected for t in range(d - horizon, d - lead + 1)) for m, d in zip(fl.machine, fl.day)]
    return float(np.mean(hit)), len(fl), np.array(hit)

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

readings, fails = make_fleet()
df = add_features_and_label(readings, fails)
train = df[df.day < 233]                       # 7-day gap: train labels never look into validation
val = df[(df.day >= 240) & (df.day < 300)]
rng = np.random.default_rng(0)

candidates = {
    "random list": rng.random(len(val)),
    "rule: highest vibration": val.vib_7.to_numpy(),
}
models = {
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    "gradient boosting": HistGradientBoostingClassifier(max_depth=3, learning_rate=0.1, random_state=0),
}
for name, model in models.items():
    model.fit(train[FEATURES], train.y)
    candidates[name] = model.predict_proba(val[FEATURES])[:, 1]

print("validation (days 240-299), 3 inspections a day")
for name, score in candidates.items():
    rate, n, _ = catch_rate(val, score, fails)
    print(f"  {name:28} caught {rate:.2f} of {n} failures")
validation (days 240-299), 3 inspections a day
  random list                  caught 0.30 of 27 failures
  rule: highest vibration      caught 0.37 of 27 failures
  logistic regression          caught 0.56 of 27 failures
  gradient boosting            caught 0.56 of 27 failures

A random list already catches 0.30 of failures, because 3 of 60 pumps on each of 6 days gives every pump several chances. The vibration rule barely beats it (0.37): pumps differ in their normal vibration, so the list fills with pumps that are always a little loud. Both models reach 0.56, by looking at the trend of each pump against its own recent past. With a tie on validation, the simpler, more explainable model wins: logistic regression. (The difference between 0.56 and 0.37 is 5 failures of 27, so it is a real but not a precise gap.)

Step 4: test once, then the errors

python · try it yourself
import numpy as np
import pandas as pd

def make_fleet(seed=0, n_machines=60, n_days=365):
    """Daily sensor readings of a pump fleet with two failure modes; returns readings and failures."""
    rng = np.random.default_rng(seed)
    frames, failures = [], []
    for m in range(n_machines):
        temp = rng.normal(60, 3) + rng.normal(0, 1.0, n_days)
        vib = rng.normal(2.0, 0.2) + rng.normal(0, 0.15, n_days)
        pres = rng.normal(5.0, 0.2) + rng.normal(0, 0.1, n_days)
        day = int(rng.integers(15, 150))
        while day < n_days:
            mode = "bearing" if rng.random() < 0.6 else "seal"
            ramp = int(rng.integers(10, 26)) if mode == "bearing" else int(rng.integers(2, 6))
            k = np.arange(max(0, day - ramp), day)
            w = ((k - (day - ramp) + 1) / ramp) ** 2
            if mode == "bearing":
                vib[k] += 0.6 * w
                temp[k] += 3.0 * w
            else:
                pres[k] -= 0.6 * w
            failures.append((m, day, mode, ramp))
            day += int(rng.integers(60, 200))
        frames.append(pd.DataFrame({"machine": m, "day": np.arange(n_days),
                                    "temp": temp.round(2), "vib": vib.round(3), "pres": pres.round(3)}))
    return pd.concat(frames, ignore_index=True), pd.DataFrame(failures, columns=["machine", "day", "mode", "ramp"])

def add_features_and_label(df, fails, horizon=7):
    """Features use only readings up to and including the day; label = a failure in the next `horizon` days."""
    df = df.sort_values(["machine", "day"]).copy()
    g = df.groupby("machine")
    for col in ("temp", "vib", "pres"):
        df[f"{col}_7"] = g[col].transform(lambda s: s.rolling(7, min_periods=1).mean())
        df[f"{col}_28"] = g[col].transform(lambda s: s.rolling(28, min_periods=1).mean())
        df[f"{col}_trend"] = df[f"{col}_7"] - df[f"{col}_28"]
        df[f"{col}_3"] = g[col].transform(lambda s: s.rolling(3, min_periods=1).mean())
    df["pres_drop"] = df["pres_28"] - df["pres_3"]
    df["y"] = 0
    for m, d, _, _ in fails.itertuples(index=False):
        df.loc[(df.machine == m) & (df.day >= d - horizon) & (df.day < d), "y"] = 1
    return df

FEATURES = ["temp_7", "vib_7", "pres_7", "temp_trend", "vib_trend", "pres_trend", "pres_drop"]

def daily_top_k(df, score, k=3):
    """The k machines with the highest score on each day: the inspection list."""
    d = df.assign(score=score)
    return d.sort_values(["day", "score"], ascending=[True, False]).groupby("day").head(k)[["machine", "day"]]

def catch_rate(df, score, fails, k=3, horizon=7, lead=2):
    """Share of failures whose machine was on the inspection list 2 to 7 days before (2 days to plan the repair)."""
    lists = daily_top_k(df, score, k)
    days = set(df.day)
    inspected = set(zip(lists.machine, lists.day))
    fl = fails[fails.day - 1 >= min(days)]
    fl = fl[fl.day - 1 <= max(days)]
    hit = [any((m, t) in inspected for t in range(d - horizon, d - lead + 1)) for m, d in zip(fl.machine, fl.day)]
    return float(np.mean(hit)), len(fl), np.array(hit)

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

readings, fails = make_fleet()
df = add_features_and_label(readings, fails)
dev = df[df.day < 293]                         # train + validation, 7-day gap before the test period
test = df[(df.day >= 300) & (df.day < 358)]
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(dev[FEATURES], dev.y)
score = model.predict_proba(test[FEATURES])[:, 1]

rate, n, hit = catch_rate(test, score, fails)
rule_rate, _, _ = catch_rate(test, test.vib_7.to_numpy(), fails)
print(f"TEST (days 300-357, used once): model caught {rate:.2f} of {n} failures, rule {rule_rate:.2f}")

rng = np.random.default_rng(0)
boot = [hit[rng.integers(0, n, n)].mean() for _ in range(2000)]
print(f"95 % bootstrap interval over failures: {np.percentile(boot, 2.5):.2f}-{np.percentile(boot, 97.5):.2f}")

fl = fails[(fails.day - 1 >= 300) & (fails.day - 1 <= 357)].assign(caught=hit)
print("\nby failure mode:")
print(fl.groupby("mode").caught.agg(["size", "mean"]).round(2).to_string())
print("\nseal failures by warning time (ramp days):")
print(fl[fl["mode"] == "seal"].groupby("ramp").caught.agg(["size", "mean"]).round(2).to_string())
lists = daily_top_k(test, score)
useful = lists.merge(test[["machine", "day", "y"]], on=["machine", "day"]).y.mean()
print(f"\ninspections that found a machine failing within 7 days: {useful:.2f}")
TEST (days 300-357, used once): model caught 0.62 of 26 failures, rule 0.38
95 % bootstrap interval over failures: 0.42-0.81

by failure mode:
         size  mean
mode
bearing    15  0.87
seal       11  0.27

seal failures by warning time (ramp days):
      size  mean
ramp
2        4  0.00
3        4  0.25
4        3  0.67

inspections that found a machine failing within 7 days: 0.53

The test result: 0.62 of 26 failures caught (95 % bootstrap interval 0.42–0.81), against 0.38 for the vibration rule. Both criteria are met on the point estimates (0.62 ≥ 0.50 and 0.24 more than the rule), but the interval's lower end is below 0.50: with 26 failures the test period cannot promise the target, and the write-up says so. The test score is a little higher than the validation score (0.56); with so few failures, a difference of this size is within the noise.

The error analysis is the most useful output of the project. Bearing failures are caught 0.87 of the time, seal failures 0.27, and the seal failures that give only 2 days of warning are never caught. That is not a modelling problem: a pressure drop that starts 2 days before the failure cannot appear on a list 2 days ahead in daily data. The fix is a different data source (hourly pressure with an alarm), not a different algorithm. About half of all inspections (0.53) find a pump that really fails within a week, ten times the base rate of 5.5 %.

Step 5: ship it as a service

The planners need a daily list, so the natural product is a nightly batch job (batch vs real time). The control room also wants to check a single pump on demand, which needs an API. The service below scores one pump from its last 28 days of readings. It calls the same feature function as training, so the service cannot compute a feature differently from the training code (training-serving skew, production ML systems), and it validates its input with Pydantic (FastAPI for model serving).

python · try it yourself
import numpy as np
import pandas as pd

def make_fleet(seed=0, n_machines=60, n_days=365):
    """Daily sensor readings of a pump fleet with two failure modes; returns readings and failures."""
    rng = np.random.default_rng(seed)
    frames, failures = [], []
    for m in range(n_machines):
        temp = rng.normal(60, 3) + rng.normal(0, 1.0, n_days)
        vib = rng.normal(2.0, 0.2) + rng.normal(0, 0.15, n_days)
        pres = rng.normal(5.0, 0.2) + rng.normal(0, 0.1, n_days)
        day = int(rng.integers(15, 150))
        while day < n_days:
            mode = "bearing" if rng.random() < 0.6 else "seal"
            ramp = int(rng.integers(10, 26)) if mode == "bearing" else int(rng.integers(2, 6))
            k = np.arange(max(0, day - ramp), day)
            w = ((k - (day - ramp) + 1) / ramp) ** 2
            if mode == "bearing":
                vib[k] += 0.6 * w
                temp[k] += 3.0 * w
            else:
                pres[k] -= 0.6 * w
            failures.append((m, day, mode, ramp))
            day += int(rng.integers(60, 200))
        frames.append(pd.DataFrame({"machine": m, "day": np.arange(n_days),
                                    "temp": temp.round(2), "vib": vib.round(3), "pres": pres.round(3)}))
    return pd.concat(frames, ignore_index=True), pd.DataFrame(failures, columns=["machine", "day", "mode", "ramp"])

def add_features_and_label(df, fails, horizon=7):
    """Features use only readings up to and including the day; label = a failure in the next `horizon` days."""
    df = df.sort_values(["machine", "day"]).copy()
    g = df.groupby("machine")
    for col in ("temp", "vib", "pres"):
        df[f"{col}_7"] = g[col].transform(lambda s: s.rolling(7, min_periods=1).mean())
        df[f"{col}_28"] = g[col].transform(lambda s: s.rolling(28, min_periods=1).mean())
        df[f"{col}_trend"] = df[f"{col}_7"] - df[f"{col}_28"]
        df[f"{col}_3"] = g[col].transform(lambda s: s.rolling(3, min_periods=1).mean())
    df["pres_drop"] = df["pres_28"] - df["pres_3"]
    df["y"] = 0
    for m, d, _, _ in fails.itertuples(index=False):
        df.loc[(df.machine == m) & (df.day >= d - horizon) & (df.day < d), "y"] = 1
    return df

FEATURES = ["temp_7", "vib_7", "pres_7", "temp_trend", "vib_trend", "pres_trend", "pres_drop"]

import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

readings, fails = make_fleet()
df = add_features_and_label(readings, fails)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(df.loc[df.day < 358, FEATURES], df.loc[df.day < 358, "y"])   # final model: all labelled days

class History(BaseModel):
    machine: int
    temp: list[float] = Field(min_length=28, max_length=28)
    vib: list[float] = Field(min_length=28, max_length=28)
    pres: list[float] = Field(min_length=28, max_length=28)

app = FastAPI(title="pump-risk", version="1.0.0")

@app.post("/risk")
async def risk(h: History):          # async: Pyodide has no threads for sync endpoints
    hist = pd.DataFrame({"machine": h.machine, "day": range(28), "temp": h.temp, "vib": h.vib, "pres": h.pres})
    row = add_features_and_label(hist, fails.iloc[:0])[FEATURES].tail(1)   # the training feature code
    return {"machine": h.machine, "risk_7d": round(float(model.predict_proba(row)[0, 1]), 3),
            "model_version": app.version}

def history(m, last_day):
    r = readings[(readings.machine == m) & (readings.day > last_day - 28) & (readings.day <= last_day)]
    return {"machine": m, "temp": r.temp.tolist(), "vib": r.vib.tolist(), "pres": r.pres.tolist()}

async def main():
    f = fails[(fails["mode"] == "bearing") & (fails.day > 300)].iloc[0]
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
        for label, body in [("bearing failure in 3 days", history(int(f.machine), int(f.day) - 3)),
                            ("same machine 40 days earlier", history(int(f.machine), int(f.day) - 40))]:
            r = await c.post("/risk", json=body)
            print(f"{label:30} {r.status_code} {r.json()}")
        bad = history(0, 100); bad["vib"] = bad["vib"][:27]
        r = await c.post("/risk", json=bad)
        print(f"{'only 27 vibration values':30} {r.status_code} {r.json()['detail'][0]['msg']}")

asyncio.run(main())
bearing failure in 3 days      200 {'machine': 7, 'risk_7d': 0.074, 'model_version': '1.0.0'}
same machine 40 days earlier   200 {'machine': 7, 'risk_7d': 0.022, 'model_version': '1.0.0'}
only 27 vibration values       422 List should have at least 28 items after validation, not 27

Three days before a bearing failure, pump 7's risk is 0.074; forty days earlier it was 0.022. The numbers look small because only 5.5 % of pump-days are positive: the risk is a probability for one pump on one day, and the list is made by ranking all 60 pumps by it. A request with 27 values instead of 28 is rejected with HTTP 422 before it reaches the model.

Step 6: monitor it

Six months after launch, the utility replaces the vibration sensors of half the fleet (the even-numbered pumps) on day 330. The new sensors read 0.3 higher. Nobody tells the ML team. The script compares three worlds: no change, the new sensors as they are, and the new sensors with their offset corrected; and it watches the population stability index (PSI) of the 7-day vibration feature, week by week, against the training period (data drift).

python · try it yourself
import numpy as np
import pandas as pd

def make_fleet(seed=0, n_machines=60, n_days=365):
    """Daily sensor readings of a pump fleet with two failure modes; returns readings and failures."""
    rng = np.random.default_rng(seed)
    frames, failures = [], []
    for m in range(n_machines):
        temp = rng.normal(60, 3) + rng.normal(0, 1.0, n_days)
        vib = rng.normal(2.0, 0.2) + rng.normal(0, 0.15, n_days)
        pres = rng.normal(5.0, 0.2) + rng.normal(0, 0.1, n_days)
        day = int(rng.integers(15, 150))
        while day < n_days:
            mode = "bearing" if rng.random() < 0.6 else "seal"
            ramp = int(rng.integers(10, 26)) if mode == "bearing" else int(rng.integers(2, 6))
            k = np.arange(max(0, day - ramp), day)
            w = ((k - (day - ramp) + 1) / ramp) ** 2
            if mode == "bearing":
                vib[k] += 0.6 * w
                temp[k] += 3.0 * w
            else:
                pres[k] -= 0.6 * w
            failures.append((m, day, mode, ramp))
            day += int(rng.integers(60, 200))
        frames.append(pd.DataFrame({"machine": m, "day": np.arange(n_days),
                                    "temp": temp.round(2), "vib": vib.round(3), "pres": pres.round(3)}))
    return pd.concat(frames, ignore_index=True), pd.DataFrame(failures, columns=["machine", "day", "mode", "ramp"])

def add_features_and_label(df, fails, horizon=7):
    """Features use only readings up to and including the day; label = a failure in the next `horizon` days."""
    df = df.sort_values(["machine", "day"]).copy()
    g = df.groupby("machine")
    for col in ("temp", "vib", "pres"):
        df[f"{col}_7"] = g[col].transform(lambda s: s.rolling(7, min_periods=1).mean())
        df[f"{col}_28"] = g[col].transform(lambda s: s.rolling(28, min_periods=1).mean())
        df[f"{col}_trend"] = df[f"{col}_7"] - df[f"{col}_28"]
        df[f"{col}_3"] = g[col].transform(lambda s: s.rolling(3, min_periods=1).mean())
    df["pres_drop"] = df["pres_28"] - df["pres_3"]
    df["y"] = 0
    for m, d, _, _ in fails.itertuples(index=False):
        df.loc[(df.machine == m) & (df.day >= d - horizon) & (df.day < d), "y"] = 1
    return df

FEATURES = ["temp_7", "vib_7", "pres_7", "temp_trend", "vib_trend", "pres_trend", "pres_drop"]

def daily_top_k(df, score, k=3):
    """The k machines with the highest score on each day: the inspection list."""
    d = df.assign(score=score)
    return d.sort_values(["day", "score"], ascending=[True, False]).groupby("day").head(k)[["machine", "day"]]

def catch_rate(df, score, fails, k=3, horizon=7, lead=2):
    """Share of failures whose machine was on the inspection list 2 to 7 days before (2 days to plan the repair)."""
    lists = daily_top_k(df, score, k)
    days = set(df.day)
    inspected = set(zip(lists.machine, lists.day))
    fl = fails[fails.day - 1 >= min(days)]
    fl = fl[fl.day - 1 <= max(days)]
    hit = [any((m, t) in inspected for t in range(d - horizon, d - lead + 1)) for m, d in zip(fl.machine, fl.day)]
    return float(np.mean(hit)), len(fl), np.array(hit)

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

def psi(ref, new, bins=10):
    """Population stability index over the reference deciles."""
    edges = np.quantile(ref, np.linspace(0, 1, bins + 1))[1:-1]
    p = np.bincount(np.searchsorted(edges, ref), minlength=bins) / len(ref)
    q = np.bincount(np.searchsorted(edges, new), minlength=bins) / len(new)
    p, q = np.clip(p, 1e-4, None), np.clip(q, 1e-4, None)
    return float(np.sum((q - p) * np.log(q / p)))

base, fails = make_fleet()
new_sensor = (base.machine % 2 == 0) & (base.day >= 330)          # even machines get new sensors on day 330
print("days 330-357, 3 inspections a day")
scenarios = {"no sensor change": 0.0, "new sensors read +0.3": 0.3, "new sensors, offset corrected": 0.0}

for name, offset in scenarios.items():
    readings = base.copy()
    readings.loc[new_sensor, "vib"] += offset
    df = add_features_and_label(readings, fails)
    model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
    model.fit(df.loc[df.day < 293, FEATURES], df.loc[df.day < 293, "y"])
    live = df[(df.day >= 330) & (df.day < 358)]
    score = model.predict_proba(live[FEATURES])[:, 1]
    rate, n, _ = catch_rate(live, score, fails)
    lists = daily_top_k(live, score).merge(live[["machine", "day", "y"]], on=["machine", "day"])
    print(f"{name:30} caught {rate:.2f} of {n} failures, useful inspections {lists.y.mean():.2f}, "
          f"new-sensor machines {(lists.machine % 2 == 0).mean():.0%} of the list")
    if offset:
        ref = df.loc[df.day < 293, "vib_7"].to_numpy()
        for start in range(316, 358, 7):
            week = df.loc[(df.day >= start) & (df.day < start + 7), "vib_7"].to_numpy()
            value = psi(ref, week)
            print(f"    PSI(vib_7) days {start}-{start + 6}: {value:.3f} {'ALARM' if value > 0.2 else ''}".rstrip())
days 330-357, 3 inspections a day
no sensor change               caught 0.64 of 11 failures, useful inspections 0.56, new-sensor machines 44% of the list
new sensors read +0.3          caught 0.64 of 11 failures, useful inspections 0.51, new-sensor machines 60% of the list
    PSI(vib_7) days 316-322: 0.020
    PSI(vib_7) days 323-329: 0.056
    PSI(vib_7) days 330-336: 0.208 ALARM
    PSI(vib_7) days 337-343: 0.605 ALARM
    PSI(vib_7) days 344-350: 0.735 ALARM
    PSI(vib_7) days 351-357: 0.701 ALARM
new sensors, offset corrected  caught 0.64 of 11 failures, useful inspections 0.56, new-sensor machines 44% of the list

The monitor raises an alarm in the first week after the change (PSI 0.208 above the usual 0.2 threshold, rising to 0.735), while the effect on the decision is modest: the same 0.64 of 11 failures are caught, but useful inspections fall from 0.56 to 0.51 and the new-sensor pumps take 60 % of the list instead of 44 %. The step looks like a "rising vibration trend" on every new-sensor pump for up to four weeks (until the 28-day mean has caught up), which is what tilts the list; the failing pumps in this period still stand out enough to stay on it, but with only 11 failures that is luck as much as robustness. An alarm is therefore a reason to investigate, not an automatic retraining: here the right fix is to correct the offset at the source, which restores the original behaviour exactly. Without the monitor, nobody would have known the list had tilted. The lab shows the same pattern for a sudden shift of half a standard deviation:

0.00.40.8−4−2024densityFeature x, day 60referenceliveDay 60: PSI = 0.467threshold 0.20: ALARMlive mean 0.54 (true 0.50)model error today 0.115drift starts on day 31PSI: <0.1 stable, >0.25 major shift0.00.20.40102030405060dayPSI per daydrift startsstatisticthresholdonsetfalse alarmalarm

With these settings PSI alarms on day 31, the first day of the shift, and never before. Now choose no drift and lower the window size n to 50: PSI raises false alarms on 33 of the 60 days although nothing changed. Small windows make PSI noisy, which is why the script above uses weekly windows of 420 values (concept drift detection covers the label-side monitors).

The write-up

text
PROJECT WRITE-UP: pump inspection list                                   v1.0
1. Problem      choose 3 of 60 pumps a day to inspect; failure within 7 days; 2 days needed to plan
2. Success      >= 0.50 of failures caught 2-7 days ahead; >= 0.15 above the vibration rule
3. Data         365 days x 60 pumps, 3 daily sensors, 171 failures (97 bearing, 74 seal); SYNTHETIC
4. Split        time: train 0-232 | gap | val 240-299 | test 300-357 (used once); refit on 0-292
5. Baselines    random 0.30, vibration rule 0.37 (validation, 27 failures)
6. Model        logistic regression on 7 rolling/trend features (tied with boosting at 0.56; simpler)
7. Test result  0.62 of 26 caught (95 % bootstrap 0.42-0.81); rule 0.38. Criteria met on the point
                estimate; the lower bound is below 0.50
8. Errors       bearing 0.87, seal 0.27; seal failures with 2 days of warning: never caught
9. Shipping     nightly list (batch) + /risk API for one pump, same feature code as training
10. Limits      synthetic data; 26 test failures; daily data cannot see fast seal failures;
                work-order labels in reality are late and noisy
11. Next steps  hourly pressure alarm for seals; monitor PSI per sensor and the list mix;
                collect 12 more months before tuning further

Extensions

  1. Add a survival-style target (days until failure) and compare the ranking (regression metrics).
  2. Give pumps different importance (a hospital district counts more) and rank by expected cost instead of risk.
  3. Replace the fixed budget by a threshold chosen on validation and compare the number of call-outs (threshold and training-only rules).
  4. Track the experiments with MLflow and register the model with its metrics (MLflow tracking, model registry).
  5. Normalise each sensor by the pump's own history (a per-pump z-score) and check whether the vibration rule becomes competitive.

Part B: your own capstone

Choosing a problem

A good capstone problem has four properties:

  1. A decision. Someone does something differently because of the prediction. "Predict X" without a user is an exercise, not a project.
  2. Data you are allowed to use. A public data set with a clear licence, your own measurements, or a generator you can defend. No personal data without consent; no scraping against a site's terms (privacy, consent and licensing, public, licensed and synthetic data).
  3. An honest test. You can hold back data that imitates the future use: a later period, new users, a new site.
  4. A size that fits. Four to six weeks at a few hours a week. If the first baseline takes more than a week, cut the scope.

Ideas that fit: energy or water demand forecasting for a building, defect detection on photos you take yourself, a classifier for your own documents or emails (kept private), sports or game outcome prediction, a recommender for a small catalogue, anomaly detection on server logs, a retrieval assistant over a set of manuals you are allowed to use.

The proposal (one page, before any code)

text
CAPSTONE PROPOSAL: <title>
User and decision      who acts on the prediction, and how
Input at decision time what is known when the prediction is made
Target                 what is predicted, and when the truth becomes known
Data                   source, licence or consent, size, period, known problems
Split                  how the test set imitates real use
Metric and criteria    the metric, the target value, the baseline it must beat
Deliverable            report / saved pipeline + loader / API / batch job / demo
Risks                  what could make the project fail, and the fallback
Milestones             weeks 1-6 (see below)

Milestones

Week Milestone Evidence
1 proposal; data obtained; first look proposal page; a quality report (project 4)
2 split fixed; baseline ladder experiment log with rungs 1–3 (workflow)
3–4 improvements on validation, one change at a time log entries; a short note per idea, kept or dropped
5 test once; error analysis the final number with an interval; a slice table
6 ship and write up the artefact or service; the write-up; a README that reproduces the main number

Rubric

Score yourself (or ask a peer) from 0 to 2 on each line; 16 or more of 20 is a strong capstone.

Criterion 0 1 2
Framing no user or decision user named, metric loosely tied to the decision decision, costs of errors and metric fit together
Data unknown source or licence source and licence stated plus quality checks and who is in the data
Split random split of dependent rows right split type plus gap or grouping where needed, sizes stated
Baseline none one the ladder: no skill, simple, strong default
Leakage preprocessing fitted on all data pipeline used plus input-at-decision-time checked for every feature
Test discipline test used for choices test used once plus an interval and an honest comparison with validation
Error analysis none overall confusion matrix slices with sizes, and a cause for the worst
Shipping notebook only saved pipeline and loader service or batch job with validation and a monitoring plan
Reproducibility cannot be rerun seeds and versions one command reproduces the main number
Write-up missing complete template plus limitations a sceptical reader would accept

The Presenting Your Projects lesson shows how to turn the result into a portfolio piece.

Test yourself

Why does the pump project leave a 7-day gap between the training and validation periods?

  1. To save memory
  2. Training labels look 7 days ahead, so without a gap the last training rows would carry information about failures in the validation period
  3. Because sensors are off during the gap
  4. To make the test set larger

Logistic regression and gradient boosting both caught 0.56 of the validation failures. Which should be chosen, and why?

  1. Gradient boosting, because it is more powerful
  2. Logistic regression: equal on validation, simpler and easier to explain to the planners
  3. Both, averaged
  4. Neither; test both on the test set

Seal failures with only 2 days of warning were never caught. What is the right response?

  1. Tune the model harder
  2. Recognise a data limitation: daily readings cannot show a drop that starts 2 days before the failure on a list made 2 days ahead; a faster data source (hourly pressure alarms) is needed
  3. Remove seal failures from the test set
  4. Lower the lead time to zero in the metric

After the sensor change, PSI on vibration rose to 0.735 but the share of failures caught stayed at 0.64. What does this show?

  1. PSI is broken
  2. An input-drift alarm is a reason to investigate; here the decision was only mildly affected (more new-sensor pumps on the list, fewer useful inspections), and correcting the offset at the source was the fix
  3. The model must be retrained every time PSI exceeds 0.2
  4. Drift never matters for trend features