pytorch卷积网络特征图可视化

pytorch特征图 可视化 清测有效,Mark一下。

引用自 https://my.oschina.net/u/4300877/blog/4693569

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 09:25:51 2020

@author: LX
"""

#%%特征可视化
import matplotlib.pyplot as plt
import cv2
import numpy as np
from PIL import Image
from torchvision import models, transforms
import torch
import timm
class SaveConvFeatures(): 
    
    def __init__(self, m): # module to hook
        self.hook = m.register_forward_hook(self.hook_fn) 
    def hook_fn(self, module, input, output): 
        self.features = output.data 
    def remove(self):
        self.hook.remove()

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
t = transforms.Compose([transforms.Resize((224, 224)), #128, 128
                                      transforms.ToTensor(),
                                      transforms.Normalize(mean=0.1307, std=0.3081)])

img_file = r"C:\Users\LX\Pictures\elephant.jpg"
img = Image.open(img_file)
img = t(img).unsqueeze(0).to(device)

custom_model = models.resnet50(pretrained=True)
# custom_model = timm.create_model('resnest50d', pretrained=True)
# custom_model.layer4是自己需要查看特征输出的卷积层
hook_ref = SaveConvFeatures(custom_model.layer4)
with torch.no_grad():
    custom_model(img)
    
conv_features = hook_ref.features # [1,2048,7,7]
print('特征图输出维度:', conv_features.shape) #其实得到特征图之后可以自己编写绘图程序
hook_ref.remove()

def show_feature_map(img_src, conv_features):
    '''可视化卷积层特征图输出
    img_src:源图像文件路径
    conv_feature:得到的卷积输出,[b, c, h, w]
    '''
    img = Image.open(img_file).convert('RGB')
    height, width = img.size
    heat = conv_features.squeeze(0)#降维操作,尺寸变为(2048,7,7)
    heat_mean = torch.mean(heat,dim=0)#对各卷积层(2048)求平均值,尺寸变为(7,7)
    heatmap = heat_mean.numpy()#转换为numpy数组
    heatmap /= np.max(heatmap)#minmax归一化处理
    heatmap = cv2.resize(heatmap,(img.size[0],img.size[1]))#变换heatmap图像尺寸,使之与原图匹配,方便后续可视化
    heatmap = np.uint8(255*heatmap)#像素值缩放至(0,255)之间,uint8类型,这也是前面需要做归一化的原因,否则像素值会溢出255(也就是8位颜色通道)
    heatmap = cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)#颜色变换
    plt.imshow(heatmap)
    plt.show()
    # heatmap = np.array(Image.fromarray(heatmap).convert('L'))
    superimg = heatmap*0.4+np.array(img)[:,:,::-1] #图像叠加,注意翻转通道,cv用的是bgr
    cv2.imwrite('./superimg.jpg',superimg)#保存结果
    # 可视化叠加至源图像的结果
    img_ = np.array(Image.open('./superimg.jpg').convert('RGB'))
    plt.imshow(img_)
    plt.show()


show_feature_map(img_file, conv_features)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch提供了一种可神经网络结构的方法,可以使用`torchsummary`库来实现。首先,你需要安装`torchsummary`库,可以使用以下命令进行安装: ``` pip install torchsummary ``` 安装完成后,你可以按照以下步骤进行卷神经网络结构的可: 1. 导入需要的库: ```python import torch import torch.nn as nn from torchsummary import summary ``` 2. 定义你的卷神经网络模型: ```python class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1) self.relu1 = nn.ReLU() self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1) self.relu2 = nn.ReLU() self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.fc1 = nn.Linear(128 * 8 * 8, 1024) self.relu3 = nn.ReLU() self.fc2 = nn.Linear(1024, 10) def forward(self, x): x = self.conv1(x) x = self.relu1(x) x = self.pool1(x) x = self.conv2(x) x = self.relu2(x) x = self.pool2(x) x = x.view(-1, 128 * 8 * 8) x = self.fc1(x) x = self.relu3(x) x = self.fc2(x) return x model = Net() ``` 3. 使用`summary`函数来可模型结构: ```python summary(model, input_size=(3, 32, 32)) ``` 这将输出模型的详细结构信息,包括每一层的输入形状、参数数量等。 需要注意的是,`input_size`参数需要根据你的输入数据的形状进行调整。在上面的示例中,假设输入数据是3通道的32x32像。 希望这能回答你的问题!如果有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值