Lesson 35 of 40

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

SectionMain questionKey output
35.1 Global versus localWhat does the model do overall versus for one case?Scope of explanation
35.2 Single predictionWhich features moved this prediction?Contribution narrative
35.3 SHAP conceptsHow can Shapley-value ideas explain predictions?Local and global SHAP views
35.4 LimitationsWhen can an explanation mislead us?Interpretation safeguards
Practical labWhy 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

ScopeTypical questionExamples of methods
GlobalWhich variables matter across the dataset?Coefficients, permutation importance, partial dependence, global SHAP summaries
LocalWhy did observation 127 receive this prediction?SHAP waterfall, local contributions, local surrogate, counterfactual analysis
Cohort / subgroupWhy 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

ElementMeaningQuestion to ask
BaselineReference model outputWhat prediction would be expected before this case-specific evidence?
Positive contributionPushes the explained output upwardWhich feature values support a higher score?
Negative contributionPushes the explained output downwardWhich feature values support a lower score?
Final outputBaseline plus local contributionsDoes 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)[01]
threshold = 0.50
predicted_class = int(p_positive >= threshold)
confidence_margin = abs(p_positive - threshold)

print("Positive-class probability:"round(p_positive, 3))
print("Predicted class:", predicted_class)
print("Distance from threshold:"round(confidence_margin,  3))

 

 

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

QuestionUseful forMain caution
What minimum change crosses the threshold?Decision sensitivityMay create an infeasible observation
Which editable feature changes the score most?Operational explorationModel association is not causal effect
Would the prediction remain stable after a plausible perturbation?RobustnessPlausibility 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

TermMeaning in practice
Expected value / base valueReference output used as the starting point of the additive explanation.
SHAP valueFeature-specific contribution for one observation.
Waterfall plotLocal view showing how important contributions move from baseline to final output.
Bar / beeswarm summaryGlobal aggregation of local SHAP values across many observations.
Dependence / scatter viewShows 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

explainer = shap.TreeExplainer(model)
explanation = explainer(X_test.iloc[[row_index]])

# Modern SHAP may include one output dimension per class.
local_exp = (
    explanation[0, :, 1]
    if explanation.values.ndim == 3
    else explanation[0]
)

shap.plots.waterfall(local_exp, max_display=12)

 

 

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]
shap_values = explainer(sample)

positive_class = (
    shap_values[:, :, 1]
    if shap_values.values.ndim == 3
    else shap_values
)

shap.plots.bar(positive_class, max_display=12)
shap.plots.beeswarm(positive_class, max_display=12)

 

 

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"
shap.plots.scatter(positive_class[:, feature_name])

 

 

Computational considerations

Table 35.6. Choosing an explanation strategy

SituationPractical approach
Tree ensemblesUse a tree-aware explainer when supported.
Linear modelsUse a linear explainer or coefficient-based interpretation where appropriate.
Arbitrary black-box modelUse a model-agnostic explainer, typically with a representative background sample.
Very large datasetsExplain a representative subset rather than every observation.
Many featuresLimit 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

MistakeWhy it misleadsBetter practice
Showing only the largest positive featuresHides evidence that pushed in the opposite direction.Show both positive and negative contributions.
Omitting the baseline or output scaleMakes magnitude difficult to interpret.State the baseline, model output, class, and threshold.
Treating contribution sign as causal directionConfuses model behavior with intervention effect.Use “pushes model output” language.
Explaining only easy correct casesCreates a falsely reassuring picture.Include errors and low-confidence cases.
Ignoring implausible feature combinationsCan 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
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

data = load_breast_cancer()
= pd.DataFrame(data.data, columns=data.feature_names)
= pd.Series(data.target, name="target")

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)

print(X_train.shape, X_test.shape)
print(y_test.value_counts(normalize=True).sort_index())

 

 

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

model = RandomForestClassifier(
    n_estimators=300,
    max_depth=4,
    min_samples_leaf=4,
    random_state=42,
    n_jobs=-1,
)
model.fit(X_train, y_train)

proba = model.predict_proba(X_test)[:, 1]
pred = (proba >= 0.50).astype(int)

 

 

Step 3 — Locate the three cases

PYTHON  •  Correct, incorrect, and low-confidence observations

actual = y_test.to_numpy()
correct_candidates = np.flatnonzero(pred == actual)
incorrect_candidates = np.flatnonzero(pred != actual)

correct_idx = correct_candidates[0]
incorrect_idx = (
    incorrect_candidates[0]
    if len(incorrect_candidates)
    else None
)
low_conf_idx = int(np.argmin(np.abs(proba - 0.50)))

print("Correct row:", correct_idx)
print("Incorrect row:", incorrect_idx)
print("Low-confidence row:", low_conf_idx)

 

 

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):
    return {
        "row": idx,
        "true"int(actual[idx]),
        "predicted"int(pred[idx]),
        "p_class_1"float(proba[idx]),
        "distance_from_0.5"float(abs(proba[idx] - 0.50)),
    }

indices = [correct_idx, low_conf_idx]
if incorrect_idx is not None:
    indices.insert(1, incorrect_idx)

summary = pd.DataFrame([case_summary(i) forin indices])
print(summary.round(3))

 

 

Step 5 — Create SHAP explanations

PYTHON  •  Reusable helper for one observation

import shap

explainer = shap.TreeExplainer(model)

def local_explanation(idx):
    exp = explainer(X_test.iloc[[idx]])
    if exp.values.ndim == 3:
        return exp[0, :, 1]
    return exp[0]

correct_exp = local_explanation(correct_idx)
low_conf_exp = local_explanation(low_conf_idx)
incorrect_exp = (
    local_explanation(incorrect_idx)
    if incorrect_idx is not None
    else None
)

 

 

Step 6 — Plot the correct prediction

PYTHON  •  Explain one correct case

print(case_summary(correct_idx))
shap.plots.waterfall(correct_exp, max_display=12)

 

 

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:
    print(case_summary(incorrect_idx))
    shap.plots.waterfall(incorrect_exp, max_display=12)

 

 

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))
shap.plots.waterfall(low_conf_exp, max_display=12)

 

 

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):
    frame = pd.DataFrame({
        "feature": X_test.columns,
        "value": local_exp.data,
        "shap_value": local_exp.values,
    })
    frame["abs_shap"= frame["shap_value"].abs()
    return frame.sort_values("abs_shap", ascending=False).head(n)

print(top_contributions(low_conf_exp).round(3))

 

 

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
feature = "worst radius"
modified = X_test.iloc[[idx]].copy()

original_p = model.predict_proba(modified)[01]
modified[feature] = X_train[feature].median()
new_p = model.predict_proba(modified)[01]

print("Original probability:"round(original_p, 3))
print("Modified probability:"round(new_p, 3))
print("Change:"round(new_p - original_p, 3))

 

 

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 [17214299]:
    m = RandomForestClassifier(
        n_estimators=300, max_depth=4,
        min_samples_leaf=4, random_state=seed, n_jobs=-1
    )
    m.fit(X_train, y_train)
    p = m.predict_proba(X_test.iloc[[low_conf_idx]])[01]
    print(seed, round(p, 3))

 

 

Step 12 — Write the local explanation report

Table 35.8. Required report structure for each case

Report elementWhat students should write
Case identityCorrect, incorrect, or low-confidence; true class; predicted class; predicted probability; threshold.
Baseline / outputState the explanation baseline/output scale shown by the SHAP object or plot.
Top supporting evidenceList the strongest features pushing toward the explained class/output.
Top opposing evidenceList the strongest features pushing in the opposite direction.
Confidence interpretationExplain how far the prediction lies from the operational threshold.
LimitationsMention correlation, non-causality, data constraints, or model instability where relevant.
Recommended follow-upState 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

ConceptTakeaway
Global vs localGlobal explanations describe the model broadly; local explanations describe one prediction.
Single predictionInterpret baseline, positive/negative contributions, model output, and threshold together.
SHAPShapley-value ideas allocate the difference between a reference output and an individual prediction across features.
CounterfactualsUseful for model sensitivity, but not evidence of causality or feasibility.
LimitationsCorrelation, 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.
Train a Supervised Machine Learning Model
1 Chapter 1 — Introduction to Machine Learning 2 Chapter 2 — Understanding Supervised Learning 3 Chapter 3 — The Complete Supervised Learning Workflow 4 Chapter 4 — Defining the Machine Learning Problem 5 Chapter 5 — Loading and Inspecting Data 6 Chapter 6 — Exploratory Data Analysis 7 Chapter 7 — Cleaning the Dataset 8 Chapter 8 — Feature and Target Preparation 9 Chapter 9 — Splitting the Dataset Correctly 10 Chapter 10 — Numerical Feature Preprocessing 11 Chapter 11 — Encoding Categorical Features 12 Chapter 12 — Preprocessing Pipelines 13 Chapter 13 — Baseline Models 14 Chapter 14 — Logistic Regression 15 Chapter 15 — K-Nearest Neighbors Classification 16 Chapter 16 — Decision Tree Classification 17 Chapter 17 — Ensemble Classification Models 18 Chapter 18 — Support Vector Machines 19 Chapter 19 — Linear Regression 20 Chapter 20 — Regularized Regression 21 Chapter 21 — Tree-Based Regression 22 Chapter 22 — Confusion Matrix and Basic Metrics 23 Chapter 23 — Probability-Based Classification Evaluation 24 Chapter 24 — Regression Metrics 25 Chapter 25 — Residual Analysis 26 Chapter 26 — Underfitting and Overfitting 27 Chapter 27 — Cross-Validation 28 Chapter 28 — Feature Engineering 29 Chapter 29 — Feature Selection 30 Chapter 30 — Hyperparameter Tuning 31 Chapter 31 — Handling Imbalanced Classification 32 Chapter 32 — Designing a Fair Model Comparison 33 Chapter 33 — Final Test Evaluation 34 Chapter 34 — Global Model Interpretation 35 Chapter 35 — Local Prediction Explanation 36 Chapter 36 — Error Analysis and Robustness 37 Chapter 37 — Fairness and Ethical Considerations 38 Chapter 38 — Model Persistence 39 Chapter 39 — Building a Basic Prediction Application 40 Chapter 40 — Monitoring a Supervised Model