A model is only one part of a machine-learning system.
The system must repeat the same preparation on every row, explain its behaviour honestly, and use evidence that matches the question being asked.
Lesson details
- Module
- Classical machine learning
- Lesson
- 8 · Pipelines, interpretation & adjacent problems
- Difficulty
- Beginner
- Learning time
- 85 minutes
Before you start
- Training, validation, and test boundaries
- Tabular preprocessing and feature engineering
- Classification, regression, metrics, and regularisation
Skills you will gain
- Build a leakage-safe scikit-learn pipeline for numeric and categorical columns
- Write a small custom transformer with fit and transform
- Match feature importance, SHAP, LIME, and partial dependence to the question they answer
- Design temporal splits and walk-forward backtests for forecasting
- Explain collaborative filtering, matrix factorisation, and two-tower retrieval
- Distinguish prediction from causal and uplift questions
Why this matters
A notebook can look convincing while hiding three production failures:
- training and serving prepare data differently;
- an explanation is treated as proof that the model is right or causal;
- an ordinary random split is used for a question about the future, ranking, or intervention.
Plain-English mental model
Part 1 — Split first, then fit one pipeline
PipelinePipelineAn ordered chain that fits data transformations and a model together, then applies that same chain to new rows. has a precise job: chain transformations and an estimator behind one fit and predict interface.
The order is:
split rows → fit the entire pipeline on training rows → transform and predict held-out rows
Not:
fit preprocessing on every row → cross-validate the model
The second version leaks validation information into imputation values, scaling statistics, selected features, and category vocabularies.
ColumnTransformer routes columns deliberately
A column transformerColumn transformerA pipeline step that sends selected columns through different transformations and joins the resulting features. sends different columns down different preparation branches, then joins their outputs.
For a support ticket:
- waiting hours and contact count are numeric;
- channel is categorical;
- a custom rule may apply
log(1 + x)to non-negative counts; - the estimator receives the joined numeric feature matrix.
Unknown categories need an explicit serving policy. OneHotEncoder(handle_unknown="ignore") keeps the feature width stable and encodes an unseen category as zeros for that encoder. It does not mean the new category is harmless: log it, monitor it, and decide whether retraining is needed.
A custom transformer follows fit and transform
fit(X, y) learns any allowed state from training data and returns the transformer.
transform(X) applies the learned rule to rows. A stateless rule can return from fit without learning values, but it still follows the interface so the pipeline can clone and validate it.
Important lines
train, test = rows.iloc[:6], rows.iloc[6:]- The split happens before any transformer is fitted. Chat appears only in the held-out rows.
ColumnTransformer([...])- Named branches apply numeric and categorical rules to declared columns, then concatenate the results.
Pipeline([('prepare', ...), ('model', ...)])- Cross-validation can now fit every learned preprocessing step and the estimator together inside a training fold.
handle_unknown='ignore'- The two chat rows can be transformed without changing feature width, even though chat was absent during fit.
In cross-validation, pass the whole pipeline to the search or validation function. Do not fit prepare first.
In production, version:
- the fitted pipeline artifact;
- input schema and feature order;
- library and code versions;
- training-data reference;
- metric, threshold, and approval notes.
Part 2 — Ask an explanation a precise question
Interpretability means making a model’s behaviour understandable enough for a declared purpose. Different people need different evidence:
- a developer asks, “Which inputs drive this one surprising score?”;
- a reviewer asks, “Does the model depend on a prohibited shortcut?”;
- an operator asks, “When should I distrust or override it?”;
- an affected person may need a faithful, actionable reason under the applicable policy and law.
No single chart answers all four.
Four common tools
| Tool | Plain question | Mechanics | Important limit |
|---|---|---|---|
| Feature importanceFeature importanceA score describing how much a fitted model relied on a feature under a particular importance method; it does not by itself show direction or cause. | Which features does the fitted model rely on overall? | A model-specific score, or the score drop after shuffling one feature | Importance need not show direction; correlated features can share or hide importance |
| SHAPSHAPSHapley Additive exPlanations, a family of methods that assigns additive feature contributions to a prediction relative to a chosen baseline. | How did features add to this prediction relative to a baseline? | SHapley Additive exPlanations allocate additive contributions under a chosen background and masking rule | Baseline and feature dependence matter; attribution is not causation |
| LIMELIMELocal Interpretable Model-agnostic Explanations, a method that perturbs inputs near one example and fits a simpler local surrogate to approximate the original model there. | What simple rule approximates the model near this row? | Local Interpretable Model-agnostic Explanations perturb nearby inputs and fit a weighted simple surrogate | Results depend on neighbourhood, perturbations, representation, and seed |
| Partial dependencePartial dependenceAn averaged view of how a fitted model's predictions change when selected feature values are replaced across a set of background rows. | On average, how does model response change as a feature is replaced? | Replace feature values across background rows, predict, then average | Can create implausible combinations and can hide subgroup behaviour |
Permutation importance is often a useful model-agnostic start:
- measure the fitted model on validation data;
- shuffle one feature column;
- measure the score again;
- repeat and report the distribution of score changes.
If two features carry the same information, shuffling either one may barely hurt because the other remains. That is a property of the fitted model and data, not a contradiction.
Local and global views answer different questions
Local question
Why this prediction?
Positive terms raise the model score; negative terms lower it. These bars are the exact terms of this tiny formula—not SHAP or LIME, and not evidence of cause.
Global question
How does the model respond as waiting time changes?
This is partial-dependence-like: it changes one input across fixed background rows and averages predictions. The channel curves reveal behaviour the average alone would conceal.
The lab uses a transparent formula so every local bar can be checked exactly. The lower chart is only partial-dependence-like teaching, not the library implementation.
Try the same waiting time with chat and phone. The average curve rises smoothly, while the channel curves behave differently. An average can conceal an interaction.
Explanation is a diagnostic, not a verdict
An explanation can reveal:
- reliance on a suspicious identifier;
- unstable behaviour near a threshold;
- a subgroup pattern hidden by an average;
- mismatch between domain expectations and model logic.
It cannot by itself prove:
- the prediction is correct;
- the feature caused the outcome;
- the system is fair or lawful;
- the input was measured accurately;
- the model will remain reliable after deployment.
Check fidelity, stability, meaningful baselines, data lineage, subgroup metrics, and human consequences alongside the chart.
Part 3 — Some problems need different evidence
Ordinary tabular prediction often assumes rows can be treated as exchangeable after grouping and time constraints are handled. The following problems make a different structure central.
Part 4 — Time series predicts after a cutoff
A time seriesTime seriesObservations ordered through time, where earlier values may help predict later values and future information must not leak backwards. is a sequence of observations ordered through time. Examples include hourly demand, daily sign-ups, and sensor readings.
Before modelling, declare:
- forecast origin: the cutoff when the prediction is made;
- horizon: how far ahead you predict;
- frequency: hourly, daily, weekly, or another interval;
- available information: what is actually known at the origin;
- retraining cadence: when the fitted pipeline may be updated.
Three common model families are:
- ARIMA: autoregressive integrated moving average. It combines past values, differencing that can stabilise a changing level, and past forecast errors.
- Prophet: an additive forecasting model with trend, seasonal, and holiday components.
- feature-based models: ordinary estimators using lagged values, rolling summaries, calendar fields, and known future inputs.
These are options, not a quality ranking. Start with a seasonal-naive baseline such as “same hour last week”, then compare at the real horizon.
Walk forward instead of shuffling
BacktestingBacktestingReplaying a forecasting or decision procedure at past cutoffs so each simulated prediction uses only information available at that time. replays predictions at past cutoffs. Every validation window must occur after its training window.
This expanding window imitates repeated retraining with all earlier data. A rolling window would keep only the most recent training period. Choose the one that matches production and possible drift.
Avoid:
- random shuffling across time;
- computing rolling features with future rows;
- choosing a model on one lucky cutoff;
- evaluating one-step forecasts when production needs twelve steps;
- ignoring missing intervals and delayed labels.
Part 5 — Recommenders retrieve and rank items
A recommender does not merely predict one label. It usually:
- generates a manageable candidate set from a large catalogue;
- scores the candidates for a user or context;
- re-ranks for rules such as availability, freshness, safety, and diversity.
Collaborative filteringCollaborative filteringA recommendation approach that learns from patterns of user-item interaction so preferences shared across users and items inform suggestions. learns from user–item interaction patterns. Similar preference patterns can connect a user to an item even when no hand-written item feature says they match.
Matrix factorisationMatrix factorisationApproximating a user-item interaction table with smaller user and item vector tables whose dot products estimate affinity. approximates a sparse user–item table with smaller user and item vector tables. The dot product between a user vector and item vector becomes an affinity score.
The vector positions are latent dimensions: useful numerical directions learned to explain interaction patterns. Do not automatically give each position a human label.
A two-tower modelTwo-tower modelA recommender with one network that produces a query or user vector and another that produces an item vector so candidates can be compared efficiently. generalises this pattern:
- one network turns a user, query, and context into a vector;
- another turns item features into a vector;
- vector similarity retrieves candidates efficiently;
- a later ranker can use richer cross-features.
Evaluate on later interactions, not randomly mixed clicks. Report retrieval and ranking metrics at realistic list sizes, plus new-user, new-item, sparse-history, popularity, and exposure slices.
An unclicked item may never have been shown. Treating every unobserved interaction as dislike creates biased training evidence. Online experiments measure product consequences but still need guardrails for safety, diversity, latency, and long-term effects.
Part 6 — Causal questions ask what changes if we act
Prediction asks:
Who is likely to cancel?
Causal inferenceCausal inferenceReasoning about how an outcome would change under an intervention, using an experiment or explicit assumptions that make the comparison identifiable. asks:
Whose cancellation probability would change because we send a retention message?
Those are different targets. A person at high risk may cancel whether or not a message is sent. Another person at moderate risk may be persuadable.
A confounderConfounderA variable that influences both a treatment or exposure and an outcome, which can create a misleading association between them. influences both the treatment and outcome. For example, support severity may make an agent more likely to offer a discount and also make cancellation more likely. Comparing discounted and non-discounted customers directly then mixes treatment effect with severity.
Random assignment breaks that treatment-selection link on average and is the clearest design when ethical and practical. With observational data, causal estimates require explicit assumptions, appropriate adjustment, overlap between treatment groups, and sensitivity checks. A predictive pipeline or SHAP plot does not supply those conditions.
Uplift modellingUplift modellingEstimating how much an action changes an outcome for different people or groups, rather than only predicting the outcome itself. estimates a conditional treatment effect:
uplift(x) = expected outcome if treated at x
- expected outcome if not treated at x
Only one outcome is observed for each person. This missing counterfactual is the central difficulty.
These are invented potential-outcome probabilities for arithmetic practice, not estimates from observational data. Segment B has the highest outcome probability if messaged, but segment C has the largest incremental change. Production uplift needs experimental or defensible causal evidence, uncertainty, costs, harms, and a no-action policy.
Worked system example — a support operations pipeline
Suppose a team wants to forecast ticket volume, prioritise current tickets, recommend help articles, and test a proactive message.
The production interface should log:
- pipeline version and schema result;
- raw feature lineage and prediction timestamp;
- model score, threshold, and action taken;
- explanation method, baseline, and version when one is shown;
- forecast origin and horizon;
- recommendation candidates shown, their order, and later interaction;
- treatment assignment and outcome window for experiments.
Never log sensitive raw data merely because an explanation library can display it.
Common mistakes
Fitting an imputer, scaler, encoder, or feature selector before cross-validation.
Fix — Place every learned transformation and the estimator in one pipeline fitted inside each training fold.
Reimplementing preparation separately in an API.
Fix — Serve the fitted pipeline or generate training and serving features from the same tested definition. Validate schema before prediction.
Calling feature importance an explanation of cause.
Fix — Say exactly which fitted-model behaviour the method describes. Use experimental or causal evidence for intervention claims.
Showing one SHAP or LIME chart without its baseline or stability checks.
Fix — Record explainer, background data, masking or perturbation settings, seed, model version, and local fidelity.
Randomly shuffling time-series rows.
Fix — Backtest at past cutoffs using only information available then and the real forecast horizon.
Treating every unclicked item as disliked.
Fix — Record exposure, use appropriate sampling and objectives, and report popularity and cold-start slices.
Targeting the people with highest predicted risk when the goal is behaviour change.
Fix — Estimate incremental treatment effect with randomisation or explicit causal assumptions, costs, uncertainty, and harm constraints.
Exercises
A team imputes missing values and one-hot encodes categories before cross-validation. Explain the problem and redesign the workflow.
Reveal solution
The imputer statistics and category vocabulary have already learned from validation-fold rows. Put imputation, encoding, and the estimator in one pipeline. Fit that whole pipeline separately inside each training fold, then call predict on the untouched fold.
A SHAP chart says account age contributed -0.7 to one rejection score. What can you conclude, and what can you not conclude?
Reveal solution
For the chosen model, explainer, baseline, and input, account age lowered that model score by an additive contribution of 0.7 in the explainer’s units. It does not prove that changing account age would cause the decision to change by that amount, that the model is correct, or that the feature is fair.
Design evaluation evidence for (a) next-week demand, (b) article recommendation, and (c) a retention message intended to prevent cancellation.
Reveal solution
For demand, use past-only training and walk-forward forecasts at the real horizon. For recommendation, split interactions through time and measure retrieval/ranking plus cold-start and exposure slices. For the message, prefer a randomised experiment; otherwise state causal identification assumptions and estimate treatment effect or uplift, not cancellation risk alone.
Knowledge check
Knowledge check
Retrieval checkpoint
- Why must a fitted pipeline include preprocessing as well as the estimator?
Answer
Because learned imputation, encoding, scaling, and model state must be fitted on the same allowed rows and applied identically to validation, test, and production rows.
- When would you choose LIME rather than partial dependence?
Answer
Choose LIME when you need a simple local approximation near one row. Choose partial dependence when you need an averaged response as selected features change. State each method’s fidelity and data assumptions.
- What makes time-series validation different?
Answer
Future rows cannot teach the past. Each validation window follows its training window and matches the production horizon.
- What are the two towers in a recommender?
Answer
One maps a query, user, or context to a vector; the other maps an item to a vector. Similarity between those vectors supports candidate retrieval.
- Why is risk not the same as uplift?
Answer
Risk predicts an outcome under observed conditions. Uplift estimates the difference an action would make compared with no action.
Practice activity
Practice · 20–30 minutes
Write four evidence contracts for one support product
Goal: Separate pipeline, explanation, forecasting, recommendation, and intervention claims before choosing models.
- Choose a support-product decision and write its unit of prediction.
- List raw columns and assign each to numeric, categorical, custom, or excluded pipeline handling.
- Choose one local and one global interpretation question, method, baseline, and caveat.
- If the system forecasts, recommends, or intervenes, write the split and evidence contract for that subproblem.
- Name the production artifact, schema check, metric, monitoring slice, and fallback.
Expected result: A short design with one fitted tabular pipeline and separate evidence contracts. Every explanation names its question and baseline; every time, ranking, or treatment claim uses an appropriate split.
Optional challenge: Add a model card paragraph that distinguishes predictive association from causal effect.
Reveal solution
Decision: route a new ticket to specialist review
Unit: one ticket at its arrival timestamp
Pipeline:
numeric -> train-fold imputation + scaling
category -> train-fold imputation + unknown-safe encoding
text-derived counts -> shared, versioned custom transformer
estimator -> calibrated classifier
Local question:
why did this model score this ticket highly?
method -> SHAP with documented background
limit -> model attribution, not cause
Global question:
does the model rely on channel after controlling the review protocol?
methods -> permutation importance + subgroup metrics + partial response
Evidence:
group by customer, split through time, fit the whole pipeline per fold
protect a later final test period
Serving:
validate schema -> pipeline.predict_proba -> threshold -> capacity fallback
log pipeline version, timestamp, score, action, and monitored slicesThis answer keeps transformations inside the evaluation boundary. It also names what the explanations do and do not support. If the product later recommends an article or tests a message, add a ranking or causal contract rather than reusing the classifier’s random split.
Key takeaways
- Split first, then fit preprocessing and the estimator as one pipeline inside each training fold.
- Feature importance, SHAP, LIME, and partial dependence answer different local or global questions; none proves causality.
- Forecasts need past-to-future backtests at the real horizon.
- Recommenders retrieve and rank user–item candidates, with later-interaction and cold-start evidence.
- Intervention decisions need treatment-effect or uplift evidence, preferably from randomisation, rather than risk prediction alone.
Flashcards
Flashcards
1 of 11Revision and interview questions
- Design a leakage-safe Pipeline and ColumnTransformer for mixed numeric and categorical data.
- Compare feature importance, SHAP, LIME, and partial dependence by question, mechanics, and limitation.
- Design a walk-forward backtest for a twelve-hour forecast and explain why a random split fails.
- Explain collaborative filtering, matrix factorisation, two-tower retrieval, scoring, and re-ranking.
- Draw a treatment–outcome diagram with a confounder and explain why prediction alone cannot estimate uplift.
- Write the artifact, schema, logging, monitoring, and fallback contract for a production pipeline.
One-page sketchnote summary
Print me · one-page revision sheet
Pipelines, interpretation & adjacent problems
Main idea
Keep preparation reproducible, interpretation scoped, and evidence matched to the system’s real question.
Core terms
- Pipeline — fitted transforms plus model
- ColumnTransformer — branch by column type
- SHAP/LIME — local model explanations
- Partial dependence — averaged model response
- Backtest — replay past cutoffs
- Two tower — query and item vectors
- Uplift — effect of acting
One picture
Code pattern
split → pipeline.fit(train) → predict(held_out) · explain the model ≠ explain the world · time/ranking/treatment need their own evidenceWatch out
- Do not preprocess before splitting
- Do not confuse attribution with cause
- Do not random-shuffle time
- Do not equate no click with dislike
- Do not target on risk when the goal is change
Remember
- Ship one fitted path
- Ask explanations precise questions
- Match horizon in backtests
- Evaluate ranking as ranking
- Randomise interventions when possible
Three quick questions
- What learned state crosses serving?
- Is this local, global, or causal?
- Which split imitates the decision?
Lesson checklist
0 of 9 completeResources
- docsscikit-learn — pipelines and composite estimatorsOfficial guide to Pipeline, ColumnTransformer, feature unions, and safe parameter search.
- docsscikit-learn — permutation feature importanceOfficial explanation of score-drop importance and its limitations.
- docsscikit-learn — partial dependenceOfficial guide to average and individual model-response plots.
- docsSHAP documentationOfficial documentation for additive feature-attribution explainers and examples.
- docsProphet — diagnosticsOfficial walk-through of historical cutoffs, horizons, and forecast cross-validation.
- courseGoogle — recommendation systemsPrimary course on candidate generation, matrix factorisation, scoring, and re-ranking.
- docsEconML — causal inference user guideOfficial guide to heterogeneous treatment-effect estimation and its assumptions.