Explaining a tree model with SHAP values
Finding the most influential features globally and for a single sample.
Goal: Attributing the network's prediction to input features and checking the completeness axiom.
import torch
from torch import nn
from captum.attr import IntegratedGradients
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(4, 8), nn.Tanh(), nn.Linear(8, 2)).eval()
x = torch.tensor([[1.0, -0.5, 2.0, 0.0]])
ig = IntegratedGradients(model)
attr, delta = ig.attribute(x, baselines=torch.zeros_like(x), target=1, n_steps=100,
return_convergence_delta=True)
diff = (model(x)[0, 1] - model(torch.zeros_like(x))[0, 1]).item()
print("Attributions:", [round(v, 4) for v in attr[0].tolist()])
print(f"Sum of attributions: {attr.sum().item():.4f} | output difference: {diff:.4f} | delta: {delta.abs().item():.2e}")
Gradients are integrated along a path from a baseline (zeros) to the input. The sum of the attributions approximately equals the difference between the model's output at the input and at the baseline, and convergence_delta measures the error of this approximation.
Attributions: [-0.0193, -0.0075, 0.0941, -0.0] Sum of attributions: 0.0673 | output difference: 0.0673 | delta: 0.00e+00
This example was actually run and tested on 21 November 2026 on a CPU — captum 0.9.0, torch 2.15.0, python 3.13.18
Finding the most influential features globally and for a single sample.
Finding out why the model classified a particular sample.
Showing the regions the network relied on for its decision.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.