Chapter 35 — Local Prediction Explanation
Explaining why a trained model produced one particular prediction — and knowing when that explanation should not be trusted.
| CHAPTER GOAL Move from global model interpretation to individual-prediction reasoning using feature contributions, SHAP values, confidence, and cautious counterfactual analysis. |
Learning objectives
- Distinguish global explanations from local explanations and choose the correct scope for a question.
- Describe an individual prediction using a baseline, positive contributions, and negative contributions.
- Explain the central idea of Shapley values and how SHAP attributes a prediction to individual features.
- Use local SHAP visualizations to investigate correct, incorrect, and low-confidence predictions.
- Apply simple counterfactual reasoning without confusing association with causality.
- Recognize the effects of correlated variables, model instability, visualization choices, and domain assumptions on explanations.
Chapter map
Table 35.1. Chapter structure
| Section | Main question | Key output |
|---|---|---|
| 35.1 Global versus local | What does the model do overall versus for one case? | Scope of explanation |
| 35.2 Single prediction | Which features moved this prediction? | Contribution narrative |
| 35.3 SHAP concepts | How can Shapley-value ideas explain predictions? | Local and global SHAP views |
| 35.4 Limitations | When can an explanation mislead us? | Interpretation safeguards |
| Practical lab | Why were three specific cases predicted this way? | Correct / incorrect / low-confidence reports |
35.1 Global versus local explanations
Global interpretation summarizes how a fitted model behaves across a population of observations. Local interpretation narrows the question to one prediction: what evidence inside the fitted model pushed this observation toward its final score or class? The two scopes answer different questions and should not be substituted for each other.
Table 35.2. Global and local explanation scopes
| Scope | Typical question | Examples of methods |
|---|---|---|
| Global | Which variables matter across the dataset? | Coefficients, permutation importance, partial dependence, global SHAP summaries |
| Local | Why did observation 127 receive this prediction? | SHAP waterfall, local contributions, local surrogate, counterfactual analysis |
| Cohort / subgroup | Why does the model behave differently for this segment? | Segmented metrics, grouped SHAP summaries, subgroup residual/error analysis |
| IMPORTANT A strong global feature does not have to dominate every individual prediction. Local evidence can differ substantially from the average pattern. |
A useful mental model
Think of the prediction as a journey from a reference value to the observation-specific output. A local explanation asks which features moved the model upward, which moved it downward, and by how much within the chosen explanation framework.
prediction = baseline + contribution₁ + contribution₂ + ··· + contributionₚ The exact output scale depends on the model and explainer: probability, log-odds, raw score, or regression value. |
35.2 Explaining a single prediction
Baseline prediction
A baseline is the reference prediction before the observation-specific feature contributions are applied. In additive explanation methods, local feature effects are interpreted relative to this reference. The baseline may be an average model output over a background dataset rather than the prevalence of the positive class itself.
Feature contributions
A local feature contribution describes how a particular feature value changes the model output relative to the baseline under the explanation method. A positive contribution pushes the explained output upward; a negative contribution pushes it downward. The sign must always be interpreted relative to the output being explained.
Table 35.3. Reading a local contribution report
| Element | Meaning | Question to ask |
|---|---|---|
| Baseline | Reference model output | What prediction would be expected before this case-specific evidence? |
| Positive contribution | Pushes the explained output upward | Which feature values support a higher score? |
| Negative contribution | Pushes the explained output downward | Which feature values support a lower score? |
| Final output | Baseline plus local contributions | Does the explanation reconcile with the model prediction? |
| CAUTION Positive does not automatically mean “good,” and negative does not automatically mean “bad.” The sign only describes movement on the model output being explained. |
Prediction confidence
For probabilistic binary classifiers, local explanation should be paired with the prediction score. A high-confidence prediction lies far from the operational threshold; a low-confidence prediction lies near it. Low confidence does not imply the explanation is wrong, but it often means small perturbations could change the predicted class.
PYTHON • Inspect a probability, class, and confidence margin p_positive = model.predict_proba(X_one)[0, 1] |
Counterfactual reasoning
Counterfactual reasoning asks how the model prediction would change if one or more input values were different while other information stayed fixed. This can reveal decision sensitivity and suggest what separates two model outcomes. However, a counterfactual input may be unrealistic, impossible, ethically inappropriate, or outside the data distribution.
Table 35.4. Counterfactual questions
| Question | Useful for | Main caution |
|---|---|---|
| What minimum change crosses the threshold? | Decision sensitivity | May create an infeasible observation |
| Which editable feature changes the score most? | Operational exploration | Model association is not causal effect |
| Would the prediction remain stable after a plausible perturbation? | Robustness | Plausibility requires domain knowledge |
| INTERPRETATION RULE A counterfactual is a statement about the model: “if the input were changed this way, the model would respond this way.” It is not proof that intervening on the real-world feature would cause the predicted outcome to change. |
35.3 SHAP concepts
SHAP (SHapley Additive exPlanations) applies ideas from cooperative game theory to model explanation. Features are treated as contributors to a prediction, and Shapley-value reasoning distributes the difference between a baseline and the explained output among those features according to their marginal contributions across feature coalitions.
f(x) ≈ E[f(X)] + Σ φⱼ φⱼ is the local SHAP contribution assigned to feature j for the explained observation. |
Shapley values
A Shapley value is based on the average marginal contribution of a feature across possible coalitions of other features. Exact enumeration becomes expensive as the number of features grows, so practical SHAP implementations use model-specific algorithms or approximations.
Table 35.5. SHAP vocabulary
| Term | Meaning in practice |
|---|---|
| Expected value / base value | Reference output used as the starting point of the additive explanation. |
| SHAP value | Feature-specific contribution for one observation. |
| Waterfall plot | Local view showing how important contributions move from baseline to final output. |
| Bar / beeswarm summary | Global aggregation of local SHAP values across many observations. |
| Dependence / scatter view | Shows how a feature value relates to its SHAP contribution across observations. |
Local contribution
For a single observation, a waterfall plot is especially useful because it explicitly connects the baseline to the model output. Students should read the largest absolute contributions first, verify their direction, and then connect the feature values to domain expectations.
PYTHON • Basic SHAP workflow for a tree classifier import shap |
| VERSION NOTE SHAP output shapes can differ by model type and library version. Always inspect `explanation.values.shape` before indexing a class-specific output. |
Global summaries from local explanations
Local SHAP values can also be aggregated across many observations. Mean absolute SHAP values provide a global importance summary, while beeswarm plots preserve both contribution magnitude and direction. This links local and global interpretation: the global view is built from many local explanations.
PYTHON • Create global SHAP summaries from many local explanations sample = X_test.iloc[:100] |
Dependence plots
A SHAP dependence or scatter plot relates a feature value to its local contribution across observations. It can reveal nonlinear patterns and possible interactions. The vertical axis is an explanation contribution, not the observed target, and the pattern remains model-dependent.
PYTHON • Inspect the contribution pattern for one feature feature_name = "worst radius" |
Computational considerations
Table 35.6. Choosing an explanation strategy
| Situation | Practical approach |
|---|---|
| Tree ensembles | Use a tree-aware explainer when supported. |
| Linear models | Use a linear explainer or coefficient-based interpretation where appropriate. |
| Arbitrary black-box model | Use a model-agnostic explainer, typically with a representative background sample. |
| Very large datasets | Explain a representative subset rather than every observation. |
| Many features | Limit displayed features, but retain the remaining contribution in an “other features” total when the plot supports it. |
35.4 Explanation limitations
Explanation is not causality
Local explanation describes how the fitted model transforms the supplied input into an output. It does not establish that the important feature causes the real-world outcome. Causal claims require a causal design, assumptions, and domain evidence beyond predictive explanation.
Correlated features
When features carry overlapping information, attribution can be distributed in unintuitive ways. Two highly correlated variables may share credit, one may dominate depending on the model, or the explanation method may depend strongly on how missing-feature coalitions are represented.
| CORRELATED-FEATURE WARNING Do not interpret a small local contribution as proof that a correlated feature is unimportant. The model may obtain similar information from another predictor. |
Model instability
An explanation is only as stable as the fitted model. If small changes in training data produce very different models, local explanations can also change. Explanation stability should therefore be considered alongside prediction stability, especially for borderline observations.
Misleading visualizations
Table 35.7. Common explanation mistakes
| Mistake | Why it misleads | Better practice |
|---|---|---|
| Showing only the largest positive features | Hides evidence that pushed in the opposite direction. | Show both positive and negative contributions. |
| Omitting the baseline or output scale | Makes magnitude difficult to interpret. | State the baseline, model output, class, and threshold. |
| Treating contribution sign as causal direction | Confuses model behavior with intervention effect. | Use “pushes model output” language. |
| Explaining only easy correct cases | Creates a falsely reassuring picture. | Include errors and low-confidence cases. |
| Ignoring implausible feature combinations | Can make counterfactuals unrealistic. | Validate feasibility with domain constraints. |
Domain validation
A technically correct explanation can still be operationally misleading. Domain experts should verify that influential features are available at prediction time, have valid definitions, are not proxies for forbidden information, and behave plausibly for the intended population.
| BEST PRACTICE Pair every important local explanation with four checks: data validity, prediction-time availability, domain plausibility, and consistency with the model’s documented use conditions. |
Practical lab — Explain three individual predictions
Goal: train one classifier, identify three diagnostically different test observations, and create a local explanation report for each: one correct prediction, one incorrect prediction, and one low-confidence prediction. The same model and explanation method must be used for all three cases so differences come from the observations rather than from the analysis procedure.
Step 1 — Load the data and create a protected test set
PYTHON • Breast Cancer Wisconsin dataset import numpy as np |
| LAB CONTEXT This dataset is used only as an educational machine-learning example. Local explanations must not be interpreted as clinical advice or causal medical evidence. |
Step 2 — Train a deliberately interpretable-size Random Forest
PYTHON • Fit the classifier and obtain test probabilities from sklearn.ensemble import RandomForestClassifier |
Step 3 — Locate the three cases
PYTHON • Correct, incorrect, and low-confidence observations actual = y_test.to_numpy() |
| IF NO ERROR OCCURS If this particular split produces no incorrect prediction, reduce `max_depth`, change the random split seed, or select another previously evaluated model. Do not fabricate an error case. |
Step 4 — Build a compact case table
PYTHON • Summarize truth, prediction, and confidence def case_summary(idx): |
Step 5 — Create SHAP explanations
PYTHON • Reusable helper for one observation import shap |
Step 6 — Plot the correct prediction
PYTHON • Explain one correct case print(case_summary(correct_idx)) |
Student interpretation prompts:
- Which three features have the largest absolute contributions?
- Which contributions push toward class 1 and which push away from it?
- Is the prediction far from or close to the 0.50 threshold?
- Do the dominant feature values look plausible for the fitted model and dataset?
Step 7 — Plot the incorrect prediction
PYTHON • Explain one error case if incorrect_exp is not None: |
The goal is not to “justify” the error. Instead, identify what evidence the model relied on, what evidence opposed the final output, whether correlated variables may have shared attribution, and whether this observation lies in a difficult part of feature space.
Step 8 — Plot the low-confidence prediction
PYTHON • Explain the observation closest to the threshold print(case_summary(low_conf_idx)) |
A low-confidence case often contains competing contributions: some features push the score upward while others push it downward. Students should explicitly connect this contribution balance to the small distance from the decision threshold.
Step 9 — Inspect the strongest local contributions as a table
PYTHON • Rank contributions by absolute magnitude def top_contributions(local_exp, n=8): |
Step 10 — Perform cautious counterfactual reasoning
Choose one feature with a strong contribution. Replace it with a plausible value drawn from the training distribution, recompute the model probability, and describe how the model changes. This is a sensitivity experiment, not a causal recommendation.
PYTHON • Simple one-feature sensitivity experiment idx = low_conf_idx |
| COUNTERFACTUAL CAUTION Changing one measurement while freezing all correlated measurements can create an unrealistic record. Use this exercise to inspect model sensitivity, then discuss feasibility and correlation before drawing conclusions. |
Step 11 — Compare explanation stability
Optional extension: refit the Random Forest with several random seeds and repeat the explanation for the low-confidence observation. Record whether the prediction and top local features remain similar. Large changes indicate that the local explanation is sensitive to model instability.
PYTHON • Optional prediction-stability check for seed in [1, 7, 21, 42, 99]: |
Step 12 — Write the local explanation report
Table 35.8. Required report structure for each case
| Report element | What students should write |
|---|---|
| Case identity | Correct, incorrect, or low-confidence; true class; predicted class; predicted probability; threshold. |
| Baseline / output | State the explanation baseline/output scale shown by the SHAP object or plot. |
| Top supporting evidence | List the strongest features pushing toward the explained class/output. |
| Top opposing evidence | List the strongest features pushing in the opposite direction. |
| Confidence interpretation | Explain how far the prediction lies from the operational threshold. |
| Limitations | Mention correlation, non-causality, data constraints, or model instability where relevant. |
| Recommended follow-up | State whether the case suggests model debugging, data review, threshold review, or no immediate change. |
Discussion questions
1. Why can the same globally important feature have a small SHAP value for one observation?
2. What does an incorrect prediction reveal that a correct prediction may hide?
3. Why are low-confidence predictions especially useful for robustness analysis?
4. How could correlated features change the apparent ranking of local contributions?
5. Why is a model counterfactual not automatically an actionable real-world recommendation?
6. Which information should accompany a waterfall plot in a formal report?
Chapter summary
Table 35.9. Key takeaways
| Concept | Takeaway |
|---|---|
| Global vs local | Global explanations describe the model broadly; local explanations describe one prediction. |
| Single prediction | Interpret baseline, positive/negative contributions, model output, and threshold together. |
| SHAP | Shapley-value ideas allocate the difference between a reference output and an individual prediction across features. |
| Counterfactuals | Useful for model sensitivity, but not evidence of causality or feasibility. |
| Limitations | Correlation, model instability, visualization choices, and domain assumptions can all change interpretation. |
| GOOD PRACTICE / NEXT STEP Explain correct, incorrect, and low-confidence cases rather than presenting only favorable examples. Local explanations help diagnose individual decisions. The next stage is to combine explanation evidence with monitoring, documentation, governance, and responsible model deployment practices. |