How to extract the hidden layer output

Hi, I have a general question for Pytorch. I already have a binary classifier neural network using Pytorch. After the model is trained, now I want to obtain the hidden layers output instead of the last layer output since I want to feed the hidden layer output to be the input for a gradient boost model. is there anyway I can do this in a pytorch way? thanks!

1 Like

You could change the forward method and return the hidden layer output additionally to or instead of the original output.
If your desired hidden layer is quite at the front of the model, it’s sometimes easier to “call” each modules:

hidden = model.layer2(F.relu(model.layer1(data)))

But this will get quite ugly if it’s not a layer at the front of your model.

1 Like

you can try to use the function of register_forward_hook,and register_backward_hook,