Integrated Gradients for a PyTorch network

AdvancedInterpretability & Explainable AIExplaining networks

Goal: Attributing the network's prediction to input features and checking the completeness axiom.

Python — example.py
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}")

Code explanation

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.

Requirements

Shell
pip install captum torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

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

Libraries used

Related examples