当前位置: 首页 > news >正文

python打卡day46@浙大疏锦行

知识点回顾:

  1. 不同CNN层的特征图:不同通道的特征图
  2. 什么是注意力:注意力家族,类似于动物园,都是不同的模块,好不好试了才知道。
  3. 通道注意力:模型的定义和插入的位置
  4. 通道注意力后的特征图和热力图

内容参考

作业:

  1. 今日代码较多,理解逻辑即可
  2. 对比不同卷积层特征图可视化的结果(可选)

一、CNN特征图可视化实现

import torch
import matplotlib.pyplot as pltdef visualize_feature_maps(model, input_tensor):# 注册钩子获取中间层输出features = []def hook(module, input, output):features.append(output.detach().cpu())# 选择不同卷积层观察target_layers = [model.layer1[0].conv1,model.layer2[0].conv1,model.layer3[0].conv1]handles = []for layer in target_layers:handles.append(layer.register_forward_hook(hook))# 前向传播with torch.no_grad():_ = model(input_tensor.unsqueeze(0))# 移除钩子for handle in handles:handle.remove()# 可视化不同层特征图fig, axes = plt.subplots(len(target_layers), 5, figsize=(20, 10))for i, feat in enumerate(features):for j in range(5):  # 显示前5个通道axes[i,j].imshow(feat[0, j].numpy(), cmap='viridis')axes[i,j].axis('off')plt.show()

二、通道注意力模块示例

class ChannelAttention(nn.Module):def __init__(self, in_channels, reduction=16):super().__init__()self.avg_pool = nn.AdaptiveAvgPool2d(1)self.max_pool = nn.AdaptiveMaxPool2d(1)self.fc = nn.Sequential(nn.Linear(in_channels, in_channels // reduction),nn.ReLU(),nn.Linear(in_channels // reduction, in_channels),nn.Sigmoid())def forward(self, x):# ... existing code ...return x * attention_weights  # 应用注意力权重

三、热力图生成方法

def generate_heatmap(model, input_img):# 前向传播获取梯度model.eval()input_img.requires_grad = Trueoutput = model(input_img)pred_class = output.argmax(dim=1).item()# 反向传播计算梯度model.zero_grad()output[0, pred_class].backward()# 获取最后一个卷积层的梯度gradients = model.layer4[1].conv2.weight.gradpooled_gradients = torch.mean(gradients, dim=[0,2,3])# 生成热力图activations = model.layer4[1].conv2.activations.detach()for i in range(activations.shape[1]):activations[:,i,:,:] *= pooled_gradients[i]heatmap = torch.mean(activations, dim=1).squeeze()return heatmap

相关文章:

  • 【驱动】Orin NX恢复备份失败:does not match the current board you‘re flashing onto
  • 数列运算中的常见错因分析
  • java学习电子书推荐
  • 密码学基础——SM4算法
  • 408第一季 - 数据结构 - 栈与队列的应用
  • Cesium等高线
  • 【GESP真题解析】第 14 集 GESP 三级 2024 年 9 月编程题 1:平衡序列
  • Python打卡第46天
  • 猜字符位置游戏-position gasses
  • STM32标准库-TIM输出比较
  • SAP ABAP LOOP GROUP BY 分组循环的使用方法
  • LMG1020YFFR 电子元器件详解
  • 贝叶斯深度学习!华科大《Nat. Commun.》发表BNN重大突破!
  • 如何计算光伏工程造价预算表?
  • Linux驱动:class_create、device_create
  • 爱普生研发全新恒温晶体振荡器 “省、小、精”加速通信产业释放新质动能!
  • Dubbo学习(一):Dubbo介绍
  • 韩国IKS特价型号找游工IKS-LM-SN1G交换机
  • SpringMVC执行流程
  • Odoo 19 路线图(新功能)
  • 443是端口网站建设/超级外链吧外链代发
  • 宜昌网站建设厂家/网络营销师是做什么的
  • 河南b2c商城网站/seo网站培训优化怎么做
  • 合肥专业做公司网站/做一个企业网站大概需要多少钱
  • 如何做盗版小说网站/网站设计论文
  • wordpress分页目录编辑/成都网站快速优化排名