使用LRP(Layer-wise relevance propagation)对模型进行解释

安装

  1. 安装cuda、cudnn,使用conda安装比较方便
  2. 安装pytorch
  3. 安装captum
pip install captum

LRP

参考:https://captum.ai/api/lrp.html

  1. 构建简单的图像分类网络
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from captum.attr import LRP
from captum.attr import visualization as viz

class ImageClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        # 第一层(卷积层)
        # 输入频道3, 输出频道6, 卷积3x3
        self.conv1 = nn.Conv2d(3, 6, 3)
        # 第二层(卷积层)
        # 输入频道6, 输出频道16, 卷积3x3
        self.conv2 = nn.Conv2d(6, 16, 3)
        # 第三层(全连接层)
        # 输入维度16x28x28=12544,输出维度 512
        self.fc1 = nn.Linear(16 * 28 * 28, 512)
        # 第四层(全连接层)
        # 输入维度512, 输出维度64
        self.fc2 = nn.Linear(512, 64)
        # 第五层(全连接层)
        # 输入维度64, 输出维度10
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        # 数据先经过第一层卷积层
        x = self.conv1(x)
        # 经过激活函数
        x = F.relu(x)

        # 数据经过第二层卷积层
        x = self.conv2(x)
        # 经过激活函数
        x = F.relu(x)

        # 调整数据维度,‘-1’表示自动计算维度
        x = x.view(-1, 16 * 28 * 28)
        # 数据经过第三层全连接层
        x = self.fc1(x)
        # 数据经过激活函数
        x = F.relu(x)

        # 数据经过第四层全连接层
        x = self.fc2(x)
        # 数据经过激活函数
        x = F.relu(x)

        # 数据经过第五层全连接层,输出结果
        x = self.fc3(x)

        return x
  1. 对ImageClassifier进行解析
net = ImageClassifier()
lrp = LRP(net)
img = cv2.imread('data/'+'0'+'.jpg')
transf = transforms.ToTensor()
img_tensor_1 = transf(img)
img = cv2.imread('data/'+'1'+'.jpg')
transf = transforms.ToTensor()  #将图片转换为tensor
img_tensor_2 = transf(img)
input_tensor = torch.stack((img_tensor_1, img_tensor_2),0) #将两个3*32*32拼接成2*3*32*32的数组
# Attribution size matches input size: 3x3x32x32(batch*通道数*宽*高)
attribution = lrp.attribute(input_tensor, target=5)  #目标类别是5
  1. 对结果进行可视化。由于是对一个batch进行解释的,所以要将返回的结果进行分割。
attri_img1, attri_img2 = attribution.split(1, 0) #将一个batch的tensor分割为两张图的tensor
attri_img1 = attri_img1.reshape(3,32,32) #去掉第一个维度
attri_img2 = attri_img2.reshape(3,32,32) #去掉第一个维度
print(attri_img1.size())
print(attri_img2.size())
default_cmap = LinearSegmentedColormap.from_list('custom blue',
                                                 [(0, '#ffffff'),
                                                  (0.25, '#000000'),
                                                  (1, '#000000')], N=256)
#可视化
_ = viz.visualize_image_attr(np.transpose(img_tensor_1.squeeze().cpu().detach().numpy(),(1,2,0)),
                             np.transpose(attri_img1.squeeze().cpu().detach().numpy(),(1,2,0)),
                             method='heat_map',
                             cmap=default_cmap,
                             show_colorbar=True,
                             sign='positive',
                             outlier_perc=1)
_ = viz.visualize_image_attr(np.transpose(img_tensor_2.squeeze().cpu().detach().numpy(),(1,2,0)),
                             np.transpose(attri_img2.squeeze().cpu().detach().numpy(),(1,2,0)),
                             method='heat_map',
                             cmap=default_cmap,
                             show_colorbar=True,
                             sign='positive',
                             outlier_perc=1)

原图
在这里插入图片描述
在这里插入图片描述
解释图
在这里插入图片描述
在这里插入图片描述
后续继续更新解释图和原图中的对应关系,欢迎关注

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值