热力图可视化,重点权重heatmap

直接上代码吧!基于PyTorch 1.0.1:

注意一个小坑:如果PyTorch=0.4.X,代码中全部retain_graph(一共两处)要改为 retain_variables:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Grad-CAM(Gradient-weighted Class Activation Mapping)是一种可卷积神经网络(CNN)中模型对输入像的分类决策的方法。它可以根据模型的输出和梯度信息,生成一个热力,用来表示输入像中哪些区域对于模型分类结果的影响较大。 以下是使用 PyTorch 实现 Grad-CAM 热力的简单步骤: 1. 加载预训练模型,设置为 evaluation 模式。 ```python import torch import torchvision.models as models model = models.resnet18(pretrained=True) model.eval() ``` 2. 对输入像进行预处理,并将其送入模型中进行前向传播。 ```python from PIL import Image import torchvision.transforms as transforms # 加载输入像 img_path = 'example.jpg' img = Image.open(img_path) # 像预处理 preprocess = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) input_tensor = preprocess(img) input_batch = input_tensor.unsqueeze(0) # 模型预测 with torch.no_grad(): output = model(input_batch) ``` 3. 计算模型输出关于目标类别的梯度。 ```python # 目标类别的下标 target_class = 2 # 计算目标类别的梯度 model.zero_grad() output[:, target_class].backward() # 获取目标类别的输出和特征 target_output = model.features[-1].forward(input_batch) target_grads = model.features[-1].weight.grad # 计算特征上每个像素点的权重 weights = target_grads.mean(dim=(2, 3)).squeeze() ``` 4. 根据权重和特征计算 Grad-CAM 热力。 ```python import numpy as np # 取出特征 features = target_output.squeeze() # 特征上每个像素的权重乘以对应像素的值 cam = np.zeros(features.shape[1:], dtype=np.float32) for i, w in enumerate(weights): cam += w * features[i, :, :] # 对热力进行归一处理 cam = np.maximum(cam, 0) cam = cam / cam.max() # 将热力到原始像上 from matplotlib import pyplot as plt # 加载原始像 img = Image.open(img_path) # 将热力缩放到原始像的大小 cam = np.uint8(255 * cam) cam = np.array(Image.fromarray(cam).resize(img.size, resample=Image.BILINEAR)) # 叠加热力和原始heatmap = plt.get_cmap('jet')(cam)[:,:,:3] heatmap = np.float32(heatmap) heatmap = heatmap / heatmap.max() superimposed_img = heatmap + np.float32(img) superimposed_img = superimposed_img / superimposed_img.max() # 可热力和叠加后的像 fig, ax = plt.subplots(nrows=1, ncols=2) ax[0].imshow(cam, cmap='jet') ax[0].set_title('Grad-CAM heatmap') ax[1].imshow(superimposed_img) ax[1].set_title('Original image with heatmap') plt.show() ``` 这样就完成了 Grad-CAM 热力的生成和可。需要注意的是,在计算模型输出关于目标类别的梯度时,需要将模型设置为 eval 模式,并关闭 autograd 引擎的计算记录功能,以避免梯度计算对模型参数的影响。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐享时分

你觉得有价值的话再打赏谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值