Vipin Chaudhary
Vipin Chaudhary

Reputation: 444

How to get ouput from a particular layer from pretrained CNN in pytorch

I have pretrained CNN (RESNET18) on imagenet dataset , now what i want is to get output of my input image from a particular layer,

for example.

my input image is of FloatTensor(3, 224, 336) and i send a batch of size = 10 in my resnet model , now what i want is the output returned by model.layer4,

Now what i tried is out = model.layer4(Variable(input)) but it gave me input dimensions mismatch error(As expected), this is the exact error returned

RuntimeError: Need input of dimension 4 and input.size[1] == 64 but got input to be of shape: [10 x 3 x 224 x 336] at /Users/soumith/miniconda2/conda-bld/pytorch_1501999754274/work/torch/lib/THNN/generic/SpatialConvolutionMM.c:47

So i'm confused , how to proceed now to get my layer4 output

PS: My ultimate task is to combine layer4 output and fullyconnected layer output together (Tweeking in CNN, kind of gated CNN ), so if anyone have any insight in this case then please do tell me, maybe my above approach is not right

Upvotes: 1

Views: 3359

Answers (1)

AmirHossein
AmirHossein

Reputation: 1416

You must create a module with all layers from start to the block you want:

resnet = torchvision.models.resnet18(pretrained=True)
f = torch.nn.Sequential(*list(resnet.children())[:6])
features = f(imgs)

Upvotes: 4

Related Questions