AI ENGINEER01-08 · Pipelines, interpretability & adjacent problems
24/90
Sign in

Layer 01 · Classical ML · Ch 08

Pipelines, interpretability & adjacent problems

Keep transformations reproducible, ask explanations precise questions, and recognise when time, ranking, or intervention changes the problem.

85 min readdifficulty beginnerdepth use

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:

  1. training and serving prepare data differently;
  2. an explanation is treated as proof that the model is right or causal;
  3. 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.

FIG 01-08.1 · THE PIPELINE IS THE MODEL BOUNDARYone fitted path from raw row to predictionraw rowssplit before fittrain · valid · testColumnTransformersend each column type down its declared branchnumbersimputescale / logcategoriesimputeone-hotcustom rulefit(X, y)transform(X)joined feature matrixestimatorfit / predictone pipeline APIFITTED ARTIFACTlearned imputer · encoder categories · scaler · model parametersversion with schema + library versions + training data referencesave togethervalidation · testproduction rowstransform + predictnever fitif training and serving take different paths, you are testing a different system
FIG 01-08.1— split before fitting. Numeric, categorical, and custom branches learn from training rows, then the fitted transformation state and estimator travel as one versioned artifact. Validation, test, and production rows never refit it.

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.

LAB 01-08.B · FIT A REAL SCIKIT-LEARN PIPELINE
IDLE⌘↵ to run

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:

  1. measure the fitted model on validation data;
  2. shuffle one feature column;
  3. measure the score again;
  4. 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

LAB 01-08.A · EXPLANATION WORKBENCH
Toy support ticket
Predicted escalation34.5%teaching model, not a production estimate

Local question

Why this prediction?

Baseline
-2.40
Waiting time
+1.28
Previous contacts
+0.48
Channel
+0.00
Wait × channel
+0.00

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?

Model response across waiting time for an average and two channelsThe solid average curve and dashed channel curves show predicted escalation from zero to twenty-four waiting hours. At 8 hours, the average curve is 34.7 percent. Chat rises faster than phone, so the average hides subgroup behaviour.

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.

LAB 01-08.A — change the ticket, compare a local score breakdown with a global response curve, and notice that explanation answers depend on the question asked.

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.

FIG 01-08.2 · LET THE QUESTION CHOOSE THE EVIDENCEsame toolbox, three different questionstime seriesWHAT HAPPENS AFTER THE CUTOFF?pastfutureARIMA · Prophetlags · rolling featuresEVIDENCEwalk-forward backtestnever random-shuffle timerecommendationWHICH ITEMS SHOULD WE RANK?userquery toweritemitem tower·retrieve → score → re-rankEVIDENCElater interactionscold-start + exposure slicescausal inferenceWHAT CHANGES IF WE ACT?confoundercommon causetreatmentoutcomeEVIDENCErandomise or state assumptionsestimate uplift, not riskthe question chooses the split, metric, and evidence—not the other way round
FIG 01-08.2— forecasting protects time order, recommendation evaluates later user–item choices and cold starts, and causal inference needs randomisation or explicit identification assumptions. One random train/test split cannot answer all three.

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.

LAB 01-08.C · BUILD EXPANDING-WINDOW BACKTESTS
IDLE⌘↵ to run

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:

  1. generates a manageable candidate set from a large catalogue;
  2. scores the candidates for a user or context;
  3. 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.

LAB 01-08.D · RANK ITEMS WITH A DOT PRODUCT
IDLE⌘↵ to run

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.

LAB 01-08.E · RANK SYNTHETIC SEGMENTS BY UPLIFT
IDLE⌘↵ to run

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

warmup · 1

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.

core · 2

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.

stretch · 3

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

1Where should a ColumnTransformer be fitted during cross-validation?
2What does a positive SHAP contribution establish?
3Why use a walk-forward backtest?
4What does matrix factorisation learn?
5Which target matches a retention intervention?

Retrieval checkpoint

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  1. Choose a support-product decision and write its unit of prediction.
  2. List raw columns and assign each to numeric, categorical, custom, or excluded pipeline handling.
  3. Choose one local and one global interpretation question, method, baseline, and caveat.
  4. If the system forecasts, recommends, or intervenes, write the split and evidence contract for that subproblem.
  5. 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 slices

This 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 11

Revision and interview questions

  1. Design a leakage-safe Pipeline and ColumnTransformer for mixed numeric and categorical data.
  2. Compare feature importance, SHAP, LIME, and partial dependence by question, mechanics, and limitation.
  3. Design a walk-forward backtest for a twelve-hour forecast and explain why a random split fails.
  4. Explain collaborative filtering, matrix factorisation, two-tower retrieval, scoring, and re-ranking.
  5. Draw a treatment–outcome diagram with a confounder and explain why prediction alone cannot estimate uplift.
  6. 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

one fitted path from raw row to predictionraw rowssplit before fittrain · valid · testColumnTransformersend each column type down its declared branchnumbersimputescale / logcategoriesimputeone-hotcustom rulefit(X, y)transform(X)joined feature matrixestimatorfit / predictone pipeline APIFITTED ARTIFACTlearned imputer · encoder categories · scaler · model parametersversion with schema + library versions + training data referencesave togethervalidation · testproduction rowstransform + predictnever fitif training and serving take different paths, you are testing a different system

Code pattern

split → pipeline.fit(train) → predict(held_out) · explain the model ≠ explain the world · time/ranking/treatment need their own evidence

Watch 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

  1. What learned state crosses serving?
  2. Is this local, global, or causal?
  3. Which split imitates the decision?

Lesson checklist

0 of 9 complete

Resources

Next up
From neurons to networks
Classical machine learning is now complete. Next, reuse the same habits—declared inputs, explicit transformations, honest validation, and careful interpretation—while building the smallest neural network.