Returning a model in a function hurts its performance?


(Wenxuan Guo) #1

I want to transfer-learn from Resnet18 model for a binary classification. The first implementation is:

model = models.resnet18(pretrained=True)
model.avgpool = nn.AvgPool2d(3, stride=1)
model.fc = nn.Linear(512, 1)

Then I try to use a function so I can return different kinds of models. The second implementaion:

def getModel(name, pretrained=False):
    if name == 'resnet18':
        model = models.resnet18(pretrained=pretrained)
        model.avgpool = nn.AvgPool2d(3, stride=1)
        model.fc = nn.Linear(512, 1) 
    
    return model

model = getModel('resnet18', pretrained=True)

I tried several times and the second implementation has worse performance(val acc=0.88) than the first one(val acc=0.9). I don’t understand why this happens.