I tried to implement this code and working fine. But if I try to modify last layer then getting error. I am new to pytorch so not able to figure out what’s wrong. Only understood that there is some dimension mismatch due to last linear layer. Please help me to resolve the issue. The code I am running is as follows:

from torchvision import models

import torch

import torch.nn as nn

class Flatten(nn.Module):

```
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
x = x.view(x.size(0), -1)
return x
```

model = models.resnet152(pretrained=True)

modules = list(model.children())[:6]

resnet_1st = nn.Sequential(*modules)

modules = list(model.children())[6:-1]

resnet_2nd = nn.Sequential(*[*modules, Flatten(), list(model.children())[-1]])

model.fc = nn.Linear(model.fc.in_features, 512)

x = torch.randn(1, 3, 224, 224)

out_1st = resnet_1st(x)

print(out_1st.shape)

out_2nd = resnet_2nd(out_1st)

print(out_2nd.shape)

for param in model.parameters():

```
param.requires_grad = False
```

out = model.fc(out_2nd)

print(out.shape)

##
Error I am getting:

torch.Size([1, 512, 28, 28])

torch.Size([1, 1000])

RuntimeError Traceback (most recent call last)

in ()

26 for param in model.parameters():

27 param.requires_grad = False

—> 28 out = model.fc(out_2nd)

29 print(out.shape)

2 frames

/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in linear(input, weight, bias)

1846 if has_torch_function_variadic(input, weight, bias):

1847 return handle_torch_function(linear, (input, weight, bias), input, weight, bias=bias)

→ 1848 return torch._C._nn.linear(input, weight, bias)

1849

1850

RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x1000 and 2048x512)