简体   繁体   English

可视化神经网络层激活

[英]Visualizing Neural Network Layer Activation

Feature visualizing in tensor flow or keras is easy and can be found here.张量流或 keras 中的特征可视化很容易,可以在这里找到。 https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/ or Convolutional Neural Network visualization - weights or activations? https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/卷积神经网络可视化 - 权重或激活?

how to do this in pytorch?如何在 pytorch 中做到这一点?

I am using PyTorch with pretrained resnet18 model.我正在使用带有预训练 resnet18 模型的 PyTorch。 All i need to input the image and get activation for specific layer(eg Layer2.0.conv2).我只需要输入图像并激活特定层(例如Layer2.0.conv2)。 Layer2.0.conv2 is specified in the pretrained model. Layer2.0.conv2 在预训练模型中指定。

In simple words;用简单的话来说; how to convert link one code to PyTorch?如何将链接一代码转换为 PyTorch? how to get the specific layers in resnet18 PyTorch and how to get the activation for input image.如何获取 resnet18 PyTorch 中的特定层以及如何获取输入图像的激活。 I tried this in tensorflow and it worked but not PyTorch.我在 tensorflow 中尝试了这个,它有效但不是 PyTorch。

You would have to register PyTorch's hooks on specific layer.您必须在特定层上注册 PyTorch 的钩子。 See this tutorial for intro about hooks.有关钩子的介绍,请参阅本教程

Basically, it allows to capture input/output of forward/backward going into the torch.nn.Module .基本上,它允许捕获forward/backward进入torch.nn.Module input/output Whole thing could be a bit complicated, there exists a library with similar goal to your (disclaimer I'm the author), called torchfunc .整个事情可能有点复杂,存在一个与您的目标相似的库(免责声明我是作者),称为torchfunc Especially torchfunc.hooks.recorder allows you to do what you want, see code snippet and comments below:尤其是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))

You could register recorder only for some layers (submodule) specified by index or layer type, to get necessary info, run:您只能为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