繁体   English   中英

可视化神经网络层激活

[英]Visualizing Neural Network Layer Activation

张量流或 keras 中的特征可视化很容易,可以在这里找到。 https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/卷积神经网络可视化 - 权重或激活?

如何在 pytorch 中做到这一点?

我正在使用带有预训练 resnet18 模型的 PyTorch。 我只需要输入图像并激活特定层(例如Layer2.0.conv2)。 Layer2.0.conv2 在预训练模型中指定。

用简单的话来说; 如何将链接一代码转换为 PyTorch? 如何获取 resnet18 PyTorch 中的特定层以及如何获取输入图像的激活。 我在 tensorflow 中尝试了这个,它有效但不是 PyTorch。

您必须在特定层上注册 PyTorch 的钩子。 有关钩子的介绍,请参阅本教程

基本上,它允许捕获forward/backward进入torch.nn.Module input/output 整个事情可能有点复杂,存在一个与您的目标相似的库(免责声明我是作者),称为torchfunc 尤其是torchfunc.hooks.recorder允许您做您想做的事,请参阅下面的代码片段和注释:

import torchvision
import torchfunc

my_network = torchvision.resnet18(pretrained=True)
# Recorder saving inputs to all submodules
recorder = torchfunc.hooks.recorders.ForwardPre()

# Will register hook for all submodules of resnet18
# You could specify some submodules by index or by layer type, see docs
recorder.modules(my_networks)

# Push example image through network
my_network(torch.randn(1, 3, 224, 224))

您只能为index或层类型指定的某些层(子模块) register记录器,以获取必要的信息,运行:

# Zero image before going into the third submodule of this network
recorder.data[3][0]

# You can see all submodules and their positions by running this:    
for i, submodule in enumerate(my_network.modules()):
    print(i, submodule)

# Or you can just print the network to get this info
print(my_network)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM