How to get the features from the Resnet model

Hi, Can I please get some help here.
I have been using the following code to obtain:
output = model(images)

where model = get_resnet34()

def get_resnet34(num_classes=6, **_):
    model_name = 'resnet34'
    model = pretrainedmodels.__dict__[model_name](num_classes=1000, pretrained='imagenet')
    arc_margin_product=ArcMarginProduct(512, num_classes)
    conv1 = model.conv1
    model.conv1 = nn.Conv2d(in_channels=4,
                            bias=conv1.bias)[:,:3,:,:] =[:,3:,:,:] =[:,:1,:,:]

    model.avgpool = nn.AdaptiveAvgPool2d(1)
    in_features = model.last_linear.in_features   
    model.last_linear = nn.Linear(in_features, num_classes)
    return model

Now I want to use Resnet34 output as features to be an input into the following code

def forward(self, features):
        cosine = F.linear(F.normalize(features), F.normalize(self.weight.cuda()))
        return cosine

i am getting this error 'torch.nn.modules.module.ModuleAttributeError: ‘ResNet’ object has no attribute ‘norm’ '.

May I know how do i get to ‘return features’ from ‘get_resnet34(num_classes=6, **_)’, instead of ‘returning model’.


The error doesn’t match the posted code, as you are not using model.norm() anywhere.

After creating the model, you could replace the last linear layer with an nn.Identity module to get the features instead of the logits from the last layer.

1 Like

Thank you very much.