备注
点击:ref:此处 <sphx_glr_download_recipes_recipes_Captum_Recipe.py> 下载完整示例代码
使用Captum解释模型¶
Created On: Apr 14, 2020 | Last Updated: Sep 26, 2023 | Last Verified: Not Verified
Captum帮助您了解数据特征如何影响您的模型预测或神经元激活,揭示模型运作方式。
通过Captum,您可以以统一的方式应用多种最先进的特征归因算法,例如 Guided GradCam
和 Integrated Gradients
。
在本配方中,您将学习如何使用Captum:
将图像分类器的预测归因到相应的图像特征。
可视化归因结果。
在您开始之前¶
确保在当前的Python环境中已安装Captum。Captum可以在GitHub上获取,也可以通过``pip``或``conda``安装。详细安装指南请参考https://captum.ai/
对于模型,我们使用PyTorch中的内置图像分类器。Captum可以揭示支持模型做出某些预测的样本图像的哪些部分。
import torchvision
from torchvision import models, transforms
from PIL import Image
import requests
from io import BytesIO
model = torchvision.models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1).eval()
response = requests.get("https://image.freepik.com/free-photo/two-beautiful-puppies-cat-dog_58409-6024.jpg")
img = Image.open(BytesIO(response.content))
center_crop = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
])
normalize = transforms.Compose([
transforms.ToTensor(), # converts the image to a tensor with values between 0 and 1
transforms.Normalize( # normalize to follow 0-centered imagenet pixel RGB distribution
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
input_img = normalize(center_crop(img)).unsqueeze(0)
计算归因¶
模型的前三个预测类别中包括类别208和283,对应狗和猫。
让我们使用Captum的Occlusion
算法将每个预测归因到输入的相关部分。
from captum.attr import Occlusion
occlusion = Occlusion(model)
strides = (3, 9, 9) # smaller = more fine-grained attribution but slower
target=208, # Labrador index in ImageNet
sliding_window_shapes=(3,45, 45) # choose size enough to change object appearance
baselines = 0 # values to occlude the image with. 0 corresponds to gray
attribution_dog = occlusion.attribute(input_img,
strides = strides,
target=target,
sliding_window_shapes=sliding_window_shapes,
baselines=baselines)
target=283, # Persian cat index in ImageNet
attribution_cat = occlusion.attribute(input_img,
strides = strides,
target=target,
sliding_window_shapes=sliding_window_shapes,
baselines=0)
除了``Occlusion``,Captum还具有许多算法,例如Integrated Gradients
、Deconvolution
、GuidedBackprop
、Guided GradCam
、DeepLift
和GradientShap
。所有这些算法都是``Attribution``的子类,它在初始化时期望您的模型作为可调用的``forward_func``,并具有``attribute(…)``方法,返回统一格式的归因结果。
让我们在图像情况下可视化计算出的归因结果。
结果可视化¶
Captum的visualization
实用程序提供了开箱即用的方法,可视化图像和文本输入的归因结果。
import numpy as np
from captum.attr import visualization as viz
# Convert the compute attribution tensor into an image-like numpy array
attribution_dog = np.transpose(attribution_dog.squeeze().cpu().detach().numpy(), (1,2,0))
vis_types = ["heat_map", "original_image"]
vis_signs = ["all", "all"] # "positive", "negative", or "all" to show both
# positive attribution indicates that the presence of the area increases the prediction score
# negative attribution indicates distractor areas whose absence increases the score
_ = viz.visualize_image_attr_multiple(attribution_dog,
np.array(center_crop(img)),
vis_types,
vis_signs,
["attribution for dog", "image"],
show_colorbar = True
)
attribution_cat = np.transpose(attribution_cat.squeeze().cpu().detach().numpy(), (1,2,0))
_ = viz.visualize_image_attr_multiple(attribution_cat,
np.array(center_crop(img)),
["heat_map", "original_image"],
["all", "all"], # positive/negative attribution or all
["attribution for cat", "image"],
show_colorbar = True
)
如果您的数据是文本类型,``visualization.visualize_text()``提供了一个专门的视图,用于基于输入文本探索归因。详情请访问http://captum.ai/tutorials/IMDB_TorchText_Interpret
最后说明¶
Captum可以处理PyTorch中大多数模型类型,包括视觉、文本等多种模式。使用Captum,您可以:* 如上所述,将特定输出归因到模型输入。* 将特定输出归因到隐藏层神经元(请参阅Captum API参考)。* 将隐藏层神经元的响应归因到模型输入(请参阅Captum API参考)。
有关支持方法的完整API以及教程列表,请访问我们的网站http://captum.ai
Gilbert Tanner的另一个有用的帖子:https://gilberttanner.com/blog/interpreting-pytorch-models-with-captum
脚本的总运行时间: (0分钟 0.000秒)