Skip to content
Advertisement

Accessing a specific layer in a pretrained model in PyTorch

I want to extract the features from certain blocks of the TimeSformer model and also want to remove the last two layers.

JavaScript

The print of the model is as follows:

JavaScript

)

)

Specifically, I want to extract the outputs of the 4th, 8th and 11th blocks of the model and removing the lats two layers. How can I do this. I tried using TimeSformer.blocks[0] but that was not working.

Update :

I have a Class and I need to access the aforementioned blocks of the TimeSformer as the output of this class. The input of this class is a 5D tensor. This is the non-modified code that I use for extracting the outputs of the aforementioned blocks:

JavaScript

Advertisement

Answer

To extract the intermediate output from specific layers, you can register it as a hook, the example is showed by the snipcode below:

JavaScript

To remove the last two layers, you can replace them with Identity:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement