Ethical AI · Advanced level

Advanced level · Module 4: Explainable AI Techniques and Interpretability · Lesson 1 of 4

SHAP for Tree Models

Learners use shap.TreeExplainer on a gradient-boosted or random forest model and read global summaries, dependence plots and individual explanations.

In this lesson you will

  • Compute SHAP values for a tree ensemble
  • Interpret beeswarm, bar and dependence plots

Key concepts

TreeExplainerbeeswarm plotmean absolute SHAPdependence (scatter) plotbackground data

The lesson

Tree ensembles such as random forests and gradient boosting are common in practice because they are accurate. shap.TreeExplainer computes SHAP values for them efficiently. shap.plots.beeswarm shows the distribution of each feature's effect across all cases, and shap.plots.bar shows the mean absolute effect.

A dependence plot (shap.plots.scatter) shows how one feature's SHAP value changes with its value, coloured by another feature to reveal interactions. For example, the effect of distance to school may be larger when the student has no transport.

The choice of background data affects results. Use a representative sample of the training data and document the choice.

Step by step

  1. Train a RandomForestClassifier or HistGradientBoostingClassifier on the capstone data.
  2. Compute SHAP values with shap.TreeExplainer.
  3. Produce beeswarm, bar and one dependence plot.
  4. Write three global findings and compare them with the linear model from the Intermediate level.
Code example

Explaining one student's predicted score with SHAP

A linear model predicts a final score, and SHAP splits one student's prediction into an average starting point plus a contribution from each input.

Pythonexplain_student.py
import numpy as npimport pandas as pdimport shapfrom sklearn.linear_model import LinearRegression # Fictional records: attendance (%), homework completed (out of 10), distance to school (km)X = pd.DataFrame({    "attendance":  [95, 88, 70, 60, 92, 75, 55, 82],    "homework":    [9, 7, 5, 4, 8, 6, 3, 7],    "distance_km": [1, 3, 8, 12, 2, 6, 10, 4],})y = [78, 70, 52, 45, 74, 58, 40, 66]   # final examination score model = LinearRegression().fit(X, y)explainer = shap.LinearExplainer(model, X)   # background data = the training recordsexplanation = explainer(X.iloc[[3]])          # the fourth student print("Average prediction:", round(float(np.ravel(explanation.base_values)[0]), 1))for name, value in zip(X.columns, explanation.values[0]):    print(f"{name:12s} {value:+.1f}")print("This student's prediction:", round(float(model.predict(X.iloc[[3]])[0]), 1)) shap.plots.waterfall(explanation[0])   # draws the same breakdown as a chart

Output

Average prediction: 60.4
attendance   -11.1
homework     -3.9
distance_km  -1.0
This student's prediction: 44.4

How it works

SHAP starts from the model's average prediction over the background data (60.4) and adds one contribution per input. For a linear model with independent background data, each contribution is the coefficient multiplied by the difference between the student's value and the average value. This student's attendance (60% against an average of about 77%) lowers the prediction by about 11 points, homework (4 against about 6) by about 4, and distance by about 1. The contributions add up exactly: 60.4 - 11.1 - 3.9 - 1.0 = 44.4. In plain language: 'Your predicted score is below average mainly because of low attendance and missed homework.' The explanation describes the model, not the causes of the student's results. With only eight records, and with distance closely related to attendance, the individual coefficients are unstable; a real model needs far more data.

Key concepts

base valueadditive feature contributionsLinearExplainerwaterfall plotexplaining the model, not the person

Practice activity

Produce a SHAP global explanation pack for the capstone tree model.

Expected result: Correct plots with careful written findings, including any interaction observed.

Check your understanding

  1. What does a beeswarm plot show?

    Show answer

    The distribution of each feature's SHAP values across all cases.

  2. Why does background data matter?

    Show answer

    SHAP values are relative to the background data, so the choice changes the results.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.