1

I’m trying to register a forward hook function to the last conv layer of my network. I first printed out the names of the modules via:

for name, _ in model.named_modules():
    print(name)

Which gave me "0.conv" as the module name. However, when I tried to do the following, the above error was triggered by line 4:

def hook_feature(module, in_, out_):
    features.append(out_.cpu().data.numpy())

model._modules.get("0.conv").register_forward_hook(hook_feature)

Here is my named_modules() output:

...
0.decoder1.dec1conv2
0.decoder1.dec1norm2
0.decoder1.dec1relu2
0.conv
1
1.outc1
1.outc2

What am I doing wrong and how do I fix it? Thanks!

2
  • try model._modules[0].get('conv') Commented Mar 15, 2020 at 6:02
  • 1
    Thanks a lot, you were super close! This helped me figure out model._modules["0"]._modules.get("conv").register_forward_hook(hook_feature) Commented Mar 15, 2020 at 7:29

1 Answer 1

0

Your modules are stored in an hierarchical way. To get to '0.conv', you need to

models._modules["0"]._modules.get("conv").register_forward_hook(hook_feature)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.