[pytorch]可视化feature map

在计算机视觉的项目中,尤其是物体分类,关键点检测等的实验里,我们常常需要可视化中间的feature map来帮助判断我们的模型是否可以很好地提取到我们想要的特征,进而帮助我们调整模型或者参数。

可视化代码:

from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

def visualize_feature(x, model, layers=[0,1]):
    net = nn.Sequential(*list(model.children())[:layers[0]])
    img = net(x)
    transform1 = transforms.ToPILImage(mode='L')
    #img = torch.cpu().clone()
    for i in range(img.size(0)):
        image = img[i]
        #print(image.size())
        image = transform1(np.uint8(image.numpy().transpose(1,2,0)))
        image.show()
    

transform函数:

将Numpy的ndarray或者Tensor转化成PILImage类型【在数据类型上,两者都有明确的要求】

  1. ndarray的数据类型要求dtype=uint8, range[0, 255] and shape H x W x C
  2. Tensor 的shape为 C x H x W 要求是FloadTensor的,不允许DoubleTensor或者其他类型

numpy转为PIL:

#初始化随机数种子
np.random.seed(0)
 
data = np.random.randint(0, 255, 300)
print(data.dtype)
n_out = data.reshape(10,10,3)
 
#强制类型转换
n_out = n_out.astype(np.uint8)
print(n_out.dtype)
 
img2 = transforms.ToPILImage()(n_out)
img2.show()

tensor转为PIL:

t_out = torch.randn(3,10,10)
img1 = transforms.ToPILImage()(t_out)
img1.show()

训练过程中调用可视化函数

def train(epoch):
    cnn.train()
    for data in tqdm(train_loader, desc='Train: epoch {}'.format(epoch), leave=False, total=len(train_loader)):  # 对于训练集的每一个batch
        img, label = data
        if cuda_available:
            img = img.cuda()
            label = label.cuda()
        #visualize_feature(img, cnn)
 
    
        out = cnn( img )  # 送进网络进行输出
        #out = torch.nn.functional.softmax(out, dim=1)
        #print(out.size())
        #print(label.size())
        loss = loss_function( out, label )  # 获得损失
 
        optimizer.zero_grad()  # 梯度归零
        loss.backward()  # 反向传播获得梯度,但是参数还没有更新
        optimizer.step()  # 更新梯度

直接load预训练好的model并输出feature map

model = Residual_Model()
model.load_state_dict(torch.load('./model.pkl'))

output = get_features(model,x)## model是训练好的model,前面已经import 进来了Residual model
print('output.shape:',output.shape)
### 回答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库将特征图可视化显示在屏幕上。请确保将图像文件路径替换为实际图像文件的路径。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值