Module 1 of 6 · 45 minutes

The machine learning workflow

Good machine learning starts with a good question. This module frames problems properly and gets your first model running in minutes.

By · Last updated

Learning objectives

  • Frame a problem with a decision, target, available data and success measure
  • Distinguish classification from regression
  • Outline the end-to-end ML workflow
  • Use scikit-learn's create–fit–predict pattern
  • Compare a model against a baseline
  • Explore the target before modelling
  • Explain what still needs human judgement when AI writes ML code
Before you start

This course uses Python, pandas and scikit-learn. Every code block is a live cell: press Run and it runs in your browser, with nothing to install (the first run on each page takes a little longer while the libraries load). If you're new to Python, take Python for AI and Data Quality & Preparation first. The non-mathematical background is in How AI and LLMs Work.

1.1 Frame the problem first

Most failed ML projects fail at the start: the wrong question, the wrong target, or no clear way to measure success. Before writing code, answer:

  • What decision will the model support? e.g. "which customers should the retention team call this week?"
  • What exactly will it predict? A category (classification) or a number (regression)?
  • What data will be available at prediction time? (No peeking into the future.)
  • How will success be measured — technically and in business terms?
  • What's the simplest baseline? A rule of thumb or "always predict the average".

A worked example

A subscription business says: "use AI to reduce churn". That's a wish, not a problem a model can solve. Framed properly it becomes:

QuestionAnswer for the churn project
DecisionWhich 50 customers the retention team phones each week
PredictionWill this customer cancel in the next 30 days? (classification)
Data at prediction timeTenure, spend, support tickets, promotions — all known today. Not "cancellation reason", which only exists after the event.
SuccessMore customers saved per 50 calls than the current rule ("call anyone with 3+ tickets")
BaselineThat current rule

Notice that the baseline is a business rule people already use. If the model can't beat it, the project isn't worth deploying — however clever the model.

1.2 Classification or regression?

Classification — predict a category

Will this customer churn (yes/no)? Is this transaction fraudulent? Which product category is this?

Regression — predict a number

What will this customer spend next year? How many units will we sell? How long will delivery take?

1.3 The machine learning workflow

  1. Frame the problem and success measure.
  2. Get and prepare data (cleaning, features).
  3. Split into training and test sets.
  4. Build a baseline.
  5. Train models and compare them with cross-validation.
  6. Evaluate the chosen model once on the test set.
  7. Interpret, check fairness, document.
  8. Deploy, monitor and retrain when needed.
Frame theproblemPreparedataSplittrain / testBuild abaselineTrain &cross-validateTest onceInterpret &documentDeploy &monitorMonitoring feeds back: new data, new questions, retraining
The end-to-end machine learning workflow. Most of the effort sits outside the 'train' box.

1.4 scikit-learn's simple pattern

Every scikit-learn model follows the same three steps — which makes it easy to try many models:

The pattern (not runnable on its own)model = SomeModel(settings)     # 1. create
model.fit(X_train, y_train)     # 2. learn from training data
predictions = model.predict(X_test)   # 3. predict on new data

X holds the features (inputs, one row per example); y holds the target (what you want to predict).

1.5 The practice dataset

You'll use a synthetic customer dataset with a hidden pattern built in, so you can see whether models find it. Press Run:

Python · practice data: synthetic customersimport numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
    "tenure_months":   rng.integers(1, 60, n),
    "monthly_spend":   rng.normal(40, 15, n).clip(5, 120).round(2),
    "support_tickets": rng.poisson(1.2, n),
    "on_promo":        rng.integers(0, 2, n),
    "region":          rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
         - 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
                             + rng.normal(0, 40, n)).round(2)
print(customers.head())
print("Churn rate:", customers["churned"].mean().round(3))

1.6 Your first model in ten lines

Python · first classifier vs a baselinefrom sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier

features = ["tenure_months", "monthly_spend", "support_tickets", "on_promo"]
X, y = customers[features], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
print("Baseline accuracy:", round(baseline.score(X_test, y_test), 3))
print("Model accuracy:   ", round(model.score(X_test, y_test), 3))

Always compare with a baseline. A model that can't beat "always predict the most common answer" isn't learning anything useful.

Why split the data at all? Because a model is judged on customers it has never seen. The 80% training set is for learning; the 20% test set stands in for tomorrow's customers. stratify=y keeps the churn rate the same in both parts, and random_state=0 makes the split repeatable.

1.7 Look before you model

Ten minutes of simple exploration often tells you what a model will find — and catches data problems before they become model problems. Here is churn rate by tenure band and by number of support tickets:

Python · explore the targetbands = pd.cut(customers["tenure_months"], [0, 6, 12, 24, 60], labels=["0-6", "7-12", "13-24", "25+"])
print(customers.groupby(bands, observed=True)["churned"].agg(["mean", "count"]).round(2))

tickets = customers["support_tickets"].clip(upper=4)        # group 4 or more together
print(customers.groupby(tickets)["churned"].agg(["mean", "count"]).round(2))

Churn falls steadily with tenure and climbs with tickets (the 4+ group is small, so its rate is noisy) — the hidden pattern, visible in two lines of pandas. If a model later claimed that tenure didn't matter, you'd know to be suspicious. Exploration gives you expectations to check the model against.

1.8 Machine learning when AI can write the code

AI coding assistants can now write a scikit-learn script like the one above in seconds. That shifts where your value lies, but it doesn't remove the need to understand what you're running. An assistant will happily produce code that scores 0.99 because the target leaked into the features, or that tunes against the test set. The parts that still need a person are the parts this course concentrates on:

  • Framing — choosing the decision, the target and the success measure.
  • Judging the evidence — is there a baseline, is the test set untouched, is the metric the right one?
  • Accountability — deciding whether a model is good enough, and fair enough, to act on.
Exercise: beat the model with a rule?

The retention team's current rule is "flag anyone with 3 or more support tickets". Using X_test and y_test, work out the rule's accuracy and compare it with the model and the baseline. Then try adding "or tenure under 6 months".

Your turnrule = (X_test["support_tickets"] >= 3).astype(int)    # 1 = flagged as likely to churn

# Compare rule with y_test, then press Run
Show a solution
rule = (X_test["support_tickets"] >= 3).astype(int)
print("Rule accuracy:      ", round((rule == y_test).mean(), 3))

rule2 = ((X_test["support_tickets"] >= 3) | (X_test["tenure_months"] < 6)).astype(int)
print("Rule + tenure:      ", round((rule2 == y_test).mean(), 3))
print("Model accuracy:     ", round(model.score(X_test, y_test), 3))
# A good rule of thumb is a serious baseline. The model has to earn its place.

Key takeaways

  • Start with the decision the model supports and how success is measured.
  • Classification predicts categories; regression predicts numbers.
  • Split, baseline, train, compare, test once, interpret, deploy, monitor.
  • Every scikit-learn model: create, fit, predict.
  • Always beat a baseline — including the rule of thumb people already use.
  • Explore first: simple group-bys set expectations to check the model against.
  • AI can write the code; framing, evidence and accountability stay with you.