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:
- import the model zoo
import torchvision.models as model
- use the model you want, the pretrained arg need to set true if you want to load the weight
resnet152 = model.resnet152(pretrained=True)
- put the object of resent152.children() into a list so that we can enumerate or see each layer
modules = list( resnet152.children() )
- now you can print modules to see the content.
- 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]
- put it in nn.Sequential then set gradient to false:
resnet152 = nn.Sequential(*modules)
for i in resnet152.parameters():
i.requires_grad = False
- finally you can put any image you want into this defined network: