PyTorch小技巧:使用Hook可视化网络层激活(各层输出)

这篇文章将演示如何可视化PyTorch激活层。可视化激活,即模型内各层的输出,对于理解深度神经网络如何处理视觉信息至关重要,这有助于诊断模型行为并激发改进。

我们先安装必要的库:

 pip install torch torchvision matplotlib

加载CIFAR-10数据集并可视化一些图像。这有助于理解模型处理的输入。

 importtorchvision
 importtorchvision.transformsastransforms
 importmatplotlib.pyplotasplt
 
 # Transformations for the images
 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])
 ])
 
 # Load CIFAR-10 dataset
 trainset=torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
 trainloader=torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True)
 
 # Function to show images
 defimshow(img):
     img=img.numpy().transpose((1, 2, 0))
     mean=np.array([0.485, 0.456, 0.406])
     std=np.array([0.229, 0.224, 0.225])
     img=std*img+mean  # unnormalize
     plt.imshow(img)
     plt.show()
 
 # Get some images
 dataiter=iter(trainloader)
 images, labels=next(dataiter)
 
 # Display images
 imshow(torchvision.utils.make_grid(images))

看着很模糊的原因是我们使用的CIFAR-10图像32x32的,很小 。因为对于小图像,处理速度很快,所以CIFAR-10称为研究的首选。

然后我们加载一个预训练的ResNet模型,并在特定的层上设置钩子函数,以在向前传递期间捕获激活。

 import torch
 from torchvision.models import resnet18
 
 # Load pretrained ResNet18
 model = resnet18(pretrained=True)
 model.eval()  # Set the model to evaluation mode
 
 # Hook setup
 activations = {}
 def get_activation(name):
     def hook(model, input, output):
         activations[name] = output.detach()
     return hook
 
 # Register hooks
 model.layer1[0].conv1.register_forward_hook(get_activation('layer1_0_conv1'))
 model.layer4[0].conv1.register_forward_hook(get_activation('layer4_0_conv1'))

这样,在通过模型处理图像时就能捕获到激活。

 # Run the model
 with torch.no_grad():
     output = model(images)

通过上面钩子函数我们获得了激活下面就可以进行可视化

 # Visualization function for activations
 def plot_activations(layer, num_cols=4, num_activations=16):
     num_kernels = layer.shape[1]
     fig, axes = plt.subplots(nrows=(num_activations + num_cols - 1) // num_cols, ncols=num_cols, figsize=(12, 12))
     for i, ax in enumerate(axes.flat):
         if i < num_kernels:
             ax.imshow(layer[0, i].cpu().numpy(), cmap='twilight')
             ax.axis('off')
     plt.tight_layout()
     plt.show()
 # Display a subset of activations
 plot_activations(activations['layer1_0_conv1'], num_cols=4, num_activations=16)

结果如下:

 plot_activations(activations['layer4_0_conv1'], num_cols=4, num_activations=16)

PyTorch的钩子函数(hooks)是一种非常有用的特性,它们允许你在训练的前向传播和反向传播过程中插入自定义操作。这对于调试、修改梯度或者理解网络的内部运作非常有帮助。

利用 PyTorch 钩子函数来可视化网络中的激活是一种很好的方式,尤其是想要理解不同层如何响应不同输入的情况下。在这个过程中,我们可以捕捉到网络各层的输出,并将其可视化以获得直观的理解。

可视化激活有助于理解卷积神经网络中的各个层如何响应输入图像中的不同特征。通过可视化不同的层,可以评估早期层是否捕获边缘和纹理等基本特征,而较深的层是否捕获更复杂的特征。这些知识对于诊断问题、调整层架构和改进整体模型性能是非常宝贵的。

https://avoid.overfit.cn/post/c63b9b1130fe425ea5b7d0bedf209b2e

相关推荐
醒了就刷牙几秒前
56 门控循环单元(GRU)_by《李沐:动手学深度学习v2》pytorch版
pytorch·深度学习·gru
炼丹师小米几秒前
Ubuntu24.04.1系统下VideoMamba环境配置
python·环境配置·videomamba
橙子小哥的代码世界1 分钟前
【深度学习】05-RNN循环神经网络-02- RNN循环神经网络的发展历史与演化趋势/LSTM/GRU/Transformer
人工智能·pytorch·rnn·深度学习·神经网络·lstm·transformer
GFCGUO7 分钟前
ubuntu18.04运行OpenPCDet出现的问题
linux·python·学习·ubuntu·conda·pip
985小水博一枚呀2 小时前
【深度学习基础模型】神经图灵机(Neural Turing Machines, NTM)详细理解并附实现代码。
人工智能·python·rnn·深度学习·lstm·ntm
SEU-WYL3 小时前
基于深度学习的任务序列中的快速适应
人工智能·深度学习
OCR_wintone4213 小时前
中安未来 OCR—— 开启高效驾驶证识别新时代
人工智能·汽车·ocr
matlabgoodboy3 小时前
“图像识别技术:重塑生活与工作的未来”
大数据·人工智能·生活
萧鼎3 小时前
Python调试技巧:高效定位与修复问题
服务器·开发语言·python
最近好楠啊3 小时前
Pytorch实现RNN实验
人工智能·pytorch·rnn