pytorch 神经网络特征可视化

news/2024/5/5 2:39:58/文章来源:https://blog.csdn.net/m0_61899108/article/details/127340090

可参考博客

Pytorch可视化模型任意中间层的类激活热力图(Grad-CAM)_潜行隐耀的博客-CSDN博客_pytorch热力图

Pytorch输出网络中间层特征可视化_Joker-Tong的博客-CSDN博客_输出网络中间特征图

GitHub - utkuozbulak/pytorch-cnn-visualizations: Pytorch implementation of convolutional neural network visualization techniques

keras可视化中间层特征_joyce_peng的博客-CSDN博客_中间层特征可视化

图像处理特征可视化方法总结(特征图、卷积核、类可视化CAM)

神经网络之特征图可视化_AI bro的博客-CSDN博客_特征图的可视化

PyTorch模型训练特征图可视化(TensorboardX) - 知乎

图像特征可视化方法总结

(1)特征图可视化

        特征图可视化有两类方法,一类是直接将某一层的feature map映射到0-255的范围,变成图像。另一类是使用一个预训练的反卷积网络(反卷积、反池化)将feature map变成图像,从而达到可视化feature map的目的。

(2)卷积核可视化

    卷积的过程就是特征提取的过程,每一个卷积核代表着一种特征。如果图像中某块区域与某个卷积核的结果越大,那么该区域就越“像”该卷积核。基于以上的推论,如果我们找到一张图像,能够使得这张图像对某个卷积核的输出最大,那么我们就说找到了该卷积核最感兴趣的图像。

(3)类别激活可视化(Class Activation Mapping,CAM)

    CAM(Class Activation Mapping,类别激活映射图),亦称为类别热力图或显著性图。它的大小与原图一致,像素值表示原始图片的对应区域对预测输出的影响程度,值越大贡献越大。目前常用的CAM系列包括:CAM、Grad-CAM、Grad-CAM++。

(4)注意力特征可视化

    与CAM类似,只不过每个特征图所占权重来自于注意力,而不是最后层的全连接,基于注意力的特征可视化方法近年有比较多的研究。

(5)一些技术工具

    tensorflow框架提供了模型和特征可视化的工具tensorboard,可使用pytorch框架引入。

tfrom torch.utils.tensorboard import SummaryWriter

更多使用细节参考PyTorch模型训练特征图可视化(TensorboardX) - 知乎

github代码

GitHub - utkuozbulak/pytorch-cnn-visualizations: Pytorch implementation of convolutional neural network visualization techniques

  • Gradient visualization with vanilla backpropagation
  • Gradient visualization with guided backpropagation [1]
  • Gradient visualization with saliency maps [4]
  • Gradient-weighted class activation mapping [3] (Generalization of [2])
  • Guided, gradient-weighted class activation mapping [3]
  • Score-weighted class activation mapping [15] (Gradient-free generalization of [2])
  • Element-wise gradient-weighted class activation mapping [16]
  • Smooth grad [8]
  • CNN filter visualization [9]
  • Inverted image representations [5]
  • Deep dream [10]
  • Class specific image generation [4] [14]
  • Grad times image [12]
  • Integrated gradients [13]
  • Layerwise relevance propagation [17]

 

GitHub - ZhugeKongan/TorchCAM: CAM', 'ScoreCAM', 'SSCAM', 'ISCAM' 'GradCAM', 'GradCAMpp', 'SmoothGradCAMpp', 'XGradCAM', 'LayerCAM' using by PyTorch.

下载包:

# python >= 3.6# Stable release
# You can install the last stable release of the package using pypi as follows:
pip install torchcam# or using conda:
conda install -c frgfm torchcam# Developer installation
# Alternatively, if you wish to use the latest features of the project that haven't made their way to a release yet, you can install the package from source:
git clone https://github.com/frgfm/torch-cam.git
pip install -e torch-cam/.

使用:

# CAM
# Learning Deep Features for Discriminative Localization: the original CAM paper
# https://arxiv.org/abs/1512.04150from torchvision.models import resnet18
from torchcam.cams import CAM
model = resnet18(pretrained=True).eval()
cam = CAM(model, 'layer4', 'fc')
with torch.no_grad(): out = model(input_tensor)
cam(class_idx=100)#Please note that by default, the layer at which the CAM is retrieved is set to the last non-reduced convolutional layer. If you wish to investigate a specific layer, use the target_layer argument in the constructor.# ScoreCAM
# paper:Score-CAM:Score-Weighted Visual Explanations for Convolutional Neural Networks
# https://arxiv.org/pdf/1910.01279.pdffrom torchvision.models import resnet18
from torchcam.cams import ScoreCAM
model = resnet18(pretrained=True).eval()
cam = ScoreCAM(model, 'layer4', 'fc')
with torch.no_grad(): out = model(input_tensor)
cam(class_idx=100)# SSCAM
# paper:SS-CAM: Smoothed Score-CAM for Sharper Visual Feature Localization
# https://arxiv.org/pdf/2006.14255.pdffrom torchvision.models import resnet18
from torchcam.cams import SSCAM
model = resnet18(pretrained=True).eval()
cam = SSCAM(model, 'layer4', 'fc')
with torch.no_grad(): out = model(input_tensor)
cam(class_idx=100)# ISCAM
# paper:IS-CAM: Integrated Score-CAM for axiomatic-based explanations
# https://arxiv.org/pdf/2010.03023.pdffrom torchvision.models import resnet18
from torchcam.cams import ISCAM
model = resnet18(pretrained=True).eval()
cam = ISCAM(model, 'layer4', 'fc')
with torch.no_grad(): out = model(input_tensor)
cam(class_idx=100)# GradCAM
# paper:Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization
# https://arxiv.org/pdf/1610.02391.pdffrom torchvision.models import resnet18
from torchcam.cams import GradCAM
model = resnet18(pretrained=True).eval()
cam = GradCAM(model, 'layer4')
scores = model(input_tensor)
cam(class_idx=100, scores=scores)# Grad-CAM++
# paper:Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks
# https://arxiv.org/pdf/1710.11063.pdffrom torchvision.models import resnet18
from torchcam.cams import  GradCAMpp
model = resnet18(pretrained=True).eval()
cam =  GradCAMpp(model, 'layer4')
scores = model(input_tensor)
cam(class_idx=100, scores=scores)# Smooth Grad-CAM++
# paper:Smooth Grad-CAM++: An Enhanced Inference Level Visualization Technique for Deep Convolutional Neural Network Models
# https://arxiv.org/pdf/1908.01224.pdffrom torchvision.models import resnet18
from torchcam.cams import SmoothGradCAMpp
model = resnet18(pretrained=True).eval()
cam = SmoothGradCAMpp(model, 'layer4')
scores = model(input_tensor)
cam(class_idx=100, scores=scores)# XGradCAM
# paper:Axiom-based Grad-CAM: Towards Accurate Visualization and Explanation of CNNs
# https://arxiv.org/pdf/2008.02312.pdffrom torchvision.models import resnet18
from torchcam.cams import XGradCAM
model = resnet18(pretrained=True).eval()
cam = XGradCAM(model, 'layer4')
scores = model(input_tensor)
cam(class_idx=100, scores=scores)# LayerCAM
# paper:LayerCAM: Exploring Hierarchical Class Activation Maps for Localization
# http://mmcheng.net/mftp/Papers/21TIP_LayerCAM.pdffrom torchvision.models import resnet18
from torchcam.cams import LayerCAM
model = resnet18(pretrained=True).eval()
cam = LayerCAM(model, 'layer4')
scores = model(input_tensor)
cam(class_idx=100, scores=scores)# Retrieving the class activation map
# Once your CAM extractor is set, you only need to use your model to infer on your data as usual. If any additional information is required, the extractor will get it for you automatically.from torchvision.io.image import read_image
from torchvision.transforms.functional import normalize, resize, to_pil_image
from torchvision.models import resnet18
from torchcam.cams import SmoothGradCAMppmodel = resnet18(pretrained=True).eval()
cam_extractor = SmoothGradCAMpp(model)
# Get your input
img = read_image("path/to/your/image.png")
# Preprocess it for your chosen model
input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])# Preprocess your data and feed it to the model
out = model(input_tensor.unsqueeze(0))
# Retrieve the CAM by passing the class index and the model output
activation_map = cam_extractor(out.squeeze(0).argmax().item(), out)# If you want to visualize your heatmap, you only need to cast the CAM to a numpy ndarray:import matplotlib.pyplot as plt
# Visualize the raw CAM
plt.imshow(activation_map.numpy()); plt.axis('off'); plt.tight_layout(); plt.show()# Or if you wish to overlay it on your input image:import matplotlib.pyplot as plt
from torchcam.utils import overlay_mask# Resize the CAM and overlay it
result = overlay_mask(to_pil_image(img), to_pil_image(activation_map, mode='F'), alpha=0.5)
# Display it
plt.imshow(result); plt.axis('off'); plt.tight_layout(); plt.show()

可视化heatmap或者叠加原图:

# Retrieving the class activation map
# Once your CAM extractor is set, you only need to use your model to infer on your data as usual. If any additional information is required, the extractor will get it for you automatically.from torchvision.io.image import read_image
from torchvision.transforms.functional import normalize, resize, to_pil_image
from torchvision.models import resnet18
from torchcam.cams import SmoothGradCAMppmodel = resnet18(pretrained=True).eval()
cam_extractor = SmoothGradCAMpp(model)
# Get your input
img = read_image("path/to/your/image.png")
# Preprocess it for your chosen model
input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])# Preprocess your data and feed it to the model
out = model(input_tensor.unsqueeze(0))
# Retrieve the CAM by passing the class index and the model output
activation_map = cam_extractor(out.squeeze(0).argmax().item(), out)# If you want to visualize your heatmap, you only need to cast the CAM to a numpy ndarray:import matplotlib.pyplot as plt
# Visualize the raw CAM
plt.imshow(activation_map.numpy()); plt.axis('off'); plt.tight_layout(); plt.show()# Or if you wish to overlay it on your input image:import matplotlib.pyplot as plt
from torchcam.utils import overlay_mask
# Resize the CAM and overlay it
result = overlay_mask(to_pil_image(img), to_pil_image(activation_map, mode='F'), alpha=0.5)
# Display it
plt.imshow(result); plt.axis('off'); plt.tight_layout(); plt.show()

 CAM Zoo:

This project is developed and maintained by the repo owner, but the implementation was based on the following research papers:

  • Learning Deep Features for Discriminative Localization: the original CAM paper
  • Grad-CAM: GradCAM paper, generalizing CAM to models without global average pooling.
  • Grad-CAM++: improvement of GradCAM++ for more accurate pixel-level contribution to the activation.
  • Smooth Grad-CAM++: SmoothGrad mechanism coupled with GradCAM.
  • Score-CAM: score-weighting of class activation for better interpretability.
  • SS-CAM: SmoothGrad mechanism coupled with Score-CAM.
  • IS-CAM: integration-based variant of Score-CAM.
  • XGrad-CAM: improved version of Grad-CAM in terms of sensitivity and conservation.
  • Layer-CAM: Grad-CAM alternative leveraging pixel-wise contribution of the gradient to the activation.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_24006.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

浅谈IT系统性能优化

一个刚上线的IT系统,往往负载压力不大,所以不会存在什么性能问题。这时,人们大多只关心系统的功能性和用户体验。但是,随着时间推移,用户量和数据量都比刚上线的时候要多很多,高并发和大数据场景下,系统遇到性能瓶颈,持续不能改善最终导致系统崩溃。这对于做C端的开发人…

<Python的变量创建与使用>——《Python》

目录 1.常量和表达式 2.变量和类型 3.变量的语法 后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教! …

python语言思想

python语言基础与应用 超级计算器 python语言解释器 为啥选用PYCHARM create new project: NANE 选择解释器 open ,选择打开文件或者加入project 注意对齐与缩进 注意字母大小写、空格 注意左右括号配对 错误是常见的,跟BUG和缺陷斗争得到过程 观察代…

08 字符串连接符 “+“ 导致的 check cast 的省略

前言 // 年轻时候,到了冬天,家人让你穿秋裤,你不仅不穿秋裤,还露着脚脖子,如果有人劝你,你会嫌他唠叨。而等你岁数大一点,天气一冷,身体受不了,就自觉把秋裤穿上了。 呵…

图论二分图问题讲解-染色法和匈牙利算法

二分图 概述: 二分图又称作二部图,是图论中的一种特殊模型。 设G(V,E)是一个无向图,如果顶点V可分割为两个互不相交的子集(A,B),并且图中的每条边(i,j)所关联的两个顶点i和j分别属于这两个不同的…

使用Python将微信和支付宝账单导入随手记

简介 本文介绍如何使用Python将微信和支付宝账单转换为可以导入随手记的文件,实现微信和支付宝账单的批量导入。 需求: 1、需要将支付宝和微信上的支出账单自动或半自动地导入到随手记中 已知信息: 1、支付宝和微信的app端都可以导出csv…

引导过程与服务控制

目录: 1、引导过程总览 2、备份与恢复第一块硬盘前512字节 3、修复GRUB引导故障 4、忘记密码 5、开关系统服务控制Linux操作系统引导过程引导过程总览: 开机自检→MBR引导→GRUB菜单→加载内核→init进程初始化 1、bios 检查硬件设置grub功能和组成 bootloader:引导加载器,…

npm install ,npm ERR code 401 Incorrect or missing password 错误原因与.npmrc 配置文件的使用

前言:前端去维护项目时,通过 git clone 下来以后,经常是直接 npm install 去安装项目需要的 node_modules ,但是往往很多项目不是我们自己写的,或者从 GitHub 上面 clone 的开源项目,这个时候出现问题就很难…

【ASM】字节码操作 转换已有的类 ClassReader 删除方法 添加方法

文章目录 1.概述2.案例2.1 删除方法2.2 添加方法2.3小总结3.总结1.概述 上一篇文章:【ASM】字节码操作 转换已有的类 ClassReader 修改字段信息 删除字段 增加字段 在上一篇文章中我们学到了如何添加字段与删除字段。 本章节我们来尝试修改方法和删除方法。 2.案例 2.1 删…

搜索查找类

查找搜索类\color{blue}{\huge{查找搜索类}}查找搜索类 find find指令从指定目录向下递归地便利各个子目录,如果在/root目录下进行寻找,根据文件目录的树状结构,就是进行全盘查找,非常浪费时间,所以使用find 进行寻找…

MATLAB | 绘图复刻(二) | 折线图+误差棒+柱状图+散点抖动+灰色背景+图片叠加

看到gzh R语言ggplot2科研绘图发布了一篇绘图复刻类文章,复刻了: Nature(IF49.962)文章(Gut microbiota modulates weight gain in mice after discontinued smoke exposure)其中的Figure.1b,绘制效果十分惊艳,手痒就想拿MATLAB也…

RocketMQ 消费者Rebalance算法 解析——图解、源码级解析

🍊 Java学习:Java从入门到精通总结 🍊 深入浅出RocketMQ设计思想:深入浅出RocketMQ设计思想 🍊 绝对不一样的职场干货:大厂最佳实践经验指南 📆 最近更新:2022年10月15日 &#…

(附源码)计算机毕业设计大学生网上书店

项目运行 环境配置: Jdk1.8 Tomcat7.0 Mysql HBuilderX(Webstorm也行) Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。 项目技术: SSM mybatis Maven Vue 等等组成,B/S模式 M…

(附源码)计算机毕业设计电脑外设销售系统小程序

项目运行 环境配置: Jdk1.8 Tomcat7.0 Mysql HBuilderX(Webstorm也行) Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。 项目技术: SSM mybatis Maven Vue 等等组成,B/S模式 M…

操作系统基本功能(操作系统)

目录 一、处理机管理 二、存储器管理 三、设备管理 四、文件管理 五、作业管理 一、处理机管理 中央处理机(CPU)是计算机系统中一个举足轻重的资源。用户程序进入内存后,只有获得CPU,才能真正得以运行。 为了提高CPU的利用率…

前端都应该了解的 NodeJs 知识及原理浅析

node.js 初探 Node.js 是一个 JS 的服务端运行环境,简单的来说,它是在 JS 语言规范的基础上,封装了一些服务端的运行时对象,让我们能够简单实现非常多的业务功能。 如果我们只使用 JS 的话,实际上只是能进行一些简单…

docker mysql8使用SSL及使用openssl生成自定义证书

《docker安装MySQL8》 修改my.cnf vi /docker_data/mysql/conf/my.cnf[client] default-character-setutf8mb4 [mysql] default-character-setutf8mb4 [mysqld] character-set-serverutf8mb4 default_authentication_pluginmysql_native_password #增加ssl ssl保存&#xff0…

【让你从0到1学会c语言】文件操作

作者:喜欢猫咪的的程序员 专栏:《C语言》 喜欢的话:世间因为少年的挺身而出,而更加瑰丽。 ——《人民日报》 目录 什么是文件: 我们为什么要使用文件呢? 文件分类&#x…

rbf神经网络和bp神经网络,rbf神经网络百度百科

1、rbf神经网络算法是什么? RBF神经网络算法是由三层结构组成,输入层至隐层为非线性的空间变换,一般选用径向基函数的高斯函数进行运算;从隐层至输出层为线性空间变换,即矩阵与矩阵之间的变换。 RBF神经网络进行数据运算时需要…

基于springboot的旅游打卡攻略分享小程序

💖💖作者:IT跃迁谷毕设展 💙💙个人简介:曾长期从事计算机专业培训教学,本人也热爱上课教学,语言擅长Java、微信小程序、Python、Golang、安卓Android等。平常会做一些项目定制化开发…