总结:用strict=False进行加载模型,则“能塞则塞,不能塞则丢”。load一般是依据key来加载的,一旦有key不匹配则出错。如果设置strict=False,则直接忽略不匹配的key,对于匹配的key则进行正常的赋值。
pretrained_dict =… model_dict = model.state_dict()
# 1. filter out unnecessary keys pretrained_dict = {k: v for k, vin pretrained_dict.items() if k inmodel_dict}
# 2. overwrite entries in the existing state dict
model_dict.update(pretrained_dict)
# 3. load the new state dict
model.load_state_dict(model_dict)
checkpoint = torch.load('modelparameters.pth') model.load_state_dict(checkpoint)
torch.load('modelparameters.pth', map_location=lambda storage, loc: storage.cuda(1))
torch.load('modelparameters.pth', map_location={'cuda:1':'cuda:0'})
torch.load('modelparameters.pth', map_location=lambda storage, loc: storage)
torch.load('modelparameters.pth', map_location='cpu')