Extract features from layer of submodule of a model

The forward_hook should work:

activation = {}
def get_activation(name):
    def hook(model, input, output):
        activation[name] = output.detach()
    return hook

model.fc0.conv2.register_forward_hook(get_activation('fc0.conv2'))
model.fc1.conv2.register_forward_hook(get_activation('fc1.conv2'))

output = model(x)
print(activation['fc0.conv2'])
print(activation['fc0.conv1'])

I’m not sure, what y = self.conv2(self.conv1(x)) in hybrid_cnn is, so I just removed it.

12 Likes