gradcam

import torch
import cv2
import numpy as np
from model.unet_model import UNet
import torchvision.transforms as transforms
import torch.nn as nn
from model.u2net import fastU2NET
from model.unetpp3 import NestedUNet

def letter_box(image):
    m_width = 368
    m_height = 368
    scale_x = m_width / image.shape[1]
    scale_y = m_height / image.shape[0]
    scale   = min(scale_x, scale_y)
    M = np.array([[scale, 0, (-scale *  image.shape[1] + m_width + scale  - 1) * 0.5],
                [0, scale, (-scale *  image.shape[0] + m_height + scale  - 1) * 0.5]])
    M_T = cv2.invertAffineTransform(M)
    value=np.random.randint(0,255)
    image = cv2.warpAffine(image ,
                M,
                (m_width , m_hei
### Grad-CAM 的基本概念 Grad-CAM(Gradient-weighted Class Activation Mapping)是一种用于解释卷积神经网络 (CNN) 预测的技术。它通过可视化模型内部的特征图来帮助理解哪些部分对预测结果贡献最大[^1]。这种方法适用于任何具有卷积层的 CNN 架构,并能够生成热力图以突出显示输入图像中影响分类决策的关键区域。 #### 工作原理 Grad-CAM 利用了目标类别的梯度信息,这些梯度是从最后一层卷积层反向传播得到的。具体来说,对于给定的目标类别 \( y^c \),计算该类别相对于最后一个卷积层激活值 \( A_k \) 的梯度并取全局平均池化操作: \[ \alpha_k^{(c)} = \frac{1}{Z} \sum_{i} \sum_{j} \frac{\partial y^c}{\partial A_k(i,j)} \] 其中 \( Z \) 是空间维度大小,\( k \) 表示第 \( k \)-th 通道。接着利用加权求和的方式构建最终的热力图: \[ L_{GradCAM}^c = ReLU\left(\sum_k \alpha_k^{(c)} A_k\right) \] 此过程强调了那些显著影响特定输出类别的像素位置[^2]。 ### 实现方法 以下是基于 PyTorch 的简单实现代码片段: ```python import torch from torchvision import models, transforms from PIL import Image import matplotlib.pyplot as plt import numpy as np class GradCam: def __init__(self, model): self.model = model.eval() self.feature_maps = [] self.gradients = [] # Hook the last convolutional layer to capture feature maps and gradients. target_layer = list(self.model.children())[-2][-1] target_layer.register_forward_hook(self.save_feature_map) target_layer.register_backward_hook(self.save_gradient) def save_feature_map(self, module, input, output): self.feature_maps.append(output.detach()) def save_gradient(self, module, grad_in, grad_out): self.gradients.append(grad_out[0].detach()) def forward_pass(self, img_tensor): prediction = self.model(img_tensor.unsqueeze(0)) class_idx = torch.argmax(prediction).item() # Get predicted class index. one_hot_output = torch.zeros_like(prediction) one_hot_output[:, class_idx] = 1 self.model.zero_grad() prediction.backward(one_hot_output) return class_idx def generate_cam(self, size=(224, 224)): pooled_gradients = torch.mean(self.gradients[-1], dim=[0, 2, 3]) feature_map = self.feature_maps[-1][0] for i in range(feature_map.size()[0]): feature_map[i, :, :] *= pooled_gradients[i] heatmap = feature_map.sum(dim=0).squeeze().cpu().numpy() heatmap = np.maximum(heatmap, 0) / np.max(heatmap) heatmap = cv2.resize(heatmap, size) return heatmap # Example usage with ResNet-18 on an image file named 'example.jpg'. model = models.resnet18(pretrained=True) gradcam = GradCam(model=model) img_path = 'example.jpg' image = Image.open(img_path).convert('RGB') preprocess = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), ]) input_tensor = preprocess(image) predicted_class = gradcam.forward_pass(input_tensor) heatmap = gradcam.generate_cam() plt.imshow(image); plt.axis('off'); plt.show() plt.matshow(heatmap); plt.title(f'Heatmap for {predicted_class}'); plt.colorbar(); plt.show(); ``` 上述脚本展示了如何创建 `GradCam` 类以及调用其功能完成热力图生成的过程[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CVer儿

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值