基于pytorch使用特征图输出进行特征图可视化

使用特征图输出进行特征图可视化

文章目录


前言

提示:这里可以添加本文要记录的大概内容:

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了基于pytorch使用特征图输出进行特征图可视化的方法

特征图输出就是某个图像(序列)经过该层时的输出


以下是本篇文章正文内容

效果展示

获取某一层特征图输出

原图

方法一:使用IntermediateLayerGetter类

python 复制代码
# 返回输出结果
import random

import cv2
import torchvision
import torch
from matplotlib import pyplot as plt
import numpy as np
from torchvision import transforms
from torchvision import models


# 定义函数,随机从0-end的一个序列中抽取size个不同的数
def random_num(size, end):
    range_ls = [i for i in range(end)]
    num_ls = []
    for i in range(size):
        num = random.choice(range_ls)
        range_ls.remove(num)
        num_ls.append(num)
    return num_ls


path = "img_1.png"
transformss = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Resize((224, 224)),
     transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

# 注意如果有中文路径需要先解码,最好不要用中文
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 转换维度
img = transformss(img).unsqueeze(0)

model = models.resnet50(pretrained=True)
new_model = torchvision.models._utils.IntermediateLayerGetter(model, {'layer1': '1', 'layer2': '2', "layer3": "3"})
out = new_model(img)

tensor_ls = [(k, v) for k, v in out.items()]

# 这里选取layer2的输出画特征图
v = tensor_ls[1][1]

# 选择目标卷积层
target_layer = model.layer2[2]
"""
如果要选layer3的输出特征图只需把第一个索引值改为2,即:
v=tensor_ls[2][1]
只需把第一个索引更换为需要输出的特征层对应的位置索引即可
"""
# 取消Tensor的梯度并转成三维tensor,否则无法绘图
v = v.data.squeeze(0)

print(v.shape)  # torch.Size([512, 28, 28])

# 随机选取25个通道的特征图
channel_num = random_num(25, v.shape[0])
plt.figure(figsize=(10, 10))
for index, channel in enumerate(channel_num):
    ax = plt.subplot(5, 5, index + 1, )
    plt.imshow(v[channel, :, :])
plt.savefig("./img/feature.jpg", dpi=300)

输出的结果如下:

方法二:使用hook机制(推荐)

如下代码所示:

python 复制代码
# 返回输出结果
import random

import cv2
import torchvision
import torch
from matplotlib import pyplot as plt
import numpy as np
from torchvision import transforms
from torchvision import models


# 定义函数,随机从0-end的一个序列中抽取size个不同的数
def random_num(size, end):
    range_ls = [i for i in range(end)]
    num_ls = []
    for i in range(size):
        num = random.choice(range_ls)
        range_ls.remove(num)
        num_ls.append(num)
    return num_ls


path = "img_1.png"
transformss = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Resize((224, 224)),
     transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

# 注意如果有中文路径需要先解码,最好不要用中文
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 转换维度
img = transformss(img).unsqueeze(0)

model = models.resnet50(pretrained=True)

# 选择目标层
target_layer = model.layer2[2]
# 注册钩子函数,用于获取目标卷积层的输出
outputs = []
def hook(module, input, output):
    outputs.append(output)

hook_handle = target_layer.register_forward_hook(hook)

_ = model(img)

v = outputs[-1]

"""
如果要选layer3的输出特征图只需把第一个索引值改为2,即:
v=tensor_ls[2][1]
只需把第一个索引更换为需要输出的特征层对应的位置索引即可
"""
# 取消Tensor的梯度并转成三维tensor,否则无法绘图
v = v.data.squeeze(0)

print(v.shape)  # torch.Size([512, 28, 28])

# 随机选取25个通道的特征图
channel_num = random_num(25, v.shape[0])
plt.figure(figsize=(10, 10))
for index, channel in enumerate(channel_num):
    ax = plt.subplot(5, 5, index + 1, )
    plt.imshow(v[channel, :, :])
plt.savefig("./img/feature2.jpg", dpi=300)

总结

以上就是今天要讲的内容

相关推荐
IT_陈寒2 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
甲维斯2 小时前
Claude Opus5手搓“NewAPI Plus”首轮成果!
人工智能
程序猿DD2 小时前
分享两个我每天都在用的 Skill,拖进豆包就能跑,限时领 30 天会员
人工智能
阿里云大数据AI技术3 小时前
Agentic Search 2.0:从单轮对话迈向企业级 AI 搜索自动驾驶Agent
人工智能·elasticsearch·agent
东风破_3 小时前
从 messages 数组到 Memory:大模型到底是怎么“记住”上一轮对话的?
人工智能
AEI3 小时前
四年间大模型的演进历程
人工智能·面试·程序员
狂师4 小时前
阿里开源:skill-up,一款Agent Skill 评测工具!
人工智能·开源·agent
武子康4 小时前
同一套 Agent Runtime,为什么 Web、Headless 和 Python SDK 仍然不是同一个产品
人工智能·llm·agent
天天代码码天天4 小时前
一个纯 C 的 OCR Runtime,又向前走了一步:lw.PPOCR.C preview.5 发布
人工智能
程序员cxuan4 小时前
Claude 官方的学习教程,太强了。
人工智能·后端·程序员