Loading a pre-trained model Customized

Hi guys, I have a problem when I load my model:

This is the code when I trained my model:

model = models.densenet121(pretrained = True)

train_on_gpu = torch.cuda.is_available()

for param in model.parameters():
param.requires_grad = False

from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([
(‘c1’,nn.Linear(1024,740)),
(‘relu’, nn.ReLU()),
(‘c2’,nn.Linear(740,400)),
(‘relu1’,nn.ReLU()),
(‘c3’, nn.Linear(400,2)),
(‘output’, nn.LogSoftmax(dim=1))
]))

model.classifier = classifier


The train code

torch.save( model.state_dict(),‘classificador-1.pth’)

When I load the model:

state_dict = (checkpoint[‘state_dict’])
model = models.densenet121(pretrained = False)
model.load_state_dict(new_state_dict,strict=False)
model.fc = classifier
for parameter in model.parameters():
parameter.requires_grad = False
model.eval()

But I have wrong predicted class when I test the model,
because I just wanted two exits but I’m getting more.

It seems you can load the saved model, but what is not clear where is the variable classifier initialized before you use when loading:

state_dict = (checkpoint[‘state_dict’])
model = models.densenet121(pretrained = False)
model.load_state_dict(new_state_dict,strict=False)
model.fc = **classifier**
for parameter in model.parameters():
parameter.requires_grad = False
model.eval()

If the linear layer is not initialized/loaded with trained weights then the predictions will not be accurate.