Python Master Course V2 — 131. Machine Learning Workflows, Splits and Baselines
Purpose and learning outcomes
Before choosing an algorithm, decide what a successful prediction means and what evidence would convince you. This lesson builds a small species-classification experiment with the bundled iris measurements. Its most important product is an honest evaluation protocol. A powerful model cannot repair a split that secretly lets it see the future or recognize an already-seen subject.
- Distinguish supervised and unsupervised learning tasks
- Split data according to the unit of observation and deployment question
- Fit a dummy baseline and separate training, validation and test roles
Prerequisites: 121–130: data and statistics; scikit-learn is introduced here.
Environment and run order
Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.
Shell
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt
Understand the model and the evidence
Learning tasks and the observation unit
Supervised learning uses examples paired with a target: a category for classification or a number for regression. Unsupervised learning searches for structure without that target, as in clustering. Here one row represents one flower, four columns are measurements, and y is a species code. The row is the observation unit, but independence is a scientific assumption. Ten photos of the same flower are not ten independent flowers; recording a row does not make it an independent case.
Three datasets, three different jobs
Training data estimates model parameters. Validation data supports choices such as which model family or threshold to use. Test data estimates the performance of the procedure after those choices are fixed. Splitting twice gives approximately 60% training, 20% validation and 20% test. The second split takes 25% of the remaining 80%, which is 20% of the original total. Validation is allowed to influence decisions; test results must not quietly become another tuning signal.
A baseline is a meaningful opponent
A DummyClassifier ignores the predictive features and follows a simple rule. The most-frequent strategy always chooses the largest training class. It answers whether a more complicated system improves on knowing only training frequencies. Accuracy is the fraction of correct predictions; balanced accuracy averages recall across classes. In a balanced toy dataset they can agree, while an imbalanced dataset can make ordinary accuracy deceptively reassuring.
Choose the split to match deployment
A stratified random split approximately preserves class proportions and is reasonable here because we treat observations as independent. If the deployment question concerns new customers, put every row from one customer in only one partition. If it concerns future days, train on earlier days and validate on later days. Stratification does not solve either dependency. A random seed fixes this example’s sampling choices; it cannot certify independence or guarantee identical training across software versions.
Incremental worked example
1. Load and partition the examples
The dataset loader returns local arrays. We split row indices rather than immediately splitting features so that we can audit membership. No model is fitted, no mean is estimated, and no feature is selected before reserving test rows.
Python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score
X, y = load_iris(return_X_y=True)
rows = np.arange(len(y))
trainval, test = train_test_split(
rows, test_size=0.20, stratify=y, random_state=31)
train, valid = train_test_split(
trainval, test_size=0.25, stratify=y[trainval], random_state=32)
assert not (set(train) & set(valid) or set(train) & set(test)
or set(valid) & set(test))
assert len(train) + len(valid) + len(test) == len(y)
print(X.shape, len(train), len(valid), len(test))
2. Fit the baseline and inspect validation
fit learns the most common training label. predict applies that learned rule to new rows. The printed labels confirm that this strategy is constant. This lesson evaluates only the declared baseline on test; later candidate comparisons must use validation first.
Python
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X[train], y[train])
valid_pred = baseline.predict(X[valid])
print("validation labels", np.unique(valid_pred))
print("validation accuracy", accuracy_score(y[valid], valid_pred))
print("validation balanced accuracy",
balanced_accuracy_score(y[valid], valid_pred))
# The baseline rule is now fixed; this is its final evaluation.
test_pred = baseline.predict(X[test])
print("baseline test accuracy", accuracy_score(y[test], test_pred))
Expected output / interpretation
(150, 4) 90 30 30
The most-frequent predictions contain one label.
With these balanced partitions, both baseline accuracies are 1/3.
This establishes a reference, not a useful species classifier.
Guided lab and acceptance criteria
- Write a four-sentence experiment card: input available at prediction time, target, unit of observation, and intended new cases. State that the toy exercise assumes independent flowers and does not validate a production botany system.
- Add counts for all three classes in each partition. Verify that their sums match partition sizes. Save the index arrays locally if you will continue this exact experiment in another file; do not recreate a favorable split after seeing a score.
- Compare most_frequent with a stratified DummyClassifier seeded at 31 on validation. The latter samples labels using training class proportions. Run several seeds for learning purposes and describe variability instead of selecting the luckiest seed.
- Submit the runnable file, split audit, baseline metric, and one paragraph describing when this split would be invalid. Acceptance requires disjoint membership and an explicit boundary between model selection and final evaluation, not an impressive numerical score.
Common mistakes and repairs
- Treating the test set as a scoreboard during development: reserve it until the procedure is fixed, and obtain a genuinely new holdout if extensive test-driven tuning has occurred.
- Using an identifier as a predictive feature: check whether it encodes a subject, date, or label-generation process that will not generalize. The row indices here audit membership and never enter X.
- Confusing a dataset loader with a remote fetch: load_iris is bundled. Keep the lesson runnable offline after package installation rather than introducing an undeclared download.
Questions that test understanding
Why not train and evaluate on all 150 rows?
Training performance measures how well the rule fits examples it has already observed. It cannot estimate success on genuinely new flowers. Separating rows creates an opportunity to test generalization, although it is only valid when those rows resemble the deployment cases and are sufficiently independent.
Does stratification guarantee a fair evaluation?
No. It preserves approximate label proportions, which helps avoid a tiny partition losing a class. It says nothing about repeated subjects, chronology, selection bias, measurement quality, or leakage. Those require decisions based on how the observations were produced.
Can an unsupervised method leak information?
Yes. A scaler or clustering representation fitted using held-out inputs can learn their distribution even without targets. If the intended evaluation concerns new unseen cases, fit the representation on the training partition and apply it to held-out rows.
Why use validation when the dummy model has nothing to tune?
The baseline introduces the same workflow future candidates will use. It also allows metric and protocol checks before final evaluation. If only one fully prespecified baseline were being assessed, a training/test split could suffice; validation becomes important when making comparative decisions.
What does one-third accuracy tell us?
For this balanced three-class toy dataset, a constant guess is correct for about one class out of three. A candidate should beat that reference on comparable held-out rows. The reference would change if class prevalence changed, so report the dataset and class counts beside the metric.
What should be frozen before opening the test set?
Freeze the features, data-quality rules, preprocessing, model family, hyperparameters, decision threshold, primary metric, and evaluation population. Otherwise test observations can influence the procedure indirectly even when fit is never called on test rows.
Exercises with worked solutions
Exercise 1: Audit class proportions
Reveal the worked solution and reasoning
Use bincount because labels are consecutive nonnegative integers. Counts expose empty or unexpectedly imbalanced partitions; normalize by each partition size to compare proportions rather than raw sizes.
Python
for name, ids in [("train", train), ("valid", valid), ("test", test)]:
counts = np.bincount(y[ids], minlength=3)
print(name, counts.tolist(), (counts / len(ids)).round(3))
Exercise 2: Repair a repeated-subject split
Reveal the worked solution and reasoning
Suppose each flower has five photos. Split flower identifiers first, then assign all five photos according to that identifier, or use a group-aware splitter with flower ID as groups. Do not merely shuffle photo rows or stratify by species: both allow the same flower to appear on both sides. In the report, change the observation description to distinguish photo-level predictions from flower-level independence.
Recap and next step
An ML workflow is an argument about unseen cases: define the task, protect the evaluation boundary, establish a baseline, and record the assumptions. The next lesson keeps that boundary intact while imputing, scaling, and encoding inputs. A pipeline is valuable because it makes the training-only rule executable.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.