How to extract output for some layers using Model Zoo?

Hi, I’m new to pytorch, and hope someone can answer this question.
If I load a pre-trained model say models.resnet101, and I want to extract outputs of intermediate layers and save it’s result. I don’t know how to access to the internal of the model to grab and save it.
For example, the following figure is the Net I defined, and I can easily get the output of the third convolution layer by returning conv3_out back.

So my question is how to do this by using the Model Zoo models? Thank guys!

Answer the question for those who may have the same problem:

  1. import the model zoo

import torchvision.models as model

  1. use the model you want, the pretrained arg need to set true if you want to load the weight

resnet152 = model.resnet152(pretrained=True)

  1. put the object of resent152.children() into a list so that we can enumerate or see each layer

modules = list( resnet152.children() )

  1. now you can print modules to see the content.

print(modules)

  1. it contains each layer of the pre-trained model, then you can assign the range you want for passing image into the model like this:

new_modules = list(resnet152.children())[:5]

  1. put it in nn.Sequential then set gradient to false:

resnet152 = nn.Sequential(*modules)
for i in resnet152.parameters():
i.requires_grad = False

  1. finally you can put any image you want into this defined network:

resnet152(img)

1 Like