TExcelTAD
Home › Machine Learning › The ML Workflow

The ML Workflow

Training a model is only one step of a machine-learning project, and often not the longest. Practitioners follow a fairly standard workflow, and knowing it helps you avoid the classic mistakes (like evaluating on data the model has already seen).

The steps

# Step Key questions
1 Define the problem What exactly should be predicted? How will the prediction be used? What counts as success?
2 Collect data Which examples and features are available? Are labels reliable?
3 Explore the data Distributions, missing values, outliers, correlations
4 Prepare the data Clean, encode categories, scale, create features
5 Split Hold out a test set before any modelling decisions
6 Baseline What does a trivial model achieve?
7 Train and compare models Cross-validate several candidates
8 Tune Grid search on the best candidates
9 Evaluate once on the test set Is the final score good enough? Which errors remain?
10 Deploy and monitor Save the model, serve predictions, watch for drift

The arrows aren't strictly one-way: exploring the errors in step 9 often sends you back to step 4 for better features. What is strict is that the test set stays untouched until the end.

Let's walk through the steps on the built-in diabetes data set: 442 patients, 10 measurements (age, BMI, blood pressure, six blood serum values), and a number measuring disease progression one year later. The goal is to predict that number.

Explore

python · try it yourself
import pandas as pd
from sklearn.datasets import load_diabetes

data = load_diabetes(as_frame=True)
df = data.frame
print(df.shape)
print(df.head(3).round(3))
print()
print("missing values:", int(df.isna().sum().sum()))
print("target range:", df["target"].min(), "to", df["target"].max())
print()
print("correlation with target:")
print(df.corr()["target"].drop("target").sort_values(ascending=False).round(2))
(442, 11)
     age    sex    bmi     bp     s1     s2     s3     s4     s5     s6  target
0  0.038  0.051  0.062  0.022 -0.044 -0.035 -0.043 -0.003  0.020 -0.018   151.0
1 -0.002 -0.045 -0.051 -0.026 -0.008 -0.019  0.074 -0.039 -0.068 -0.092    75.0
2  0.085  0.051  0.044 -0.006 -0.046 -0.034 -0.032 -0.003  0.003 -0.026   141.0

missing values: 0
target range: 25.0 to 346.0

correlation with target:
bmi    0.59
s5     0.57
bp     0.44
s4     0.43
s6     0.38
s1     0.21
age    0.19
s2     0.17
sex    0.04
s3    -0.39
Name: target, dtype: float64

The features in this data set are already centred and scaled (that's why the values are small). BMI and s5 (a serum measurement) are the features most correlated with the target.

Split, then set a baseline

Split first. Then ask: how good is a model that ignores the features and always predicts the training mean? Any real model must beat that.

python · try it yourself
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
mae = mean_absolute_error(y_train, baseline.predict(X_train))
print(f"baseline always predicts {baseline.predict(X_test[:1])[0]:.1f}")
print(f"baseline MAE on training data: {mae:.1f}")
baseline always predicts 153.7
baseline MAE on training data: 66.4

MAE (mean absolute error) is the average size of the errors in the target's own units — the Regression Metrics lesson covers it in detail.

Compare candidates with cross validation

Next we try a few different model types on the training set only, using 5-fold cross validation:

python · try it yourself
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.tree import DecisionTreeRegressor
from sklearn.neighbors import KNeighborsRegressor

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

candidates = {
    "baseline (mean)": DummyRegressor(),
    "linear regression": LinearRegression(),
    "ridge": Ridge(alpha=0.1),
    "tree (depth 3)": DecisionTreeRegressor(max_depth=3, random_state=0),
    "knn (k=15)": KNeighborsRegressor(n_neighbors=15),
}
for name, model in candidates.items():
    mae = -cross_val_score(model, X_train, y_train, cv=5, scoring="neg_mean_absolute_error").mean()
    print(f"{name:18} CV MAE = {mae:5.1f}")
baseline (mean)    CV MAE =  66.8
linear regression  CV MAE =  45.5
ridge              CV MAE =  45.5
tree (depth 3)     CV MAE =  52.5
knn (k=15)         CV MAE =  48.0

scikit-learn's scorers follow the rule "higher is better", so error metrics are returned negated (neg_mean_absolute_error); we flip the sign back for printing.

Final evaluation

Linear regression and ridge tie, and both clearly beat the baseline. We pick ridge (its small penalty makes it a little more robust, see Regularization), fit it on the whole training set and evaluate it once on the test set:

python · try it yourself
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, r2_score

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

final = Ridge(alpha=0.1).fit(X_train, y_train)
pred = final.predict(X_test)
print(f"test MAE: {mean_absolute_error(y_test, pred):.1f}")
print(f"test R^2: {r2_score(y_test, pred):.3f}")
print("first five predictions:", pred[:5].round(0))
print("first five true values:", y_test[:5])
test MAE: 43.0
test R^2: 0.461
first five predictions: [144. 178. 143. 287. 126.]
first five true values: [219.  70. 202. 230. 111.]

An R² well below 1 tells us the 10 measurements explain only part of the disease progression — useful, but far from perfect. That is a realistic result: many real problems have a lot of irreducible noise.

Common pitfalls

  • Data leakage: information from the test set (or from the future) sneaks into training — for example, scaling with statistics computed on all data, or a feature that is only known after the event you're predicting. Pipelines (later lesson) prevent the first kind.
  • Tuning on the test set: repeatedly checking the test score turns it into training data.
  • Skipping the baseline: a "90 % accurate" model is worthless if always guessing the majority class gives 92 %.
  • Optimising the wrong metric: accuracy on imbalanced data, average error when large errors are what really hurt.

Test yourself

When should the test set be split off?

  1. After tuning hyperparameters
  2. Before any modelling decisions are made
  3. Only when the model performs badly
  4. It doesn't matter

What is the purpose of a baseline model such as DummyRegressor?

  1. It is the final model
  2. It shows the score a trivial strategy achieves, which real models must beat
  3. It cleans the data
  4. It speeds up training

Why does scikit-learn report neg_mean_absolute_error (a negative number)?

  1. Because errors are always negative
  2. Its scorers follow 'higher is better', so error metrics are negated
  3. It's a bug
  4. To save memory