pytorch可视化特征图

根据大神的代码整理的。
链接在这
自己定义了一个LeNet,
代码如下:

import os
import torch
import torchvision as tv
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import argparse
import skimage.data
import skimage.io
import skimage.transform
import numpy as np
import matplotlib.pyplot as plt



class LeNet(nn.Module):
    '''
    该类继承了torch.nn.Modul类
    构建LeNet神经网络模型
    '''
    def __init__(self):
        super(LeNet, self).__init__()

        # 第一层神经网络,包括卷积层、线性激活函数、池化层
        self.conv1 = nn.Sequential( 
            nn.Conv2d(3, 8, 5, 1, 2),   # input_size=(3*256*256),padding=2
            nn.ReLU(),                  # input_size=(32*256*256)
            nn.MaxPool2d(kernel_size=2, stride=2),  # output_size=(32*128*128)
        )

        # 第二层神经网络,包括卷积层、线性激活函数、池化层
        self.conv2 = nn.Sequential(
            nn.Conv2d(8, 16, 5, 1, 2),  # input_size=(32*128*128)
            nn.ReLU(),            # input_size=(64*128*128)
            nn.MaxPool2d(2, 2)    # output_size=(64*64*64)
        )

        # 全连接层(将神经网络的神经元的多维输出转化为一维)
        self.fc1 = nn.Sequential(
            nn.Linear(16 * 64 * 64, 128),  # 进行线性变换
            nn.ReLU()                    # 进行ReLu激活
        )

        # 输出层(将全连接层的一维输出进行处理)
        self.fc2 = nn.Sequential(
            nn.Linear(128, 84),
            nn.ReLU()
        )

        # 将输出层的数据进行分类(输出预测值)
        self.fc3 = nn.Linear(84, 62)

    # 定义前向传播过程,输入为x
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        # nn.Linear()的输入输出都是维度为一的值,所以要把多维度的tensor展平成一维
        x = x.view(x.size()[0], -1)
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)
        return x


def get_picture(picture_dir, transform):
    '''
    该算法实现了读取图片,并将其类型转化为Tensor
    '''
    img = skimage.io.imread(picture_dir)
    img256 = skimage.transform.resize(img, (256, 256))
    img256 = np.asarray(img256)
    img256 = img256.astype(np.float32)

    return transform(img256)



def get_picture_rgb(picture_dir):
    '''
    该函数实现了显示图片的RGB三通道颜色
    '''
    img = skimage.io.imread(picture_dir)
    img256 = skimage.transform.resize(img, (256, 256))
    skimage.io.imsave('D:\code\jupyter\data/4.jpg',img256)
    img = img256.copy()
    ax = plt.subplot()
    ax.set_title('image')
    plt.imshow(img)

    plt.show()
    
    
class FeatureExtractor(nn.Module):
    def __init__(self, submodule, extracted_layers):
        super(FeatureExtractor, self).__init__()
        self.submodule = submodule
        self.extracted_layers = extracted_layers
 
    def forward(self, x):
        outputs = []
#         print(self.submodule._modules.items())
        for name, module in self.submodule._modules.items():
            if "fc" in name: 
#                 print(name)
                x = x.view(x.size(0), -1)
#             print(module)
            x = module(x)
#             print(name)
            if name in self.extracted_layers:
                outputs.append(x)
        return outputs
    
    
def get_feature():
    # 输入数据
    img = get_picture(pic_dir, transform)
    # 插入维度
    img = img.unsqueeze(0)

    img = img.to(device)

    # 特征输出
    net = LeNet().to(device)
    # net.load_state_dict(torch.load('./model/net_050.pth'))
    exact_list = ["conv1","conv2"]
    myexactor = FeatureExtractor(net, exact_list)
    x = myexactor(img)

    # 特征输出可视化
    for i in range(8):
        ax = plt.subplot(2,4, i + 1)
        ax.set_title('Feature {}'.format(i))
        ax.axis('off')
        plt.imshow(x[0].cpu()[0,i,:,:].detach().numpy(),cmap='jet')
#         plt.imshow(x[0].data.numpy()[0,i,:,:],cmap='jet')
    plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用以下代码来生成VGG特征:import torch import torchvision.models as models import torchvision.transforms as transforms from torch.autograd import Variable import matplotlib.pyplot as plt# 载入VGG16模型 model = models.vgg16(pretrained=True)# 读入一张片 img = Image.open('path_to_image')# 对片做预处理 transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) img_t = transform(img)# 把片做成一个batch batch_t = torch.unsqueeze(img_t, 0)# 将VGG16模型设置为可训练 for parma in model.parameters(): parma.requires_grad = False # 为片送入模型 out = model(Variable(batch_t))# 可视化VGG特征 plt.figure(figsize=(14, 8)) for i in range(out.size()[1]): ax = plt.subplot(8, 8, i + 1) ax.imshow(out[0, i, :, :].data.numpy(), cmap='jet') ax.axis('off') plt.show() ### 回答2: 要生成一个pytorch可视化VGG特征,需要进行以下步骤: 1. 导入必要的库和模块: ```python import torch import torch.nn as nn import torchvision.models as models import matplotlib.pyplot as plt ``` 2. 定义VGG模型并加载预训练的权重: ```python vgg = models.vgg16(pretrained=True) ``` 3. 获取所需层的特征: ```python layer_name = 'features.29' # 这里选择VGG16的最后一个卷积层,可以根据需要调整layer_name layer = vgg.features._modules[layer_name] ``` 4. 创建一个向前传递的hook函数,用于获取特征输出: ```python target_output = None def hook_fn(module, input, output): global target_output target_output = output ``` 5. 注册hook函数到目标层: ```python layer.register_forward_hook(hook_fn) ``` 6. 前向传播输入并得到特征: ```python input_img = torch.randn(1, 3, 224, 224) # 这里随机生成一个输入像,可以根据需要调整 _ = vgg(input_img) # 触发前向传播并生成特征 ``` 7. 将特征可视化: ```python feature_map = target_output[0].detach().numpy() # 将特征从Tensor转换为NumPy数组 plt.imshow(feature_map) plt.show() ``` 这样就可以生成并可视化VGG模型中指定层的特征了。注意,代码中的像尺寸、层的选择和其他参数可以根据需要进行调整。 ### 回答3: 要生成PyTorch中VGG特征代码,需要首先导入必要的库和模块。代码如下所示: ```python import torch import torchvision.models as models import cv2 import matplotlib.pyplot as plt # 加载预训练的VGG模型 vgg = models.vgg16(pretrained=True) vgg.eval() # 选择指定层级的特征 selected_layer = vgg.features[12] # 加载并预处理像 image = cv2.imread('image.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (224, 224)) image = torch.from_numpy(image.transpose((2, 0, 1))) image = image.float() image /= 255.0 image = torch.unsqueeze(image, 0) # 前向传播获取输出特征 output = selected_layer(image) # 转换输出特征格式 output = output.data.squeeze() output = output.numpy() # 可视化特征 plt.imshow(output, cmap='gray') plt.axis('off') plt.show() ``` 以上代码首先加载了预训练的VGG16模型,并选择了第13层特征(vgg.features[12])作为可视化对象。然后,加载和预处理了待处理的像,将其转换为PyTorch张量。接下来,通过前向传播计算输出特征。最后,使用matplotlib库将特征可视化显示在屏幕上。请确保将像文件路径替换为实际像文件的路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值