【python】使用grad-cam包过程中遇到的问题

grad-cam包

Crad-Cam的原理就不在这里展开,为了偷懒想要使用Pytorch中的grad-cam的类库,但是遇到了一些问题。

安装pytorch-grad-cam

在Pycharm终端进行安装

pip install grad-cam

问题1:The NVIDIA driver on your system is too old (found version 10010).

在安装之前我使用的torch版本是0.4.0,但是在安装grad-cam的过程中,由于grad-cam支持torch版本>=1.9.0.但建议是1.10.0,是比较稳定的。所以在安装过程中,torch进行了自动升版本。而我的cuda版本是10.1.在官方网站是找不到torch=1.10.0+cu101这样的搭配,但可以是torch=1.8.1+cu101.

如下操作查看自己pytorch版本和cuda版本

  1. 查看pytorch版本
import torch
print(torch.__version__)
  1. 查看cuda版本
nvidia-smi
  1. 重装pytorch+CUDA
pip3 install torch==1.8.1+cu101 torchvision==0.9.1+cu101  -f https://download.py torch.org/whl/cu101/torch_stable.html

综上所述,要使用grad-cam类库,必须满足torch>=1.10.0, cuda >=10.2否则会报错!!!

问题2: ModuleNotFoundError: No module named ‘torch.fx’

这个问题其实是上一个问题的一个延申,我自己的cuda版本是10.1,所以我就想使用torch 1.8.0+cu101的组合,但是报错了。出现这个报错的原因是,torch.fx这个模块要求torch版本大于等于1.9.0.但是cuda 10.1的版本适配的torch的最高版本是1.8.1

参考链接

链接: link.

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Guided Grad-CAM方法可以通过以下步骤实现: 1. 对输入图像进行预处理,括归一化、缩放等操作。 2. 在模型添加Guided Backpropagation模块,该模块通过反向传播特征图的梯度,并将与正激活相关的梯度保留。 3. 计算目标类别的Grad-CAM热力图,括卷积层特征图的梯度和分类器权重的结合。 4. 对Grad-CAM热力图进行平滑处理,减少噪声和不确定性,并提高可视化效果。 5. 将平滑后的Grad-CAM热力图与Guided Backpropagation模块生成的梯度结合,生成Guided Grad-CAM热力图。 6. 将Guided Grad-CAM热力图与原始图像进行叠加,可视化模型的注意力区域。 下面是一个简单的代码示例,说明如何使用Guided Grad-CAM方法可视化图像分割模型的注意力区域: ```python import torch from torchvision import models, transforms import cv2 import numpy as np # 加载模型 model = models.segmentation.deeplabv3_resnet50(pretrained=True).eval() # 定义预处理函数 preprocess = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) # 定义反向传播函数 class GuidedBackpropRelu(torch.autograd.Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return input.clamp(min=0) @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output.clone() grad_input[input < 0] = 0 return grad_input # 定义Guided Grad-CAM函数 def guided_grad_cam(img, target_class): # 转换为tensor格式 img_tensor = preprocess(img).unsqueeze(0) # 前向传播 features = model.backbone(img_tensor)['out'] output = model.classifier(features) # 计算梯度 target = output[0, target_class] target.backward() # 计算Grad-CAM热力图 grads = model.backbone.grads['out'] pooled_grads = torch.mean(grads, dim=[2, 3], keepdim=True) cams = (pooled_grads * features).sum(dim=1, keepdim=True) cams = torch.relu(cams) # 平滑Grad-CAM热力图 sigma = 0.1 cams = torch.nn.functional.conv2d(cams, torch.ones((1, 1, 3, 3)).to(device=cams.device) / 9, padding=1, groups=1) cams = torch.nn.functional.interpolate(cams, img_tensor.shape[-2:], mode='bilinear', align_corners=False) cams = cams.squeeze().cpu().numpy() cams = cv2.GaussianBlur(cams, (5, 5), sigmaX=sigma, sigmaY=sigma) cams = np.maximum(cams, 0) cams_max = cams.max() if cams_max != 0: cams /= cams_max # 计算Guided Grad-CAM热力图 gb = model.backbone.grads['out'] gb = gb.cpu().numpy()[0] cam_gb = np.zeros_like(cams) for i, w in enumerate(model.classifier.weight[target_class]): cam_gb += w * gb[i] cam_gb = cv2.resize(cam_gb, img_tensor.shape[-2:]) cam_gb = np.maximum(cam_gb, 0) cam_gb_max = cam_gb.max() if cam_gb_max != 0: cam_gb /= cam_gb_max cam_gb = cv2.cvtColor(cv2.applyColorMap(np.uint8(255 * cam_gb), cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB) # 叠加Guided Grad-CAM热力图和原始图像 img = cv2.cvtColor(np.uint8(255 * img), cv2.COLOR_RGB2BGR) cam_gb = cv2.resize(cam_gb, img.shape[:2][::-1]) result = cv2.addWeighted(img, 0.5, cam_gb, 0.5, 0) return result # 加载图像 img = cv2.imread('test.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 可视化Guided Grad-CAM result = guided_grad_cam(img, target_class=15) cv2.imshow('Guided Grad-CAM', result) cv2.waitKey() ``` 这个代码示例是使用PyTorch框架实现的,其`model`是已经训练好的图像分割模型,`preprocess`函数是预处理函数,`GuidedBackpropRelu`函数是Guided Backpropagation模块,`guided_grad_cam`函数是Guided Grad-CAM函数。你需要将模型和预处理函数替换为你自己的模型和预处理函数,然后将图像和目标类别作为输入,即可可视化Guided Grad-CAM热力图。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值