用途
Captum 是一个基于 PyTorch 的模型可解释性库,旨在帮助研究人员和开发者理解 PyTorch 模型的预测依据。它支持包括视觉、文本等多种模态的可解释性分析。
主要能力
- 为 PyTorch 模型提供可解释性支持,覆盖视觉、文本等多种模态。
- 构建于 PyTorch 之上,兼容大多数类型的 PyTorch 模型,只需对原始神经网络做最小修改即可使用。
- 作为开源通用库,面向可解释性研究,便于实现和基准测试新算法。
使用方式
安装 Captum:
- 通过 conda(推荐):
conda install captum -c pytorch - 通过 pip:
pip install captum
创建并准备模型(官方示例):
import numpy as np
import torch
import torch.nn as nn
from captum.attr import IntegratedGradients
class ToyModel(nn.Module):
def __init__(self):
super().__init__()
self.lin1 = nn.Linear(3, 3)
self.relu = nn.ReLU()
self.lin2 = nn.Linear(3, 2)
# initialize weights and biases
self.lin1.weight = nn.Parameter(torch.arange(-4.0, 5.0).view(3, 3))
self.lin1.bias = nn.Parameter(torch.zeros(1, 3))
self.lin2.weight = nn.Parameter(torch.arange(-3.0, 3.0).view(2, 3))
self.lin2.bias = nn.Parameter(torch.ones(1, 2))
def forward(self, input):
return self.lin2(self.relu(self.lin1(input)))
model = ToyModel()
model.eval()
为了使计算可复现,固定随机种子:
torch.manual_seed(123)
np.random.seed(123)
定义输入和基线张量:
input = torch.rand(2, 3)
baseline = torch.zeros(2, 3)
选择算法实例化并应用(此例为 Integrated Gradients):
ig = IntegratedGradients(model)
attributions, delta = ig.attribute(input, baseline, target=0, return_convergence_delta=True)
print('IG Attributions:', attributions)
print('Convergence Delta:', delta)
输出示例:
IG Attributions: tensor([[-0.5922, -1.5497, -1.0067],
[ 0.0000, -0.2219, -5.1991]])
Convergence Delta: tensor([ 2.3842e-07, -4.7684e-07])
适用场景
适用于需要对 PyTorch 模型进行可解释性分析的场景,尤其是涉及视觉、文本等多模态任务的研究与开发。
限制
暂未提供更多限制说明。