首页 > 其他分享 >CAM、热力图 pytorch可视化卷积层

CAM、热力图 pytorch可视化卷积层

时间:2023-06-14 21:35:13浏览次数:43  
标签:load CAM img 卷积 json pytorch cam import


参考github:https://github.com/sixitingting/CAM/blob/master/pytorch_CAM.py

也就是类激活映射(CAM)原作者所给,想要懂理论的去看论文,本次着重实践。

CAM、热力图 pytorch可视化卷积层_加载

CAM结果展示:

CAM、热力图 pytorch可视化卷积层_json_02

top1 prediction: mountain bike, all-terrain bike, off-roader

 

后话先说: 我发现现在还有很多朋友搜到这篇文章,但这是我刚开始学的时候写的笔记,很多东西都不太全,最近我更新了一个新的方法,更简单,更实用。如果感兴趣,欢迎查看我的另一篇博文CAM(类激活映射),卷积可视化,神经网络可视化,一个库搞定,真的简单的不能再简单。我相信这篇提供的帮助更多,如果有需要的话,点击看看吧。

----------------------------------------------------------实战开始-------------------------------------------------------

# simple implementation of CAM in PyTorch for the networks such as ResNet, DenseNet, SqueezeNet, Inception

import io
import requests
from PIL import Image
import torch
from torchvision import models, transforms
from torch.autograd import Variable
from torch.nn import functional as F
import numpy as np
import cv2
import json

# input image
LABELS_URL = 'https://s3.amazonaws.com/outcome-blog/imagenet/labels.json'
IMG_URL = 'http://media.mlive.com/news_impact/photo/9933031-large.jpg'
# jsonfile = r'D:\python\Camtest\labels.json'
# with open(jsonfile, 'r') as load_f:
#     load_json = json.load(load_f)

# networks such as googlenet, resnet, densenet already use global average pooling at the end,
# so CAM could be used directly.
model_id = 1
if model_id == 1:
    net = models.squeezenet1_1(pretrained=False)
    pthfile = r'E:\anaconda\app\envs\luo\Lib\site-packages\torchvision\models\squeezenet1_1.pth'
    net.load_state_dict(torch.load(pthfile))
    finalconv_name = 'features'   # this is the last conv layer of the network
elif model_id == 2:
    net = models.resnet18(pretrained=False)
    finalconv_name = 'layer4'
elif model_id == 3:
    net = models.densenet161(pretrained=False)
    finalconv_name = 'features'

net.eval()
print(net)

# hook the feature extractor
features_blobs = []


def hook_feature(module, input, output):
    features_blobs.append(output.data.cpu().numpy())


net._modules.get(finalconv_name).register_forward_hook(hook_feature)

# get the softmax weight
params = list(net.parameters())
weight_softmax = np.squeeze(params[-2].data.numpy())


def returnCAM(feature_conv, weight_softmax, class_idx):
    # generate the class activation maps upsample to 256x256
    size_upsample = (256, 256)
    bz, nc, h, w = feature_conv.shape
    output_cam = []
    for idx in class_idx:
        cam = weight_softmax[idx].dot(feature_conv.reshape((nc, h*w)))
        cam = cam.reshape(h, w)
        cam_img = (cam - cam.min()) / (cam.max() - cam.min())  # normalize
        cam_img = np.uint8(255 * cam_img)
        output_cam.append(cv2.resize(cam_img, size_upsample))
    return output_cam


normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
   transforms.Resize((224, 224)),
   transforms.ToTensor(),
   normalize
])

response = requests.get(IMG_URL)
img_pil = Image.open(io.BytesIO(response.content))
img_pil.save('test.jpg')

img_tensor = preprocess(img_pil)
img_variable = Variable(img_tensor.unsqueeze(0))
logit = net(img_variable)

# download the imagenet category list
classes = {int(key): value for (key, value)
          in requests.get(LABELS_URL).json().items()}
# classes = {int(key): value for (key, value)
#           in load_json.items()}


# 结果有1000类,进行排序
h_x = F.softmax(logit, dim=1).data.squeeze()
probs, idx = h_x.sort(0, True)
probs = probs.numpy()
idx = idx.numpy()

# output the prediction 取前5
for i in range(0, 5):
    print('{:.3f} -> {}'.format(probs[i], classes[idx[i]]))

# generate class activation mapping for the top1 prediction
CAMs = returnCAM(features_blobs[0], weight_softmax, [idx[0]])

# render the CAM and output
print('output CAM.jpg for the top1 prediction: %s'%classes[idx[0]])
img = cv2.imread('test.jpg')
height, width, _ = img.shape
heatmap = cv2.applyColorMap(cv2.resize(CAMs[0],(width, height)), cv2.COLORMAP_JET)
result = heatmap * 0.3 + img * 0.5
cv2.imwrite('CAM.jpg', result)

结果:0.678 -> mountain bike, all-terrain bike, off-roader
          0.088 -> bicycle-built-for-two, tandem bicycle, tandem
         0.042 -> unicycle, monocycle
         0.038 -> horse cart, horse-cart
         0.019 -> lakeside, lakeshore
         output CAM.jpg for the top1 prediction: mountain bike, all-terrain bike, off-roader

以上是所有代码,对容易遇到的问题做个解释:

1.由于网络问题下载不下来json文件:

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='media.mlive.com', port=80):

方法:手动把文件下载下来,放在同一个项目下,用被注释掉的代码:

jsonfile = r'D:\python\Camtest\labels.json'   # 换成自己的地址
with open(jsonfile, 'r') as load_f:
    load_json = json.load(load_f)




# 并把下面内容打开
classes = {int(key): value for (key, value)
          in load_json.items()}

2.由于网络问题加载不出来预训练的网络,我就加载不出来,所以 pretrained=False,并去下载预训练好的参数,

3.关于hook住中间特征不懂得去百度: register_forward_hook

4.结果只展示了top5的预测结果。


标签:load,CAM,img,卷积,json,pytorch,cam,import
From: https://blog.51cto.com/u_16159492/6481501

相关文章

  • 如何从Pytorch 到 Pytorch Lightning (二) | 简要介绍
    这篇文章主要介绍为什么使用pytorch时,需要使用Lightning的最常见问题。由PytorchLightning的主创团队编写(WilliamFalcon),经本文翻译。PyTorch非常易于使用,可以构建复杂的AI模型。但是一旦研究变得复杂,并且将诸如多GPU训练,16位精度和TPU训练之类的东西混在一起,用户很可能引入Bug。......
  • CAM(类激活映射),卷积可视化,神经网络可视化,一个库搞定,真的简单的不能再简单
    文章目录前言1.`pytorch-grad-cam`这个库可以做什么?2.安装`pytorch-grad-cam`3.具体使用案例3.1选择目标层(TargetLayer)3.2单个图像CAM热力图3.3批处理图像3.4一个CAM计算模板前言18年,我刚入门的时候,写了这样一篇文章,想要看之前那一篇的点击这里现在都还有很多朋友在看,但我......
  • 卷积神经网络VGG
    1.概述VGG[1]是Oxford的VisualGeometryGroup的组提出的,VGG的缩写也来自于这个组的名字。VGG网络探索了提升网络的深度对最终的图像识别准确率的重要性,同时在VGG中尝试使用小的卷积核来构建深层的卷积网络。VGG在当年的ILSVRC2014上取得了第一的成绩,证明了增加网络的深度能够在......
  • ESP32-CAM开发板WiFi连接
    ESP32连接wifi这里我们可以参考官方文档所提供的接口函数,如下而对应我们常用的esp连接网络,我们只需要用好官方提供的下面这个函数就好了defdo_connect():importnetwork#引入所需要的模块wlan=network.WLAN(network.STA_IF)#设置模式为APwlan.active(......
  • pytorch -- topk()
    torch.topk(input,k,dim=None,largest=True,sorted=True,out=None)->(Tensor,LongTensor) pytorch中文官网文档:http://www.mamicode.com/info-detail-2217311.html沿给定dim维度返回输入张量input中 k 个最大值。如果不指定dim,则默认为input的最后一维。如果为largest......
  • ESP32-CAM开发板刷固件时遇到问题与解决方法
    ESP32-CAM开发板刷固件时遇到的问题通过ThonnyIDE给ESP32-CAM刷入micorpython固件时,我遇到三个问题,给大家做个参照。1从MicroPython官网下载的固件没有Camera库,所以经过多次努力,找到了一个国外的开发者前辈,他给MicroPython中添加了Camera摄像头库。2ESP32-CAM有专门的......
  • pytorch 使用示例
    记录通过pytorch编写cnn模型示例,包括训练、模型、预测全流程代码结构,数据采集公共调制方式识别数据集,编写代码简单,以便进行pytorch学习。train.pyimportosimportnumpyasnpimporttorchimporttorch.nnasnnimporttorch.optimasoptimfromtqdmimporttqdmfrom......
  • opcenter camstar designer基础知识--Tables
    tables用于存储持久性数据,通过Designer创建表时,实际上创建的表定义将成为事务数据库中的表。单击工具栏上的“Tables”按钮将打开“tables”窗口,可以在其中查看所选表的属性。选择树显示表的5种类别:   1.modeling建模此类别的表对应于各种模型或结构,例如工厂、位......
  • 卷积神经网络(LeNet)
    目录1.卷积神经网络(LeNet)1.1LeNet1.卷积神经网络(LeNet)\(LeNet\)最早的卷积神经网络之一(\(1989\)年提出)。用于银行支票上手写数字识别(\(1998\)年杨立坤教授提出)。1.1LeNet\(LeNet\)\((LeNet-5)\)由两部分组成:卷积编码器:由\(2\)个卷积层。全连接层密集块:由\(......
  • v831-openwrt-c开发-cam篇
    流程:libmaix_camera_module_init->libmaix_cam_create->start_capture->capture_image->libmaix_cam_destroy->libmaix_camera_module_deinit此为最简单的流程,需要添加操作再次之间添加 CAM的创建(注意)根据sipeed的官方例程,如果是v831啧需要创建两个cam句柄才能让摄像头正常......