Sub topic 14
Interpretability, latency, and maintenance
This chapter assumes you can build a scikit-learn pipeline, run cross-validation, and read a table of fair model comparison scores. Accuracy decides which models are candidates. Three practical constraints often decide which one ships: how well people can understand it, how fast it predicts, and how much work it costs to keep running.
Interpretability: who needs to understand the model?
Interpretability depends on the audience. A regulator may need a reason for each decision. A product team may only need to know which features matter. Ask who will question the model, and what they will ask, before you pick a model family.
| Model | Global view | Per-prediction explanation |
|---|---|---|
| Logistic regression | Coefficients show direction and size | Each feature's contribution is a coefficient times its value |
| Shallow decision tree | The rules can be read directly | Follow one path from root to leaf |
| Random forest | Permutation importance | Needs a separate tool, such as SHAP |
| Gradient boosting | Permutation importance | Needs a separate tool, such as SHAP |
Post-hoc tools describe a model. They do not make it simple. Permutation importance, for example, shuffles one column of held-out data and measures how much the score drops.
from sklearn.inspection import permutation_importance
# Continues from earlier chapters (X, y, preprocess, cv).
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
model = make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0))
model.fit(X_tr, y_tr)
result = permutation_importance(
model, X_te, y_te, scoring="roc_auc", n_repeats=10, random_state=0
)
for name, mean in zip(X.columns, result.importances_mean):
print(f"{name}: {mean:.3f}")Because the pipeline is passed in whole, the shuffling happens on the raw columns, so you get one importance per original column, not per one-hot column.
Latency: how fast must a prediction be?
Measure latency on the real serving path, including preprocessing. Separate two cases. Batch scoring cares about throughput over millions of rows. Online scoring cares about the time for one row, often at the 95th or 99th percentile.
import time
row = X_te.iloc[[0]]
times = []
for _ in range(200):
start = time.perf_counter()
model.predict_proba(row)
times.append(time.perf_counter() - start)
times.sort()
print(f"median {times[100] * 1000:.2f} ms, p95 {times[190] * 1000:.2f} ms")Linear models and small trees predict in microseconds. A forest with hundreds of deep trees takes longer, and prediction time grows with the number of trees. Single-row calls in scikit-learn carry fixed overhead, so batch rows together when you can. Also check model size in memory, since a large forest can be hundreds of megabytes.
Maintenance: the cost after launch
A model is code plus data plus a schedule. These are the usual costs:
- Drift. Input distributions change, and scores decay. You need monitoring on inputs and on the metric once labels arrive.
- Retraining. More tuned hyperparameters and more preprocessing steps mean more that can break during a retrain.
- Dependencies. Pin library versions. A pickled model can fail to load after a scikit-learn upgrade.
- Ownership. If only one person understands the model, it is a risk.
Making the trade-off
Use the comparison scores from the previous chapter. If two models differ by less than the fold-to-fold standard deviation, the difference is noise, and the simpler model wins. If gradient boosting beats logistic regression by a wide margin, write down what the gap is worth against the extra cost, then decide.
Exercise
A random forest scores ROC AUC 0.871 +/- 0.015 across folds. Logistic regression scores 0.864 +/- 0.014. The business requires a written reason for each decision. Which model do you pick, and why?
Show answer
Logistic regression. The 0.007 gap is smaller than either fold standard deviation, so it is within noise. The reason-per-decision requirement is met directly by coefficients, while the forest would need an extra explanation tool.
Exercise
Why do you time predictions on the full pipeline instead of the final estimator alone?
Show answer
In serving, every request also passes through imputation, scaling, and encoding. Timing only the estimator hides that cost and understates real latency.