使用pytorch进行模型加载时,遇见IncompatibleKeys‘ object has no attribute ‘xxx‘问题

今天使用pytroch进行模型加载,出现了IncompatibleKeys' object has no attribute 'xxx'问题,该问题发生情况如下。
错误案例

def fun()
	model = VGG16()
    if pretrained:
        model = model.load_state_dict(torch.load('xxx.pth'))
    return model

会报错_IncompatibleKeys' object has no attribute xxx, 因为这里不能对moel进行赋值。
正解

def fun()
	model = VGG16()
    if pretrained:
        model.load_state_dict(torch.load('xxx.pth'))
    return model

初始化模型后,直接对模型通过model.load_state_dict()进行加载预训练参数,然后直接返回该模型。

你可能感兴趣的:(code出错)