The Project Workflow: from Question to Write-Up
Every project in this course is built with the same eight steps: frame, data, split, baseline, model, test once, error analysis, ship. This lesson turns them into a checklist you can copy into a new project, gives you two small reusable tools (an experiment log and a slice report), and ends with the write-up template that every project fills in. Use it as the reference page while you work through the projects; each step names the lesson that teaches it in depth.
Step 1: frame the problem
Most failed ML projects fail here, before any code: the model predicts something nobody can act on, or optimises a metric that does not match what the user cares about. Answer these questions in writing:
| Question | Example (fraud detection) |
|---|---|
| Who uses the prediction, and what do they decide with it? | an analyst team reviews flagged payments; a flag delays the payment |
| What is the input, at the moment of the decision? | the payment and the card's history up to that payment, nothing later |
| What is the target, and when is it known? | "confirmed fraud" from chargebacks, known weeks later |
| What does each kind of error cost? | a missed fraud loses the amount; a false flag costs review time and an annoyed customer |
| Constraints | answer within 50 ms, explainable to the customer, personal data rules |
| Metric and success criteria | recall at 200 alerts per day at least 0.6, measured on the last month, never seen in training |
| What is the non-ML baseline? | the current rule "amount over 1,000 abroad" |
The input row is the one that catches leakage early: if a feature is not available when the decision is made, it must not be in the training data (leakage rules, what is ML). The success criteria must be written before the first result, so that the result cannot shape them.
Step 2: understand the data
Before modelling, look: types, ranges, missing values, duplicates, outliers, label quality and class balance (dataset inspection, quality report). Write down where the data came from, under which licence or consent, and who is in it (privacy, consent and licensing). Project 4, the dataset quality analyzer, builds a tool for this step.
Step 3: split before you learn anything
Decide how the model will be used, and split the data to imitate it: randomly (stratified) for independent rows, by group when rows of the same customer, patient or image source must not appear on both sides, and by time when the model predicts the future (split strategies, stratified and group CV, time-series backtesting). Lock the test set away. Every preprocessing step that learns from data (scaling, imputation, encoding, feature selection) is fitted on the training part only, inside a pipeline (pipelines).
Step 4: a baseline ladder
Train the simplest models first and keep their scores in the report:
- No skill: predict the majority class, the mean, or "same as last week".
- Simple skill: a scaled linear or logistic model, or the current business rule.
- Strong default: a random forest or gradient boosting for tables, a pretrained model for images and text.
A complex model is only worth its cost if it beats rung 3 by more than the noise in the validation score. The Ten Principles lesson shows the ladder on one data set; here is a version that also writes an experiment log: every run gets the data's fingerprint, the model's parameters, the seed and the score, so any number in the report can be traced back to how it was made (experiment tracking).
import hashlib
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import balanced_accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
SEED = 0
X, y = make_classification(n_samples=3000, n_features=12, n_informative=6, weights=[0.8], random_state=SEED)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=SEED)
X_tr, X_val, y_tr, y_val = train_test_split(X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=SEED)
data_id = hashlib.sha256(X_tr.tobytes() + y_tr.tobytes()).hexdigest()[:12]
ladder = {
"1 majority class": DummyClassifier(strategy="most_frequent"),
"2 logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
"3 gradient boosting": HistGradientBoostingClassifier(random_state=SEED),
}
log = []
for name, model in ladder.items():
model.fit(X_tr, y_tr)
log.append({"run": name, "model": type(model).__name__, "data": data_id,
"seed": SEED, "n_train": len(y_tr),
"val_bal_acc": round(balanced_accuracy_score(y_val, model.predict(X_val)), 3)})
print(pd.DataFrame(log).to_string(index=False))
print(f"\ntrain {len(y_tr)}, validation {len(y_val)}, test {len(y_test)} rows (test not used yet)") run model data seed n_train val_bal_acc
1 majority class DummyClassifier b364a9f08096 0 1800 0.500
2 logistic regression Pipeline b364a9f08096 0 1800 0.804
3 gradient boosting HistGradientBoostingClassifier b364a9f08096 0 1800 0.874
train 1800, validation 600, test 600 rows (test not used yet)
Balanced accuracy is used because the classes are 80/20: plain accuracy would give the do-nothing model 0.8 and make it look useful (classification metrics). The data fingerprint is the same in every row, so the three scores are comparable; if someone regenerates the data differently, the fingerprint changes and the log shows it. In a real project the log goes to a file or to MLflow (MLflow tracking), not to the screen.
Step 5: improve on validation data
Tune, engineer features and try other models with cross-validation or the validation set, never the test set (grid and random search, nested cross-validation). Change one thing at a time and log each run. Stop when the gains are smaller than the run-to-run noise (repeat a run with another seed to measure it), or when the success criteria are met.
Step 6: test once
Fit the chosen pipeline on train plus validation, evaluate it once on the test set, and report that number with its sample size and, ideally, a confidence interval (a bootstrap of the test rows is enough). If the test score is disappointing, the honest move is to report it and explain it, not to tune again and re-test: a test set used twice has become a validation set (external validation).
Step 7: error analysis
An overall score hides where a model fails. Group the errors: by a feature range, a category, a data source, a time period, an object size or a text phenomenon (error analysis). The slice that fails most tells you what to fix: more data of that kind, a better feature, a different threshold, or a sentence in the limitations section. A small reusable slice report:
import numpy as np
import pandas as pd
def slice_report(df, slice_col, y_col="y", pred_col="pred", min_n=30):
"""Error rate per slice, with its size and a rough 95 % interval; small slices are marked."""
g = df.assign(err=(df[y_col] != df[pred_col]).astype(int)).groupby(slice_col)["err"]
out = pd.DataFrame({"n": g.size(), "error_rate": g.mean()})
half = 1.96 * np.sqrt(out.error_rate * (1 - out.error_rate) / out.n)
out["interval"] = [f"{max(0, e - h):.2f}-{min(1, e + h):.2f}" for e, h in zip(out.error_rate, half)]
out["note"] = np.where(out.n < min_n, "too small to judge", "")
return out.round(3).sort_values("error_rate", ascending=False)
rng = np.random.default_rng(1)
n = 1200
region = rng.choice(["north", "south", "east", "west", "islands"], n, p=[0.3, 0.3, 0.2, 0.18, 0.02])
y = rng.integers(0, 2, n)
p_wrong = np.select([region == "east", region == "islands"], [0.25, 0.30], default=0.10)
pred = np.where(rng.random(n) < p_wrong, 1 - y, y)
df = pd.DataFrame({"region": region, "y": y, "pred": pred})
print(f"overall error rate {np.mean(y != pred):.3f} on {n} rows\n")
print(slice_report(df, "region").to_string())overall error rate 0.152 on 1200 rows
n error_rate interval note
region
east 234 0.299 0.24-0.36
west 236 0.144 0.10-0.19
islands 24 0.125 0.00-0.26 too small to judge
north 351 0.117 0.08-0.15
south 355 0.099 0.07-0.13
The overall error of 0.152 hides a region with twice that rate: "east" (0.299, interval 0.24–0.36) clearly fails more often than the rest. "islands" was generated with the highest error probability of all (0.30), yet with 24 rows its measured rate is 0.125, below the overall rate, and its interval runs from 0.00 to 0.26: the data cannot say whether the slice is good or bad, which is itself a finding for the limitations section. Always print the slice size next to its score.
Step 8: ship and write up
"Ship" means whatever the user needs: a saved pipeline and a loader program, an API, a batch job that writes a file, or a report with a decision (saving models, FastAPI, batch vs real time). Whatever form it takes, it travels with a write-up. The projects use this template; copy it into your own work:
PROJECT WRITE-UP: <name> date, author, version
1. Problem user, decision, input at decision time, target, cost of each error
2. Success criteria fixed before results (metric, target, measured on)
3. Data source, licence/consent, rows and period, who is in it, known quality issues
4. Split how and why (random / group / time), sizes, what was fitted on what
5. Baselines no-skill, simple, strong default: scores on validation
6. Model what was chosen and why; main settings; experiment log reference
7. Test result the one final number, sample size, interval; criteria met or not
8. Errors the worst slices with sizes; examples of typical failures
9. Shipping artefact or service, how to call it, how it is monitored
10. Limits what the evaluation cannot show; where the model must not be used
11. Next steps ranked by expected valueSection 10 is the one most often left empty and the one reviewers read first. A model card (governance) is the same information in the form a model registry expects. The Presenting Your Projects lesson shows how to turn a write-up into a portfolio piece.
The ten principles, as a checklist
The curriculum ends with ten study principles (explained here). Each one is a step of the workflow:
| Principle | Where it lives in the workflow |
|---|---|
| Start with data, not model complexity | step 2, and every error analysis that ends in "get more data of this kind" |
| Understand the problem before selecting an algorithm | step 1 |
| Build a simple baseline first | step 4 |
| Prevent data leakage | steps 1 (input at decision time) and 3 (fit on training data only) |
| Choose preparation methods based on the data | steps 2–3 (preparation by data type) |
| Keep experiments reproducible | step 4's log: data fingerprint, seed, parameters |
| Evaluate on genuinely unseen data | step 6 |
| Monitor deployed systems | step 8 (monitoring) |
| Learn the mechanics by implementing them | the from-scratch parts of each project |
| Treat ML as a complete engineering lifecycle | the whole loop, and project 15 |
Practice
- Frame the problem "predict which students will fail the course" with the table of step 1. What is the input at decision time if the prediction is made in week 3 of a 12-week course?
Answer
User: a tutor deciding whom to contact. Input: only what is known by week 3 (enrolment data, prior grades, attendance and assignment marks of weeks 1–3), not the final exam or later attendance. Target: fail at the end of the course, known only after the exam. Errors: a missed student loses support; a false alarm costs a tutor's time and may worry the student. Constraints: explainable, fair across groups, personal data of minors or students. Metric: recall at the number of students the tutors can contact. Project 2, student performance, works this out.
- In the experiment log, the majority-class model has balanced accuracy 0.500. What would its plain accuracy be on this validation set, and why is that number misleading?
Answer
About 0.8, the share of the majority class (the generator was set to 80/20). It looks like a decent score but the model never finds a single positive. Balanced accuracy averages the recall of both classes, so a model that ignores one class scores 0.5.
- A colleague evaluates on the test set, adds a feature, evaluates again, and reports the better number. What went wrong, and what should the report say now?
Answer
The test set was used for a modelling decision, so the second test score is optimistic: it was chosen because it was higher. The report should say so, and if possible the final number should come from fresh data (a new time period or a new sample). Next time, compare the two versions on validation data.
Test yourself
Which question in the framing table is most useful for catching leakage early?
- Who uses the prediction?
- What is the input at the moment of the decision?
- What are the latency constraints?
- What is the non-ML baseline?
In the slice report, why is the islands slice marked 'too small to judge' although its error rate (0.125) is below the overall rate?
- Its interval (0.00-0.26) is so wide that the true error could be far below or above the overall rate
- Its error rate is too low
- It has no positive labels
- Slices must have exactly 30 rows
Why does the experiment log store a fingerprint of the training data?
- To compress the data
- So that scores from runs on different data are not compared as if they were the same
- Because scikit-learn requires it
- To encrypt the data
The test score is below the success criterion. What is the honest next step?
- Tune on the test set until the criterion is met
- Report the score and explain it; any new attempt is compared on validation data and tested on fresh data
- Lower the criterion
- Drop the hardest test rows