PyTorch - Best way to get at intermediate layers in VGG and ResNet?

To get output of any layer while doing a single forward pass, you can use register_forward_hook.

outputs= []
def hook(module, input, output):
    outputs.append(output)

res50_model = models.resnet50(pretrained=True)
res50_model.layer4[0].conv2.register_forward_hook(hook)
out = res50_model(res)
out = res50_model(res1)
print(outputs)

Here in the outputs you get a list with two tensors in it. Those tensors are outputs of that particular layer for each forward pass.

4 Likes