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,
                            out_channels=conv1.out_channels,
                            kernel_size=conv1.kernel_size,
                            stride=conv1.stride,
                            padding=conv1.padding,
                            bias=conv1.bias)
    model.conv1.weight.data[:,:3,:,:] = conv1.weight.data
    model.conv1.weight.data[:,3:,:,:] = conv1.weight.data[:,:1,:,:]

    model.avgpool = nn.AdaptiveAvgPool2d(1)
    in_features = model.last_linear.in_features   
    model.last_linear = nn.Linear(in_features, num_classes)
    #cosine=arc_margin_product(in_features)
    
    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’.

Thanks

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.