puhuk
puhuk

Reputation: 484

How can I extract features from pytorch fasterrcnn_resnet50_fpn

I tried to extract features from following code. However, it says 'FasterRCNN' object has no attribute 'features' I want to extract features with (36, 2048) shape features when it has 36 classes. Is there any method to extract with pretrained pytorch models.

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True).to(device)
features = list(model.features)

dummy_img = torch.zeros((1, 3, 800, 800)).float() # test image array

req_features = []
output = dummy_img.clone().to(device)

for feature in features:
    output = feature(output)
    if output.size()[2] < 800//16: # 800/16=50
        break
    req_features.append(feature)
    out_channels = output.size()[1]

faster_rcnn_feature_extractor = nn.Sequential(*req_features)

output_map = faster_rcnn_feature_extractor(dummy_img )
print(output_map.shape)

Upvotes: 0

Views: 1244

Answers (1)

Ivan
Ivan

Reputation: 40728

The function you are calling returns a FasterRCNN object which is based on GeneralizedRCNN. As you have experienced, this object doesn't indeed have a feature attribute. Looking at its source code, if you want to acquire the feature maps, you can follow L83 and L101:

>>> images, _= model.transform(images, None)
>>> features = model.backbone(images.tensors)

Upvotes: 1

Related Questions