Feature Vector Extraction from Densenet121

Hi, I have a CNN model that classifies images of an x-rays dataset. Now, what I want is to extract the feature vectors from any convolution layer and save them so that I can use them somewhere else.

I saw some posts mentioning changing sub-classing the model, and overriding the forward method but I wasn’t successful doing that.

This is a part of my code:

class DenseNet121(nn.Module):

** def init(self, out_size):**
** super(DenseNet121, self).init()**
** self.densenet121 = torchvision.models.densenet121(pretrained = True)**
** num_ftrs = self.densenet121.classifier.in_features**
** self.densenet121.classifier = nn.Sequential(**
** nn.Linear(num_ftrs, out_size),**
** nn.Sigmoid()**
** )**

** def forward(self, x):**
** x = self.densenet121(x)**
** return x**

I’d appreciate a detailed explanation of what to do since I’m still new to this field.
Thanks.

If overriding the forward method is too cumbersome, you could use forward hooks instead as described here.