Interpreting and deploying models
A model is only valuable if people can trust it, use it and keep it working. This module covers what happens after the accuracy score.
Learning objectives
- Measure feature importance with permutation importance
- Analyse errors by group
- Save and load models safely
- Plan deployment, monitoring and retraining
- Choose between classic ML and LLMs
- Detect drift by comparing new data with training data
- Review an ML pipeline with a short checklist
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
"tenure_months": rng.integers(1, 60, n),
"monthly_spend": rng.normal(40, 15, n).clip(5, 120).round(2),
"support_tickets": rng.poisson(1.2, n),
"on_promo": rng.integers(0, 2, n),
"region": rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
- 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
+ rng.normal(0, 40, n)).round(2)
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
features = ["tenure_months", "monthly_spend", "support_tickets", "on_promo"]
X, y = customers[features], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_score, recall_score, roc_auc_score6.1 Which features matter?
Permutation importance measures how much a model's score drops when one feature's values are randomly shuffled — breaking its link with the target. It works for any model and is computed on held-out data.
from sklearn.inspection import permutation_importance
rf = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_train, y_train)
imp = permutation_importance(rf, X_test, y_test, scoring="roc_auc", n_repeats=5, random_state=0)
print(pd.Series(imp.importances_mean, index=features).sort_values(ascending=False).round(3))
On our synthetic data you should see tenure_months and support_tickets near the top — matching the hidden pattern. On real data, importance tells you what the model relies on, which is not necessarily what causes the outcome.
Explaining a single prediction
Importance describes the model overall. People affected by a decision usually want to know about their case. A simple, honest way is a what-if: change one input and see how the prediction moves.
Python · a what-if for one customerone = X_test.iloc[[0]].copy()
print(one.to_string(index=False))
print("Churn probability:", model.predict_proba(one)[0, 1].round(2)) # the logistic model from Module 1
for tickets in [0, 2, 4, 6]:
what_if = one.assign(support_tickets=tickets)
print(f" with {tickets} tickets: {model.predict_proba(what_if)[0, 1]:.2f}")
Each extra ticket pushes this customer's score up. (Swap model for rf and the steps become uneven: tree ensembles respond in jumps, which is one reason simpler models are easier to explain.) This shows how the model responds, which is what you need for explaining a score. It does not prove that resolving a customer's tickets would make them stay; that would take an experiment.
6.2 Error analysis by group
test = X_test.copy()
test["actual"] = y_test
test["pred"] = (rf.predict_proba(X_test)[:, 1] >= 0.5).astype(int)
test["region"] = customers.loc[X_test.index, "region"]
for region, g in test.groupby("region"):
print(region, "n =", len(g),
" recall =", round(recall_score(g["actual"], g["pred"]), 2),
" precision =", round(precision_score(g["actual"], g["pred"], zero_division=0), 2))
Check performance for every group that matters — regions, customer types and, where lawful and appropriate, protected characteristics. Overall scores can hide poor performance for smaller groups (see Responsible AI, Module 3).
Mind the group sizes. With around 100 customers in the smaller region, a difference of a few points in recall can be chance. Small groups need more data, or at least a clear note that the estimate is uncertain.
6.3 Saving and loading a model
import joblib
joblib.dump(rf, "churn_model_v1.joblib")
loaded = joblib.load("churn_model_v1.joblib")
print(loaded.predict_proba(X_test.head(3))[:, 1].round(2))
Only load model files from sources you trust: like Python pickles, joblib files can execute code when loaded.
6.4 Deploying and monitoring
- Serve predictions in batch (e.g. a nightly churn list) or in real time (an API)
- Monitor input data for drift, prediction distributions, and real outcomes as they arrive
- Retrain on a schedule or when performance drops — and re-evaluate before replacing the live model
- Version data, code and models so any prediction can be traced
- Document the model in a model card: purpose, data, metrics by group, limitations, owner
6.5 Classic ML or an LLM?
Classic ML is usually better when…
- you have structured, tabular data
- you need a number or category at high volume and low cost
- you have labelled historical outcomes
- you need well-understood, auditable behaviour
An LLM is usually better when…
- inputs are unstructured text, images or audio
- you have few or no labelled examples
- the task needs language generation or reasoning
- requirements change often and prompting is faster than retraining
Many strong systems combine both — for example, an LLM extracts structured fields from emails, and a gradient-boosted model scores them.
The same pairing shows up in AI agents: an agent handling a customer conversation can call a churn model as a tool to get a risk score, then decide what to offer. The score comes from a small, tested, auditable model; the conversation comes from the LLM. Asking an LLM to guess the churn probability directly would be slower, costlier and much harder to check.
6.6 Drift: a worked example
A model learns the world as it was when the training data was collected. Suppose that, six months after launch, a price rise brings in higher-spending customers and a product fault doubles support tickets. Simulate that month and compare it with the training data:
Python · has the incoming data drifted?rng2 = np.random.default_rng(7)
new_month = pd.DataFrame({
"tenure_months": rng2.integers(1, 60, 500),
"monthly_spend": rng2.normal(52, 15, 500).clip(5, 120).round(2), # was about 40
"support_tickets": rng2.poisson(2.4, 500), # was about 1.2
"on_promo": rng2.integers(0, 2, 500),
})
compare = pd.DataFrame({"training": X_train.mean(), "new month": new_month.mean()}).round(2)
compare["change %"] = ((compare["new month"] / compare["training"] - 1) * 100).round(0)
print(compare)
print("Share flagged as churners, test set: ", (rf.predict_proba(X_test)[:, 1] >= 0.5).mean().round(2))
print("Share flagged as churners, new month:", (rf.predict_proba(new_month)[:, 1] >= 0.5).mean().round(2))
Two features have shifted sharply and the share of customers flagged has risen. Neither fact tells you the model is now wrong: perhaps more customers really are about to leave. It tells you the model is working outside the conditions it was tested in, so its scores need checking against real outcomes before anyone relies on them. Simple comparisons like this, run every week, catch most problems early.
6.7 Reviewing ML work that an AI wrote
Whether a pipeline was written by a colleague or by an AI coding assistant, the same short review catches most serious mistakes. You now know enough to run it:
- Is there a baseline? A score means nothing without something to compare it with (Module 1).
- Could any feature be unavailable at prediction time? A suspiciously high score is a leak until proven otherwise (Module 4).
- Was the test set used only once? Tuning against it makes the reported score optimistic (Module 4).
- Is preprocessing inside the pipeline? Scaling or imputing before the split leaks information (Module 4).
- Does the metric match the decision? Accuracy on a rare-event problem hides failure (Module 3).
- Are results broken down by group? (6.2)
- Can it be reproduced? Fixed random seeds, versions recorded, data snapshot kept.
Write a short model card (as a Python dictionary or Markdown) for the churn model: purpose, training data, test AUC, recall by region, known limitations, and owner.
Your turn# Write your code here, then press RunShow a solution
card = {
"model": "churn_model_v1 (random forest, 100 trees)",
"purpose": "Rank customers for weekly retention calls; human decides who to call",
"data": "Synthetic customers, 2,000 rows; features: tenure, spend, tickets, promo",
"test_auc": round(roc_auc_score(y_test, rf.predict_proba(X_test)[:, 1]), 3),
"recall_by_region": {r: round(recall_score(g["actual"], g["pred"]), 2) for r, g in test.groupby("region")},
"limitations": "Synthetic data; not validated on real customers; association not causation",
"owner": "Retention analytics team",
}
for k, v in card.items():
print(f"{k}: {v}")Outcomes for the new month have arrived. Run the starter code to create them, then compute the model's ROC-AUC on the new month and compare it with the test-set AUC. Has drift damaged the model?
Your turn# Outcomes for the new month (same hidden pattern as before)
logit2 = (1.2 - 0.06 * new_month["tenure_months"] + 0.55 * new_month["support_tickets"]
- 0.02 * new_month["monthly_spend"] + 0.4 * new_month["on_promo"])
new_churned = (rng2.random(500) < 1 / (1 + np.exp(-logit2))).astype(int)
# Compute the AUC on new_month, then press RunShow a solution
logit2 = (1.2 - 0.06 * new_month["tenure_months"] + 0.55 * new_month["support_tickets"]
- 0.02 * new_month["monthly_spend"] + 0.4 * new_month["on_promo"])
new_churned = (rng2.random(500) < 1 / (1 + np.exp(-logit2))).astype(int)
print("Test AUC: ", round(roc_auc_score(y_test, rf.predict_proba(X_test)[:, 1]), 3))
print("New-month AUC:", round(roc_auc_score(new_churned, rf.predict_proba(new_month)[:, 1]), 3))
print("Actual churn rate, new month:", new_churned.mean().round(2))
# The ranking holds up because the underlying pattern hasn't changed, only the mix of customers.
# Drift in the inputs is a prompt to check, not proof of failure.Key takeaways
- Permutation importance shows what a model relies on — not causation.
- Check metrics for every group that matters.
- Only load model files from trusted sources.
- Monitor drift and outcomes; retrain and re-evaluate.
- Classic ML suits tabular, high-volume prediction; LLMs suit unstructured language tasks.
- Drift in the inputs is a prompt to check outcomes, not proof the model has failed.
- Baseline, leakage, test-set use, metric, groups, reproducibility: review every pipeline, whoever wrote it.