3
votes


I'm trying to extract the features of images using VGG19 network (the output should be of dim : [1 , 7 , 7 , 512] per frame
here is the code I have used :

    deep_net = models.vgg19(pretrained=True).cuda()
    deep_net = nn.Sequential(*list(deep_net.children())[:-2])
    deep_net.eval()
    save_file_sample_path = '/media/data1/out.npy'
    input_image = torch.zeros(1, 3, 224, 224)
    output_feat = np.zeros(shape=[1, 49, 512])
    with torch.no_grad():
      im = default_loader('/media/data1/images/frame612.jpg')
      im = transform(im)
      input_image[0, :, :] = im
      input_image = input_image.cuda()
      output_feat = deep_net(input_image)
      output_feat = output_feat.features[:-2].view(1, 512, 49).transpose(1, 2)

But I get the following error :

AttributeError: 'Sequential' object has no attribute 'features'

At the line :

          output_feat = output_feat.features[:-2].view(1, 512, 49).transpose(1, 2)

Any idea why this does not work anymore? and how to fix?
Thanks!

1

1 Answers

2
votes

It's because you are rebuilding deep_net with nn.Sequential so it loses the attribute features.

deep_net = models.vgg19(pretrained=True)
deep_net.features
Sequential(
  (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (1): ReLU(inplace=True)
  ...
  (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
deep_net = nn.Sequential(*list(deep_net.children())[:-2])
deep_net.features
AttributeError: 'Sequential' object has no attribute 'features'

The equivalent you want now is this:

list(deep_net.children())[0][:-2]