Sub topic 14
Interpretability, latency, and maintenance
The earlier chapters compared models on validation scores. This chapter covers what the score leaves out. A model that wins by 0.004 AUC but takes ten times longer to serve, can't be explained to a reviewer, or breaks on every library upgrade is often the wrong choice. This chapter assumes you can fit scikit-learn pipelines, read cross-validation output, and know the model families from the previous chapters (linear, random forest, gradient boosting).
Treat constraints as requirements, not tie-breakers
Accuracy is a quantity you maximize. Constraints are limits you must meet. Write them down before you compare models, so they filter candidates and don't get used to rationalize a choice afterward.
Useful questions to ask the people who will use the model:
- Who must understand a prediction: a regulator, a customer, a domain expert, or only you?
- How fast must a prediction arrive, and how many arrive at once?
- Who will retrain and debug the model in a year, and with what tools?
Interpretability
Interpretability means different things in different settings. Separate two questions.
- Global: which features does the model rely on, and in which direction?
- Local: why did the model give this score to this row?
Models that explain themselves
A logistic regression gives one coefficient per feature. If you standardize numeric columns, coefficients are comparable in size. For one-hot columns, each coefficient is relative to the dropped or implicit baseline category, so read them with care. A shallow decision tree can be printed as rules. These models let you answer both questions directly.
Gradient boosting and random forests have no such readout. You explain them after the fact.
Post-hoc tools and their limits
Permutation importance shuffles one column in held-out data and measures how much the score drops. It works with any model and is simple to run.
Its main limitation is correlated features. If income and credit_limit carry the same signal, shuffling one leaves the other to compensate, and both look unimportant. Treat the numbers as a ranking of what the model uses, not as proof of cause.
Impurity-based importances (feature_importances_ on forests) are computed on training data. They favor high-cardinality and noisy numeric columns. Prefer permutation importance on a validation set.
Partial dependence plots and SHAP values give per-feature effect curves and per-row attributions. They add a dependency and compute cost, and they describe the model, not the world.
Constraining a flexible model
Sometimes you can keep a strong model and add a rule it must obey. HistGradientBoostingClassifier accepts monotonic_cst, which forces the prediction to rise (or fall) with a feature. For example, you can require that predicted default risk never decreases as missed_payments increases. This costs a little accuracy and removes behavior that a reviewer would reject.
Latency and size
There are two different performance questions, and they often get confused.
- Throughput: rows scored per second in a batch job. Most tree and linear models are fast here.
- Latency: time to answer one request, including feature lookup, preprocessing, and the model call.
Report latency as a percentile (p95 or p99), not an average. A model that is fast on average but occasionally stalls will still break a timeout.
Things that dominate latency in practice:
- Per-call overhead. Scoring one row with a scikit-learn pipeline costs far more than one row's share of a batch. If you serve one row at a time, measure single-row calls.
- Ensemble size. A random forest with 500 deep trees does 500 traversals per row. Gradient boosting with a few hundred shallow trees is usually smaller and faster.
- Preprocessing. One-hot encoding, imputing, and pandas overhead can cost more than the model.
- Feature retrieval. Joining a feature from a database often takes longer than any model. A more accurate model that needs an expensive extra feature may be the slower choice.
The script below is self-contained. It trains a logistic regression and a gradient-boosted model, then measures single-row latency, serialized size, and permutation importance on a held-out split.
import pickle
import time
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 2000
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 100, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
models = {
"logreg": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
"hist_gb": make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
}
for name, model in models.items():
model.fit(X_train, y_train)
# Single-row latency: time each call, report percentiles in milliseconds.
times = []
for i in range(200):
row = X_test.iloc[[i]]
start = time.perf_counter()
model.predict_proba(row)
times.append((time.perf_counter() - start) * 1000)
p50, p95 = np.percentile(times, [50, 95])
size_kb = len(pickle.dumps(model)) / 1024
print(f"{name}: p50={p50:.2f} ms, p95={p95:.2f} ms, size={size_kb:.0f} KB")
# Permutation importance on held-out data, using the raw columns.
result = permutation_importance(
model, X_test, y_test, scoring="roc_auc", n_repeats=5, random_state=0
)
for col, drop in zip(X.columns, result.importances_mean):
print(f" {col}: AUC drop {drop:.3f}")Exact timings depend on your machine, so compare the two models against each other and not against fixed numbers. Because city and age both feed the label, you should see both rank above income, which carries no signal.
Maintenance
A model is software that depends on data. Its cost comes after the first deployment.
- Retraining. How often does the data change? A model you can retrain from one script with fixed folds is cheaper to keep than one that needs manual tuning each time.
- Drift. Input distributions shift and so does the relationship between inputs and the label. Track input summaries and, when labels arrive, the live metric. Tree models do not extrapolate, so values outside the training range are clamped to the nearest leaf's behavior.
- Dependencies. Pickled scikit-learn models generally load only under the same library version that saved them. Pin versions, or store the training code and data version so you can rebuild.
- Pipeline fit. Ship preprocessing and model as one object. Separating them invites train/serve mismatches such as a different category order.
- Team skill. A model your team can debug at 2 a.m. is worth some accuracy. A neural network with custom training code may fail that test while a boosted tree usually passes.
- Missing and new categories.
HistGradientBoostingClassifierhandles missing values natively.OneHotEncoder(handle_unknown="ignore")keeps serving from crashing on unseen categories. Check what each component does with inputs it has never seen.
Common errors
- Choosing by validation score alone, then discovering the model misses the latency budget.
- Measuring latency on a batch and assuming it holds for single requests.
- Quoting impurity importances as evidence of what matters.
- Comparing accuracy gain without a spread. If the gain is smaller than the fold-to-fold standard deviation from the comparison chapter, prefer the simpler model.
- Forgetting that a constraint can be met by changing the model, for example by capping
max_iter, tree depth, or number of trees, and then re-scoring on the same folds.
A decision summary
| Situation | Reasonable lean |
|---|---|
| Regulated decision, must justify each score | Logistic regression or a shallow tree, or boosting with monotonic constraints |
| Maximum accuracy, batch scoring, no explanation needed | Gradient-boosted trees |
| Strict per-request latency on one CPU | Linear model or small boosted ensemble, measured end to end |
| Small team, frequent retraining | Simplest model within noise of the best score |
| Scores differ by less than fold standard deviation | Choose the cheaper, more explainable model |
Exercise
A gradient-boosted model scores 0.912 ROC AUC (std 0.010 across folds) and a logistic regression scores 0.906 (std 0.009) on the same folds. The product requires a reason for every prediction and a p95 latency under 20 ms. Which model do you choose, and what two measurements back your answer?
Show answer
Choose the logistic regression. The 0.006 gap is smaller than the fold-to-fold standard deviation, so the data does not show a real accuracy advantage for boosting, and the logistic model meets the explanation requirement directly through its coefficients. Back it with (1) single-row p95 latency measured end to end through the full pipeline, confirming it is under 20 ms, and (2) a check that its coefficients or permutation importances on held-out data give sensible, stable explanations. If the boosted model were required, you would instead add monotonic constraints and show its latency also meets the budget.