使用GradCAM对vision transformer进行注意力可视化的过程中遇到的问题记载

0.pip install grad-cam

1.首先是跑了其他一些博主的帖子,都没跑通,最后在知乎上找到的这篇帖子,修改了图片的输入设置后跑通了,实例代码如下

bash 复制代码
import cv2
import numpy as np
import torch

from pytorch_grad_cam import GradCAM, \
                            ScoreCAM, \
                            GradCAMPlusPlus, \
                            AblationCAM, \
                            XGradCAM, \
                            EigenCAM, \
                            EigenGradCAM, \
                            LayerCAM, \
                            FullGrad

from pytorch_grad_cam import GuidedBackpropReLUModel
from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image

# 加载预训练的 ViT 模型
model = torch.hub.load('facebookresearch/deit:main','deit_tiny_patch16_224', pretrained=True)
model.eval()

# 判断是否使用 GPU 加速
use_cuda = torch.cuda.is_available()
if use_cuda:
    model = model.cuda()

def reshape_transform(tensor, height=14, width=14):
    # 去掉cls token
    result = tensor[:, 1:, :].reshape(tensor.size(0),
    height, width, tensor.size(2))

    # 将通道维度放到第一个位置
    result = result.transpose(2, 3).transpose(1, 2)
    return result

# 创建 GradCAM 对象
cam = GradCAM(model=model,
            target_layers=[model.blocks[-1].norm1],
            # 这里的target_layer要看模型情况,
            # 比如还有可能是:target_layers = [model.blocks[-1].ffn.norm]
            use_cuda=use_cuda,
            reshape_transform=reshape_transform)

# 读取输入图像
image_path = "2.png"
rgb_img = cv2.imread(image_path, 1)[:, :, ::-1]
rgb_img = cv2.resize(rgb_img, (224, 224))
rgb_img = np.float32(rgb_img) / 255.0

# 预处理图像
input_tensor = preprocess_image(rgb_img,
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])

# 看情况将图像转换为批量形式
# input_tensor = input_tensor.unsqueeze(0)
if use_cuda:
    input_tensor = input_tensor.cuda()

# 计算 grad-cam
target_category = None # 可以指定一个类别,或者使用 None 表示最高概率的类别
grayscale_cam = cam(input_tensor=input_tensor, targets=target_category)
grayscale_cam = grayscale_cam[0, :]

# 将 grad-cam 的输出叠加到原始图像上
visualization = show_cam_on_image(rgb_img, grayscale_cam)

# 保存可视化结果
cv2.cvtColor(visualization, cv2.COLOR_RGB2BGR, visualization)
cv2.imwrite('cam3.jpg', visualization)

参考链接:

bash 复制代码
https://zhuanlan.zhihu.com/p/640450435

2.接下来参考了这位大佬的博客,针对我的网络进行修改,一些遇到的错误在大佬在里面说了

bash 复制代码
https://blog.csdn.net/holly_Z_P_F/article/details/130011296

3.新的问题

AttributeError: 'NoneType' object has no attribute 'shape'

bash 复制代码
Traceback (most recent call last):
  File "D:\yanjiusheng\ZSE-SBIR\kk.py", line 68, in <module>
    test()
  File "D:\yanjiusheng\ZSE-SBIR\kk.py", line 56, in test
    grayscale_cam = cam(input_tensor=input_tensor, targets=target_category)
  File "D:\anaconda3\envs\zse-sbir\lib\site-packages\pytorch_grad_cam\base_cam.py", line 186, in __call__
    return self.forward(input_tensor, targets, eigen_smooth)
  File "D:\anaconda3\envs\zse-sbir\lib\site-packages\pytorch_grad_cam\base_cam.py", line 110, in forward
    cam_per_layer = self.compute_cam_per_layer(input_tensor, targets, eigen_smooth)
  File "D:\anaconda3\envs\zse-sbir\lib\site-packages\pytorch_grad_cam\base_cam.py", line 141, in compute_cam_per_layer
    cam = self.get_cam_image(input_tensor, target_layer, targets, layer_activations, layer_grads, eigen_smooth)
  File "D:\anaconda3\envs\zse-sbir\lib\site-packages\pytorch_grad_cam\base_cam.py", line 66, in get_cam_image
    weights = self.get_cam_weights(input_tensor, target_layer, targets, activations, grads)
  File "D:\anaconda3\envs\zse-sbir\lib\site-packages\pytorch_grad_cam\grad_cam.py", line 23, in get_cam_weights
    if len(grads.shape) == 4:
AttributeError: 'NoneType' object has no attribute 'shape'

这个问题我最后解决也是一知半解做出来了,目标层的问题:GradCAM 需要一个可以计算梯度的层作为 target_layer,通常是卷积层或自注意力机制中的特定部分,我原来选择的是model.sa.model.transformer.layers[-1] 作为目标层,但是这可能并不是一个适合用于 GradCAM 的层。我选择了原来目标层下更具体的一层,即model.sa.model.transformer.layers[-1][0].layer_norm_input ,兄弟们可以 print(model) 看下结构,多试几层看看哪层能用,我太菜了只能试。。。

参考的另外一些帖子:

bash 复制代码
https://ask.csdn.net/questions/8051598
bash 复制代码
https://github.com/open-mmlab/mmdetection/issues/1809
相关推荐
WPG大大通17 分钟前
有奖直播 | onsemi IPM 助力汽车电气革命及电子化时代冷热管理
大数据·人工智能·汽车·方案·电气·大大通·研讨会
百锦再19 分钟前
AI对汽车行业的冲击和比亚迪新能源汽车市场占比
人工智能·汽车
ws20190722 分钟前
抓机遇,促发展——2025第十二届广州国际汽车零部件加工技术及汽车模具展览会
大数据·人工智能·汽车
Zhangci]26 分钟前
Opencv图像预处理(三)
人工智能·opencv·计算机视觉
新加坡内哥谈技术43 分钟前
口哨声、歌声、boing声和biotwang声:用AI识别鲸鱼叫声
人工智能·自然语言处理
wx7408513261 小时前
小琳AI课堂:机器学习
人工智能·机器学习
FL16238631291 小时前
[数据集][目标检测]车油口挡板开关闭合检测数据集VOC+YOLO格式138张2类别
人工智能·yolo·目标检测
YesPMP平台官方1 小时前
AI+教育|拥抱AI智能科技,让课堂更生动高效
人工智能·科技·ai·数据分析·软件开发·教育
FL16238631291 小时前
AI健身体能测试之基于paddlehub实现引体向上计数个数统计
人工智能
黑客-雨2 小时前
构建你的AI职业生涯:从基础知识到专业实践的路线图
人工智能·产品经理·ai大模型·ai产品经理·大模型学习·大模型入门·大模型教程