Lesson 3 of 30

Chapter 3 — The Complete Supervised Learning Workflow

Chapter overview

A successful supervised learning project is not a single call to a training function. It is a controlled sequence of decisions about the problem, data, validation strategy, candidate models, evaluation criteria, interpretation, delivery, and monitoring. A weakness in any one stage can invalidate the final result, even when the selected algorithm is technically sophisticated.

This chapter presents a complete workflow that can be reused for classification and regression. The emphasis is on experimental discipline: the test set remains untouched, transformations are learned only from training data, candidate models are compared under the same conditions, and every important decision is recorded. A synthetic customer-churn example is used throughout the Python sections so that the complete notebook can be executed without downloading external data.

KEY IDEA  The workflow is iterative, not merely linear

The numbered sequence provides a clear first pass, but real projects often move backward. Error analysis can reveal a data-quality problem, monitoring can trigger retraining, and feature interpretation can expose leakage. Iteration is valuable when each change is documented and re-evaluated under the same validation protocol.

 

Learning objectives

  • Describe the fifteen main stages of an end-to-end supervised learning project.
  • Distinguish the roles of training, validation, cross-validation, and testing data.
  • Construct a leakage-resistant preprocessing and modeling pipeline.
  • Establish meaningful baselines and compare candidate algorithms fairly.
  • Tune hyperparameters without using the test set.
  • Record configurations, random seeds, transformations, metrics, and artifacts for reproducibility.
  • Recognize common workflow mistakes and replace them with defensible practices.
  • Design a workflow diagram for a new supervised learning project.

Running example and notebook conventions

The code examples model customer churn as a binary classification problem. Each row represents one customer at a defined prediction date. The target equals 1 when that customer leaves during the following observation window and 0 otherwise. Numerical and categorical features are included, and a small amount of missing data is introduced to demonstrate realistic preprocessing.

Element

Running example

Unit of observationOne customer at the prediction date
Targetchurn: 1 = leaves during the next period; 0 = remains
Numerical featurestenure_months, monthly_charge, support_tickets, late_payments, usage_score
Categorical featurescontract_type and region
Primary metricROC AUC for model comparison; recall and precision for operational review
Final deliverableA serialized preprocessing-and-model pipeline plus evaluation report

 

Chapter map

Section

Purpose

3.1 Main workflowDevelop the complete project from problem definition to monitoring.
3.2 Experimental disciplineProtect the validity, fairness, and reproducibility of experiments.
3.3 Common mistakesIdentify workflow failures that create optimistic or unusable results.
Practical activityCreate and justify a workflow diagram for a supervised learning project.

 

3.1 Main Workflow

The complete workflow contains fifteen connected stages. Some stages create technical artifacts, such as a fitted pipeline or a metric report. Others create decision artifacts, such as a target definition, data contract, risk statement, or deployment threshold. A professional workflow treats both categories as essential.

Governing principles

Principle

Meaning

Separation of rolesTraining learns parameters, validation supports decisions, and testing estimates final generalization.
Whole-pipeline evaluationPreprocessing and the estimator are evaluated together under the same data boundaries.
Lifecycle ownershipThe project includes delivery, monitoring, retraining criteria, and retirement—not only model fitting.

 

Figure 3.1 — The fifteen-stage supervised learning workflow.

Workflow deliverables at a glance

Stage

Core question

Main artifact

1. Define the problemWhat decision or prediction is required?Problem statement and success criteria
2. Obtain dataWhich historical examples are available and lawful to use?Dataset inventory and provenance record
3. Understand dataWhat does each row and column mean?Data dictionary and exploratory report
4. Clean dataWhich quality problems must be corrected?Cleaning rules and quality log
5. Prepare featuresHow will raw variables become model inputs?Feature specification and preprocessing plan
6. Split dataHow will future or unseen performance be simulated?Train/validation/test split protocol
7. Establish baselineWhat simple result must the model exceed?Dummy or rule-based baseline
8. Select algorithmsWhich model families suit the task and constraints?Candidate model shortlist
9. Train modelsHow are identical training conditions applied?Fitted candidate pipelines
10. EvaluateWhich model generalizes best under the chosen criteria?Cross-validation comparison report
11. TuneWhich hyperparameters improve the selected candidates?Search results and chosen configuration
12. InterpretWhy does the model behave as observed?Global and local interpretation report
13. Final testWhat is the unbiased final estimate?Locked test-set evaluation
14. Save/deployHow will predictions be delivered safely?Versioned model artifact and interface
15. MonitorHow will drift and degradation be detected?Monitoring and retraining plan

 

3.1.1 Define the Problem

Problem definition determines every later choice. The team must state the predicted outcome, the unit of observation, the prediction horizon, the moment at which features are available, the intended user, and the action that follows a prediction. Without these details, a technically accurate model may answer the wrong question.

For customer churn, “predict churn” is incomplete. A usable formulation might be: “At the end of each month, estimate the probability that each active customer will cancel during the next 30 days, using information available before the scoring date, so that the retention team can prioritize a limited number of interventions.”

Problem component

Question to answer

Churn example

Unit of observationWhat does one row represent?One active customer at month-end
TargetWhat outcome is predicted?Cancellation within the next 30 days
Prediction timeWhen is the model executed?Last day of each month
Feature cutoffWhat information is allowed?Data recorded no later than month-end
User and actionWho acts on the result?Retention team contacts selected customers
Error costsWhich mistakes matter?False negatives lose customers; false positives consume capacity
Success criterionWhat level of value is required?Improved recall at a feasible contact volume

 

GOOD PRACTICE  Define the target before inspecting model scores

Changing the target from cancellation within 30 days to cancellation within 90 days creates a different dataset, operational process, and evaluation problem. The target definition must be versioned like code.

 

3.1.2 Collect or Obtain Data

Data may come from databases, files, APIs, surveys, sensors, experiments, logs, or public repositories. Collection is not only a technical task. The project must document provenance, permissions, time coverage, sampling mechanisms, label generation, and known limitations. Historical records reflect the process that produced them; they are not automatically representative of future use.

  • Identify authoritative sources and assign an owner to each source.
  • Record extraction dates, query versions, filters, and row counts.
  • Verify that labels were generated consistently across time and groups.
  • Confirm privacy, consent, retention, licensing, and security requirements.
  • Preserve an immutable raw snapshot before cleaning or feature construction.
  • Check whether important populations or rare events are underrepresented.

PYTHON   •  EXAMPLE 3.1 — CREATE A REPRODUCIBLE DEMONSTRATION DATASET

import numpy as np
import pandas as pd

RANDOM_STATE = 42
rng = np.random.default_rng(RANDOM_STATE)
= 2_500

df = pd.DataFrame({
    "customer_id": [f"C{i:05d}" forin range(n)],
    "tenure_months": rng.integers(173, n),
    "monthly_charge": rng.normal(6520, n).clip(15150),
    "support_tickets": rng.poisson(2.0, n),
    "late_payments": rng.poisson(0.8, n),
    "usage_score": rng.normal(6018, n).clip(0100),
    "contract_type": rng.choice(
        ["monthly""annual""two_year"], n, p=[0.550.300.15]
    ),
    "region": rng.choice(["north""south""east""west"], n),
})

contract_effect = df["contract_type"].map(
    {"monthly"0.9"annual"-0.25"two_year"-0.8}
)
logit = (
    -2.2 - 0.025 * df["tenure_months"]
    + 0.018 * (df["monthly_charge"- 60)
    + 0.30 * df["support_tickets"]
    + 0.48 * df["late_payments"]
    - 0.015 * (df["usage_score"- 50)
    + contract_effect
)
probability = 1 / (1 + np.exp(-logit))
df["churn"= rng.binomial(1, probability)

# Introduce realistic missing values for later preprocessing.
for column in ["monthly_charge""usage_score""contract_type"]:
    missing_rows = rng.choice(df.index, size=int(0.025 * n), replace=False)
    df.loc[missing_rows, column] = np.nan

print(df.head())
print("Churn rate:", df["churn"].mean().round(3))

 

Run this cell once at the start of the notebook. The same random seed recreates the same demonstration dataset.

 

3.1.3 Understand the Dataset

Data understanding combines semantic review and exploratory analysis. Semantic review asks what each field means, how it was measured, when it became available, and whether its meaning changed. Exploratory analysis examines distributions, missingness, duplicates, target prevalence, relationships, outliers, and unexpected values.

A data dictionary should distinguish identifiers, features, targets, timestamps, grouping variables, and fields excluded from modeling. Identifiers such as customer_id are useful for joining predictions back to business systems but are usually not predictive inputs. Timestamps may define split boundaries even when they are not model features.

PYTHON   •  EXAMPLE 3.2 — PRODUCE AN INITIAL DATA AUDIT

def audit_dataframe(data: pd.DataFrame, target: str-> pd.DataFrame:
    """Return a compact column-level quality report."""
    return pd.DataFrame({
        "dtype": data.dtypes.astype(str),
        "missing_n": data.isna().sum(),
        "missing_pct": (100 * data.isna().mean()).round(2),
        "unique_n": data.nunique(dropna=False),
        "example": [data[c].dropna().iloc[0if data[c].notna().any() else None
                    forin data.columns],
    }).sort_values(["missing_pct""unique_n"], ascending=[FalseTrue])

print("Shape:", df.shape)
print("Duplicate rows:", df.duplicated().sum())
print("Target counts:\n", df["churn"].value_counts(dropna=False))
print(audit_dataframe(df, target="churn"))

numeric_summary = df.describe(include=["number"]).T
categorical_summary = df.describe(include=["object"]).T
print(numeric_summary)
print(categorical_summary)

 

The audit is a starting point, not a substitute for a domain expert’s review of definitions and collection processes.

 

CAUTION  Unexpectedly strong predictors require investigation

A column that almost perfectly predicts the target may be genuinely informative, but it may also encode an event that occurs after the outcome, a manually assigned status derived from the label, or a duplicated identifier. Treat suspicious performance as a data question before celebrating it as a modeling success.

 

3.1.4 Clean the Data

Cleaning removes or corrects defects that prevent valid analysis. Typical tasks include resolving duplicate entities, standardizing categories, converting units, parsing dates, handling impossible values, and deciding how missingness will be treated. Cleaning rules should be explicit and deterministic so that the same logic can later be applied to new data.

Issue

Example

Defensible response

Missing valuemonthly_charge is absentInvestigate cause; impute within the training pipeline and optionally add a missing indicator
Invalid rangeusage_score = 145 although valid range is 0–100Correct from source, set to missing, or reject row according to a documented rule
Inconsistent categoryMonthly, monthly, MONTHLYNormalize case and map to one controlled vocabulary
Duplicate entitySame customer and scoring date repeatedDefine the authoritative record or aggregation rule
Unit inconsistencyCharges recorded in different currenciesConvert using a documented historical or contractual rule
Label inconsistencyCancellation definition changed mid-yearVersion the label and reconsider time coverage or stratification

 

GOOD PRACTICE  Do not hide cleaning decisions in ad hoc notebook cells

Cleaning logic should live in reusable functions, SQL transformations, validation rules, or versioned pipelines. A later reader must be able to identify exactly which rows and values were modified.

 

3.1.5 Prepare the Features

Feature preparation converts raw fields into numerical representations suitable for candidate algorithms. Numerical features may require imputation, scaling, transformation, or clipping. Categorical features commonly require imputation and one-hot or ordinal encoding. Dates may generate calendar or duration features. Text, images, and signals require specialized representations.

Any transformation that estimates a statistic from data—mean, median, scaling parameters, vocabulary, category frequencies, selected features, or learned embeddings—must be fitted on training data only. A scikit-learn pipeline makes this boundary explicit and applies identical transformations during validation, testing, and deployment.

Feature type

Typical preparation

Important risk

NumericalMedian imputation; optional standardization or log transformUsing full-dataset mean or standard deviation
Nominal categoricalMost-frequent imputation and one-hot encodingUnseen categories at prediction time
OrdinalOrdered encoding based on domain meaningInventing an order that does not exist
Date/timeDurations, recency, seasonality, day-of-weekUsing future timestamps or post-outcome information
TextTF–IDF, embeddings, language-specific processingVocabulary fitted before splitting or privacy leakage
Image/signalNormalization, windows, descriptors, learned representationsRelated samples from one entity split across datasets

 

3.1.6 Split the Dataset

The split strategy approximates how the model will encounter future unseen cases. Random splitting can be appropriate for independent and identically distributed observations. Stratified splitting preserves class proportions. Grouped splitting keeps all records from the same customer, patient, device, or subject together. Time-based splitting trains on earlier periods and evaluates on later periods.

Figure 3.2 — Training, validation, and test data serve different purposes.

KEY IDEA  The test set is a sealed final exam

Do not inspect its metrics repeatedly, use it to choose features, select a threshold, or decide between algorithms. Every such use turns the test set into another validation set and makes the reported performance optimistic.

 


 

 

PYTHON   •  EXAMPLE 3.3 — SPLIT FIRST AND CONSTRUCT A PREPROCESSING PIPELINE

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

TARGET = "churn"
DROP_COLUMNS = ["customer_id", TARGET]
= df.drop(columns=DROP_COLUMNS)
= df[TARGET]

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.20,
    stratify=y,
    random_state=RANDOM_STATE,
)

numeric_features = X.select_dtypes(include="number").columns.tolist()
categorical_features = X.select_dtypes(exclude="number").columns.tolist()

numeric_pipe = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("scaler", StandardScaler()),
])

categorical_pipe = Pipeline([
    ("imputer", SimpleImputer(strategy="most_frequent")),
    ("onehot", OneHotEncoder(handle_unknown="ignore")),
])

preprocessor = ColumnTransformer([
    ("numeric", numeric_pipe, numeric_features),
    ("categorical", categorical_pipe, categorical_features),
])

print("Training rows:"len(X_train))
print("Test rows:"len(X_test))

 

No imputer, scaler, or encoder is fitted yet. They will learn statistics only inside each training fold.

 

3.1.7 Establish a Baseline

A baseline establishes the minimum performance that a trained model must exceed. For classification, a DummyClassifier can always predict the majority class or sample according to class proportions. For regression, a DummyRegressor can always predict the training mean or median. A domain rule may provide a stronger operational baseline.

A baseline can expose a misleading metric. In a dataset with 98% negative cases, a classifier that predicts the negative class for everyone obtains 98% accuracy but detects none of the positive cases. Baselines should therefore be evaluated with metrics aligned to the project objective.

Baseline

Purpose

Interpretation

Majority-class classifierChecks whether a model beats the most frequent labelUseful accuracy floor, but may have zero minority recall
Stratified random classifierChecks whether ranking or probability metrics beat chanceExpected ROC AUC is near 0.5
Mean/median regressorProvides a no-feature regression referenceCandidate models must reduce prediction error
Domain ruleRepresents current practice or policyMost important baseline when replacing an existing process

 

3.1.8 Select Candidate Algorithms

Candidate selection should cover several model families while respecting data size, latency, interpretability, probability requirements, and maintenance constraints. A compact, diverse shortlist is more informative than an indiscriminate catalogue of algorithms.

Model family

Strengths

Limitations / requirements

Logistic regressionFast, interpretable, calibrated baseline, strong for approximately linear effectsRequires encoding; scaling helps; limited nonlinear interactions
Decision treeReadable rules, nonlinear splits, limited preprocessingHigh variance and easy overfitting
Random forestRobust nonlinear baseline, interactions, limited scaling needsLarger artifact; probabilities may need calibration
Gradient boostingOften excellent on structured tabular dataMore tuning; training and interpretation are more complex
Support vector machineStrong decision boundaries on medium-sized datasetsScaling required; can be expensive; probabilities are optional
K-nearest neighborsSimple local model and useful teaching toolScaling required; slow prediction; sensitive to dimensionality

 

GOOD PRACTICE  Complexity must earn its place

A more complex model is justified only when it provides a reliable improvement large enough to outweigh reduced interpretability, higher latency, tuning effort, maintenance cost, or operational risk.

 

3.1.9 Train the Models

Training estimates model parameters from the training data. For fair comparison, all candidates should use the same feature definition, cross-validation folds, scoring metrics, and preprocessing discipline. Each candidate should be represented as one complete pipeline so that preprocessing is refitted independently inside every training fold.

PYTHON   •  EXAMPLE 3.4 — COMPARE BASELINES AND CANDIDATE PIPELINES

from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model  import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier

models = {
    "dummy": DummyClassifier(strategy="prior"),
    "logistic": LogisticRegression(max_iter=1_000, class_weight="balanced"),
    "tree": DecisionTreeClassifier(
        max_depth=5, min_samples_leaf=20, random_state=RANDOM_STATE
    ),
    "random_forest": RandomForestClassifier(
        n_estimators=300,
        min_samples_leaf=5,
        class_weight="balanced",
        random_state=RANDOM_STATE,
        n_jobs=-1,
    ),
}

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=RANDOM_STATE)
scoring = {"roc_auc""roc_auc""f1""f1""recall""recall"}
results = []

for name, estimator in models.items():
    pipeline = Pipeline([("preprocess", preprocessor), ("model", estimator)])
    scores = cross_validate(
        pipeline, X_train, y_train, cv=cv, scoring=scoring, n_jobs=-1
    )
    results.append({
        "model": name,
        "roc_auc_mean": scores["test_roc_auc"].mean(),
        "roc_auc_std": scores["test_roc_auc"].std(),
        "f1_mean": scores["test_f1"].mean(),
        "recall_mean": scores["test_recall"].mean(),
        "fit_seconds": scores["fit_time"].mean(),
    })

comparison = pd.DataFrame(results).sort_values("roc_auc_mean", ascending=False)
print(comparison.round(3))

 

Cross-validation refits the preprocessing steps and estimator inside each fold, preventing statistics from leaking from validation folds into training.

 

3.1.10 Evaluate Performance

Evaluation asks whether the model generalizes, whether its errors are acceptable, and whether performance is stable across folds, time periods, and relevant subgroups. A single average score is insufficient. Report variability, confusion-matrix quantities, probability quality when needed, computation time, and failure patterns.

Question

Classification evidence

Regression evidence

Does the model discriminate or rank well?ROC AUC; precision-recall AUCCorrelation and explained variation may provide context
How large are the errors?False-positive and false-negative counts or ratesMAE, RMSE, quantile errors
Are predictions operationally useful?Precision/recall at chosen threshold or capacityError within acceptable tolerance
Are probabilities trustworthy?Log loss, Brier score, calibration curvePrediction intervals or uncertainty estimates
Is performance stable?Fold, time, source, and subgroup comparisonsResiduals and slice-level error comparisons

 

KEY IDEA  Choose the primary metric before comparing models

The primary metric encodes the project objective. Secondary metrics help explain trade-offs, but selecting whichever metric looks best after training encourages result shopping and weakens the experiment.

 

3.1.11 Tune Hyperparameters

Hyperparameters control model capacity, regularization, learning behavior, and computational trade-offs. They are selected using validation data or cross-validation—not the test set. Search spaces should be motivated by model behavior and available resources. Randomized search is often more efficient than an exhaustive grid when many parameters are considered.

Tuning should follow an initial comparison. Spending a large search budget on every candidate can waste resources and increase the chance of overfitting the validation procedure. Usually one or two promising model families are tuned more carefully.

PYTHON   •  EXAMPLE 3.5 — TUNE A CANDIDATE WITHOUT TOUCHING THE TEST SET

from scipy.stats import randint, loguniform
from sklearn.model_selection import RandomizedSearchCV

forest_pipeline = Pipeline([
    ("preprocess", preprocessor),
    ("model", RandomForestClassifier(
        class_weight="balanced",
        random_state=RANDOM_STATE,
        n_jobs=-1,
    )),
])

parameter_space = {
    "model__n_estimators": randint(200700),
    "model__max_depth": [None581216],
    "model__min_samples_split": randint(230),
    "model__min_samples_leaf": randint(120),
    "model__max_features": ["sqrt""log2"0.50.8],
}

search = RandomizedSearchCV(
    forest_pipeline,
    param_distributions=parameter_space,
    n_iter=30,
    scoring="roc_auc",
    cv=cv,
    random_state=RANDOM_STATE,
    n_jobs=-1,
    refit=True,
    return_train_score=True,
)
search.fit(X_train, y_train)

print("Best cross-validated ROC AUC:"round(search.best_score_, 3))
print("Best parameters:", search.best_params_)
best_pipeline = search.best_estimator_

 

RandomizedSearchCV selects settings using only the training portion and refits the best complete pipeline on all training rows.

 

3.1.12 Interpret the Results

Interpretation examines what the model learned, why individual predictions occur, and whether behavior is plausible. Linear coefficients, tree-based importance, permutation importance, partial dependence, and SHAP values answer different questions and have different limitations. Interpretation should be combined with domain review and error analysis.

  • Global interpretation: Which features influence predictions across the dataset?
  • Local interpretation: Which feature values contributed to one specific prediction?
  • Error analysis: Which types of observations produce false positives, false negatives, or large residuals?
  • Sensitivity analysis: How do predictions change when a feature is perturbed within a realistic range?
  • Sanity checks: Does the model rely on identifiers, post-outcome variables, proxies, or implausible relationships?

CAUTION  Importance is not causality

A feature can improve prediction because it correlates with the target. This does not establish that changing the feature will change the outcome. Causal claims require a different design and stronger assumptions.

 

3.1.13 Test the Final Model

After the model family, preprocessing, hyperparameters, and decision rule have been finalized, the complete pipeline is evaluated once on the untouched test set. This provides the closest available estimate of performance on comparable unseen data. The test report should include the primary metric, important secondary metrics, uncertainty or confidence intervals where possible, and limitations.

PYTHON   •  EXAMPLE 3.6 — PERFORM THE LOCKED FINAL TEST EVALUATION

from sklearn.metrics import (
    classification_report,
    confusion_matrix,
    precision_recall_curve,
    roc_auc_score,
)

# This is the first time X_test and y_test are used for model evaluation.
test_probability = best_pipeline.predict_proba(X_test)[:,  1]

# Example operational rule: select a threshold using training/CV analysis,
# then freeze it before evaluating the test set.
FINAL_THRESHOLD = 0.45
test_prediction = (test_probability >= FINAL_THRESHOLD).astype(int)

print("Test ROC AUC:"round(roc_auc_score(y_test, test_probability), 3))
print("Confusion matrix:\n", confusion_matrix(y_test, test_prediction))
print(classification_report(y_test, test_prediction, digits=3))

final_report = {
    "random_state": RANDOM_STATE,
    "threshold": FINAL_THRESHOLD,
    "test_roc_auc"float(roc_auc_score(y_test, test_probability)),
    "test_rows"int(len(y_test)),
    "best_parameters": search.best_params_,
}
print(final_report)

 

The decision threshold must also be selected without using the test labels. Freeze it before this cell is executed.

 

3.1.14 Save and Deploy the Model

Deployment makes the trained pipeline available to another process. Predictions may be generated in a scheduled batch, through an API, inside a web application, or on an edge device. The serialized artifact should include preprocessing and the estimator together, accompanied by model metadata, an input schema, version information, and tests.

Deployment concern

Required control

Input schemaValidate required columns, types, ranges, units, and allowed categories
VersioningAssign versions to code, data snapshot, feature definition, and model artifact
Dependency compatibilityRecord Python and library versions; rebuild artifacts when necessary
SecurityNever load untrusted pickle/joblib files; restrict artifact access
Latency and capacityMeasure prediction time, memory, batch size, and concurrent load
Fallback behaviorDefine what happens when input is invalid or the model is unavailable
TraceabilityLog model version, scoring time, input identifiers, and outputs appropriately

 

PYTHON   •  EXAMPLE 3.7 — SAVE, LOAD, VALIDATE, AND REUSE THE PIPELINE

from pathlib import Path
import joblib

MODEL_PATH = Path("artifacts/churn_pipeline_v1.joblib")
MODEL_PATH.parent.mkdir(parents=True, exist_ok=True)
joblib.dump(best_pipeline, MODEL_PATH)

loaded_pipeline = joblib.load(MODEL_PATH)
required_columns = list(X_train.columns)

def predict_churn(new_data: pd.DataFrame) -> pd.DataFrame:
    missing = sorted(set(required_columns) - set(new_data.columns))
    if missing:
        raise ValueError(f"Missing required columns: {missing}")

    ordered = new_data.loc[:, required_columns]
    probability = loaded_pipeline.predict_proba(ordered)[:,  1]
    return pd.DataFrame({
        "churn_probability": probability,
        "churn_prediction": (probability >= FINAL_THRESHOLD).astype(int),
    }, index=new_data.index)

example_predictions = predict_churn(X_test.head(5))
print(example_predictions)

 

Serialization formats such as joblib and pickle can execute code when loaded. Load only artifacts produced and stored by trusted systems.

 

3.1.15 Monitor the Model

A deployed model operates in a changing environment. Input distributions can drift, categories can appear or disappear, data pipelines can fail, user behavior can change, and the relationship between features and outcomes can weaken. Monitoring detects these changes early enough to investigate, retrain, recalibrate, or roll back.

Monitoring layer

Examples

Possible response

Service healthLatency, errors, throughput, memory, missing predictionsScale service, repair dependency, activate fallback
Schema and qualityMissing columns, invalid types, out-of-range values, unseen categoriesReject or quarantine records; repair upstream data
Input driftChanges in feature distributions or category proportionsInvestigate source/process change; schedule review
Prediction driftChanges in score, class, confidence, or abstention distributionCheck data shift, threshold, and capacity assumptions
PerformanceRecall, precision, AUC, MAE, calibration after labels arriveRecalibrate, retrain, redesign features, or retire model
Fairness and slicesError rates across relevant groups, regions, devices, or time periodsInvestigate representation and process differences

 

PYTHON   •  EXAMPLE 3.8 — RECORD SIMPLE PRODUCTION-QUALITY SIGNALS

def monitoring_snapshot(batch: pd.DataFrame, probabilities: np.ndarray) -> dict:
    snapshot = {
        "rows"int(len(batch)),
        "mean_probability"float(np.mean(probabilities)),
        "high_risk_rate"float(np.mean(probabilities >= FINAL_THRESHOLD)),
        "missing_rate": batch.isna().mean().round(4).to_dict(),
        "numeric_mean": batch.select_dtypes("number").mean().round(3).to_dict(),
        "category_share": {
            column: batch[column].value_counts(normalize=True, dropna=False)
                                  .round(4).to_dict()
            for column in batch.select_dtypes(exclude="number").columns
        },
    }
    return snapshot

production_batch = X_test.sample(100, random_state=7)
production_probability = loaded_pipeline.predict_proba(production_batch)[:,  1]
snapshot = monitoring_snapshot(production_batch, production_probability)
print(snapshot)

 

A production system should compare these signals with reference ranges, attach timestamps and model versions, and alert only when predefined conditions are met.

 

KEY IDEA  Monitoring closes the lifecycle

When labels become available, compare current performance with the validated reference. A retrained model must pass the same validation and test gates before replacing the deployed version.

 


 

 

3.2 Experimental Discipline

Experimental discipline protects the credibility of results. It separates exploration from final evaluation, makes comparisons fair, and ensures that another person can reconstruct what was done. The goal is not to eliminate iteration but to make every iteration traceable and scientifically defensible.

3.2.1 Keeping the Test Set Untouched

The test set is reserved for one final evaluation after all modeling choices have been fixed. This includes feature inclusion, preprocessing, candidate selection, hyperparameters, calibration method, decision threshold, and metric definitions. Looking at test results during development creates feedback: the team unconsciously adapts decisions to the test cases, and the final estimate becomes optimistic.

Allowed before final testing

Not allowed before final testing

Inspect training data and cross-validation resultsUse test labels to choose features or algorithms
Select a metric and validation strategyTune hyperparameters on test performance
Choose a threshold using validation predictionsAdjust the threshold after seeing the test confusion matrix
Debug code using synthetic or training examplesRepeatedly inspect test errors and revise the model
Verify test schema without studying labelsReport the best of many test-set experiments

 

CAUTION  What if the test set has already been used repeatedly?

Treat it as validation data. Create a new final test set from a later time period, a new source, or an independently held-out sample. Clearly document why the original test estimate is no longer unbiased.

 

3.2.2 Recording Model Configurations

A result without its configuration is not reproducible. Record algorithm names, hyperparameters, preprocessing choices, feature lists, random seeds, data snapshot identifiers, split rules, metrics, library versions, and output artifacts. Configuration files or structured dictionaries are preferable to scattered constants across notebook cells.

Record

Example

Experiment identifierchurn_rf_2026_08_01_001
Data versionwarehouse snapshot 2026-07-31; extraction query commit a92f…
Split rule80/20 stratified random split; random_state=42
Feature versionchurn_features_v3; seven input variables
Preprocessingmedian imputation, standardization, one-hot encoding
EstimatorRandomForestClassifier
Hyperparametersn_estimators=514, max_depth=12, min_samples_leaf=6
Primary metricfive-fold stratified CV ROC AUC
Artifact pathsmodel, report, predictions, environment specification

 

3.2.3 Controlling Random Seeds

Randomness can enter data splitting, resampling, model initialization, feature subsampling, and hyperparameter search. Fixed seeds make debugging and comparison easier. They do not guarantee identical results across all hardware, parallel execution orders, or library versions, and they do not replace repeated validation. The seed itself should be part of the experiment record.

PYTHON   •  EXAMPLE 3.9 — CENTRALIZE EXPERIMENT SETTINGS

from dataclasses import asdict, dataclass
import json
import platform
import sklearn

@dataclass(frozen=True)
class ExperimentConfig:
    name: str = "churn_workflow_demo"
    random_state: int = 42
    test_size: float = 0.20
    cv_folds: int = 5
    primary_metric: str = "roc_auc"
    final_threshold: float = 0.45

config = ExperimentConfig()
metadata = {
    "config": asdict(config),
    "python": platform.python_version(),
    "pandas": pd.__version__,
    "scikit_learn": sklearn.__version__,
    "rows"len(df),
    "columns"list(df.columns),
}

Path("artifacts").mkdir(exist_ok=True)
Path("artifacts/experiment_metadata.json").write_text(
    json.dumps(metadata, indent=2), encoding="utf-8"
)

 

Centralized settings reduce accidental inconsistencies between data splitting, cross-validation, model training, and saved reports.

 

3.2.4 Tracking Data Transformations

Every transformation should have a defined input, output, fitted state, and purpose. Pipelines provide an executable record, while feature specifications and data dictionaries provide human-readable context. Track transformations that occur upstream as well as those inside the model pipeline.

Transformation question

Why it matters

Was the transformation fitted or rule-based?Fitted transformations must learn from training data only.
What columns and units are expected?Prevents silent schema or unit mismatches.
How are missing and unknown values handled?Determines whether deployment can process real inputs safely.
Does the transformation use time or target information?Reveals temporal and target leakage.
Is the output feature order stable?Ensures the estimator receives the same representation.
Is the transformation versioned and tested?Supports reproducible retraining and rollback.

 

3.2.5 Comparing Models Fairly

A fair comparison changes the model while holding the experimental conditions constant. Candidates should see the same training examples, cross-validation folds, scoring functions, feature definitions, and preprocessing principles. Search budgets and computational constraints should be disclosed, especially when one model receives much more tuning than another.

Fair-comparison control

Unfair alternative

Same cross-validation folds for all candidatesDifferent random splits chosen separately for each model
Same primary metricSelecting the best-looking metric for each model
Pipeline-based preprocessing within foldsPreprocessing the complete dataset before validation
Comparable feature informationGiving one candidate access to additional variables
Reported tuning budgetExtensively tuning one model and using defaults for all others
Multiple dimensions reportedChoosing only by mean score while ignoring variability and cost

 

3.2.6 Avoiding Accidental Reuse of Test Data

Test leakage is not limited to calling fit on the test rows. It can occur when a developer repeatedly checks the test score, manually examines test errors, computes full-dataset preprocessing statistics, selects features using all labels, or uses the test distribution to redesign categories. Organizational controls can be as important as code controls.

  • Store the test set separately or expose it through a final-evaluation script.
  • Limit access to test labels during model development.
  • Use cross-validated out-of-fold predictions for threshold and calibration analysis.
  • Keep a written record of every test-set execution.
  • Require a final configuration file before unlocking the test evaluation.
  • Create an external or later-period validation set for especially high-stakes projects.

3.2.7 Reproducibility

Reproducibility means that the dataset, code, environment, configuration, and execution sequence can regenerate the reported artifacts within expected numerical tolerances. It includes more than setting a random seed. The original raw data or a lawful immutable snapshot, extraction logic, dependency versions, hardware-sensitive notes, and report-generation process all matter.

Reproducibility layer

Recommended artifact

DataImmutable snapshot, checksum, extraction query, provenance and license notes
CodeVersion-control commit, reviewed source files, automated tests
EnvironmentPinned dependencies, Python version, container or environment file
ConfigurationMachine-readable parameters and split rules
ExecutionScript or notebook with deterministic cell order
ResultsSaved predictions, metrics, plots, logs, and model artifact
DocumentationREADME, data dictionary, model card, limitations, intended use

 

KEY IDEA  Reproducible does not mean universally identical

Floating-point arithmetic, parallelism, platform libraries, and hardware can create very small differences. Define acceptable tolerances and verify that scientific conclusions and operational decisions remain unchanged.

 

Minimal experiment checklist

Before training

During comparison

Before final test

Before deployment

Target and horizon frozenSame folds and metricsConfiguration frozenArtifact and schema versioned
Raw data snapshot recordedPipelines fitted within foldsThreshold frozenInference tests passed
Split protocol selectedMean and variability reportedOne controlled executionSecurity review completed
Primary metric declaredErrors and costs examinedReport archivedMonitoring thresholds defined

 

3.3 Common Mistakes

Workflow mistakes can create impressive but invalid results. The following errors are common because they simplify the notebook or produce attractive metrics in the short term. Each one should be recognized by its symptom, understood by its mechanism, and corrected through a specific experimental control.

3.3.1 Training on the Entire Dataset

The model is fitted on every available row, leaving no independent examples for validation or testing. Training performance then measures how well the model fits known data rather than how it generalizes.

GOOD PRACTICE  Corrective practice

Reserve independent data before fitting. Use cross-validation on the training portion and a final untouched test set.

 

3.3.2 Evaluating on the Training Set

Metrics computed on the same examples used for fitting are systematically optimistic, especially for flexible models. A deep tree can memorize training labels and still fail on new cases.

GOOD PRACTICE  Corrective practice

Report training metrics only as a diagnostic and compare them with validation or cross-validation metrics.

 

3.3.3 Performing Preprocessing Before Splitting

Imputation, scaling, feature selection, target encoding, or vocabulary construction on the complete dataset transfers information from validation and test observations into training.

COMMON MISTAKE  Corrective practice

Split first and place fitted transformations inside a pipeline that is trained separately within each fold.

 

3.3.4 Selecting a Metric After Seeing the Results

Trying many metrics and highlighting the most favorable one makes the evaluation objective depend on the observed outcomes.

GOOD PRACTICE  Corrective practice

Declare a primary metric and operational criteria before model comparison. Report relevant secondary metrics transparently.

 

3.3.5 Ignoring Class Imbalance

Accuracy may be high even when the minority event is never detected. Default thresholds and unweighted training may not reflect error costs.

GOOD PRACTICE  Corrective practice

Inspect prevalence, confusion matrices, precision-recall behavior, class weights, resampling, and operational thresholds.

 

3.3.6 Optimizing Directly on the Test Set

Repeated tuning against test performance overfits decisions to the test sample, converting it into validation data.

COMMON MISTAKE  Corrective practice

Tune with cross-validation or a validation set. Evaluate the locked configuration once on the test set.

 

3.3.7 Using Accuracy for Every Classification Problem

Accuracy treats all errors equally and can conceal failure on rare or costly classes. It also ignores ranking and probability quality.

GOOD PRACTICE  Corrective practice

Choose metrics from the decision context: recall, precision, F1, PR AUC, ROC AUC, log loss, calibration, or cost.

 

3.3.8 Assuming a More Complex Model Is Always Better

Complexity can improve training fit while increasing variance, latency, maintenance effort, and explanation difficulty. Small score gains may not survive new data.

GOOD PRACTICE  Corrective practice

Prefer the simplest model that meets validated performance and operational constraints; justify added complexity with evidence.

 

Mistake diagnostic table

Observed symptom

Likely cause

First investigation

Training score is excellent; validation score is poorOverfitting or leakage in feature constructionCompare learning curves; simplify model; audit features
All models score unusually close to 1.0Target leakage, duplicate rows, post-event variablesTrace feature timestamps and target derivation
Accuracy is high but positive recall is near zeroClass imbalance and unsuitable thresholdInspect confusion matrix and precision-recall curve
Cross-validation is strong but production failsDistribution shift, group leakage, schema mismatchCompare production data and validate split design
Results change dramatically between runsSmall data, unstable split, uncontrolled randomnessFix seeds, repeat CV, inspect subgroup counts
A tuned model is only slightly better but much slowerOverly complex search or diminishing returnsMeasure latency and select using operational utility
Saved model gives different behavior from notebookPreprocessing not saved or feature order differsSerialize the complete pipeline and validate schema

 


 

 

Practical Activity — Design a Supervised Learning Workflow Diagram

Students create a workflow diagram for a proposed supervised learning project and justify the information flow, data boundaries, validation strategy, and final deliverables. The activity can be completed individually or in groups of two to four students.

Activity scenario

A university wants to identify students who may fail a first-semester course so that academic support can be offered early. Available historical data include program, prior grades, attendance up to week 5, learning-platform activity up to week 5, assessment scores available by week 5, and the final course result. The intervention team can support at most 15% of enrolled students.

CAUTION  Ethical boundary

The purpose is to offer support, not to punish, rank, exclude, or deny opportunities. Students should consider privacy, fairness, transparency, and human review when designing the workflow.

 

Student instructions

1.  Define the unit of observation, target, prediction time, feature cutoff, user, action, and primary success criterion.

2.  List the expected raw data sources and record at least three data-quality or governance risks.

3.  Choose a split strategy. Decide whether random, stratified, grouped, or time-based splitting is most appropriate and justify the choice.

4.  Specify numerical, categorical, and time-derived preprocessing steps. Indicate which transformations must be fitted on training data only.

5.  Define one dummy baseline and one current-practice or rule-based baseline.

6.  Select at least three candidate algorithms from different model families.

7.  Choose a primary metric and at least two secondary metrics. Explain how the 15% intervention capacity affects threshold selection.

8.  Describe a cross-validation and hyperparameter-tuning plan that does not use the test set.

9.  Define the final test gate, model interpretation tasks, deployment artifact, and monitoring signals.

10.  Draw arrows showing feedback loops from monitoring or error analysis back to data review and retraining.

Workflow diagram template

Phase

Boxes to include

Required annotation

A. FrameProblem → target → prediction time → actionState the feature cutoff and error costs
B. DataSources → audit → cleaning → feature preparationMark identifiers, target, groups, and timestamps
C. ValidationSplit → baseline → candidates → cross-validationDraw a visible boundary around the untouched test set
D. SelectionMetric comparison → tuning → interpretationIdentify the primary metric and decision threshold
E. OperationFinal test → save/deploy → monitor → retrainRecord artifact version, schema checks, and alerts

 

Required deliverables

  • One-page workflow diagram with numbered stages and directional arrows.
  • A 300–500 word justification of the target, split strategy, metrics, and test-set boundary.
  • A table listing at least five risks and corresponding controls.
  • A short experiment record containing the proposed random seed, cross-validation design, candidate algorithms, and artifact names.
  • A monitoring panel specifying at least two service, two data-quality, two drift, and two performance signals.

Suggested risk-control table

Risk

Why it matters

Proposed control

Attendance recorded after week 5Creates temporal leakageEnforce a timestamp cutoff in extraction queries
Multiple course records for one studentMay leak the same student across foldsUse grouped or carefully time-aware splitting
Low number of failing studentsAccuracy may conceal missed casesUse stratification and precision-recall metrics
Historical interventions affected outcomesLabels reflect prior policyDocument intervention history and analyze cohorts
Sensitive attributes or proxiesMay produce unequal error ratesReview necessity, legality, fairness, and subgroup performance
Only 15% can receive supportDefault threshold may exceed capacitySelect threshold using validation ranking and capacity

 

Assessment rubric

Criterion

Excellent

Adequate

Needs improvement

Problem formulationTarget, timing, action, cutoff, and costs are preciseMost elements defined but one is ambiguousProblem remains generic or unmeasurable
Data and leakage controlSources, provenance, groups, time, and fitted transformations are explicitBasic cleaning and split are shownPreprocessing or temporal boundaries are unclear
Validation designBaseline, CV, metrics, tuning, and sealed test set are coherentValidation exists but some choices lack justificationTest data is reused or metrics are unsuitable
Operational designDeployment, schema, monitoring, and retraining loop are completeDeployment and basic monitoring includedWorkflow stops after training
CommunicationDiagram is readable, numbered, and supported by concise rationaleDiagram is understandable with minor gapsArrows, stages, or explanations are inconsistent

 

Model answer — Key design decisions

Decision

Reasoned answer

Unit and targetOne student-course enrollment; target = fail/pass at semester end.
Prediction timeEnd of week 5; only information recorded by that cutoff is eligible.
Split strategyPrefer later cohorts as test data; use grouped or stratified CV while preventing the same student from crossing folds.
Primary metricRecall or precision-recall-oriented utility at a threshold selecting no more than 15% of students.
BaselineMajority classifier plus a simple rule based on early assessment and attendance.
CandidatesRegularized logistic regression, constrained decision tree, random forest or gradient boosting.
InterpretationGlobal importance, false-negative review, subgroup performance, and case-level explanations for human advisers.
DeploymentWeekly batch scores delivered to authorized advisers with model version and explanation summary.
MonitoringSchema, missingness, score distribution, selected-rate, delayed-label recall/precision, and subgroup differences.

 

KEY IDEA  Expected outcome

Students should be able to place supervised learning inside a complete project lifecycle. They should understand that model training is only one stage and that valid data boundaries, fair validation, reproducibility, deployment controls, and monitoring determine whether a model can be trusted and maintained.

 

Knowledge check

1.  Why should the primary evaluation metric be selected before candidate models are compared?

2.  What is the difference between validation data and test data?

3.  Name three transformations that can leak information when fitted before splitting.

4.  Why might grouped or time-based splitting be preferable to a random split?

5.  What does a dummy baseline reveal?

6.  Why should preprocessing and the estimator be stored in one pipeline?

7.  What information belongs in an experiment configuration record?

8.  When can the final test set be evaluated?

9.  Give three categories of post-deployment monitoring.

10.  Why is the most accurate model not automatically the best model?

Knowledge check — Suggested answers

1. Selecting it in advance prevents result shopping and aligns model selection with the scientific or operational objective.

2. Validation data supports choices during development; test data provides one final unbiased estimate after choices are frozen.

3. Examples include imputation, scaling, feature selection, target encoding, vocabulary construction, and aggregation statistics.

4. They prevent related entities or future information from appearing in both training and evaluation data and better simulate deployment.

5. It shows the performance achievable without useful feature learning and provides a minimum standard for candidate models.

6. The pipeline ensures that identical fitted transformations and feature order are applied during validation, testing, and inference.

7. Data version, split rule, feature definition, preprocessing, algorithm, hyperparameters, seed, metrics, dependencies, and artifact paths.

8. Only after preprocessing, model family, hyperparameters, threshold, and report plan have been frozen.

9. Service health, schema/data quality, input or prediction drift, delayed performance, fairness slices, and operational capacity.

10. A small accuracy gain may not justify poorer interpretability, higher latency, instability, maintenance cost, or operational risk.

Chapter summary

The complete supervised learning workflow begins with a measurable problem and ends with a monitored operational system. Data is collected and understood before it is cleaned and transformed. A split strategy protects independent evaluation. Baselines and diverse candidate algorithms are compared under identical cross-validation conditions. Hyperparameters are tuned without touching the test set, and interpretation verifies that the model relies on plausible information. The locked configuration is then evaluated once, serialized as a complete pipeline, deployed with schema and security controls, and monitored for quality, drift, performance, and fairness.

Experimental discipline is the thread connecting every stage. Keeping the test set untouched, controlling randomness, recording configurations, tracking transformations, and ensuring reproducibility make the reported results defensible. Avoiding common mistakes—especially leakage, training-only evaluation, unsuitable metrics, and unnecessary complexity—turns machine learning from an isolated experiment into a reliable engineering and scientific process.

Key terms

Term

Meaning

BaselineA simple reference model or rule that candidate models must exceed.
Candidate modelA model family evaluated under the common experimental protocol.
Cross-validationRepeated training and validation across defined folds to estimate generalization.
Data leakageInformation unavailable at genuine prediction time entering model training or selection.
HyperparameterA configuration choice set outside ordinary parameter fitting.
PipelineA single object that applies fitted preprocessing and then generates predictions.
ReproducibilityAbility to regenerate results from recorded data, code, configuration, environment, and execution.
Test setIndependent examples reserved for the final locked evaluation.
MonitoringOngoing observation of service, data, predictions, performance, and drift after deployment.