Python Pytorch:当参数或大小发生变化时,是否可以加载模型?
Pytorch模型(图形、权重和偏差)通过以下方式保存:Python Pytorch:当参数或大小发生变化时,是否可以加载模型?,python,load,pytorch,Python,Load,Pytorch,Pytorch模型(图形、权重和偏差)通过以下方式保存: torch.save(self.state_dict(), file) 并载有: self.load_state_dict(torch.load(file)) 但如果参数更改,模型将不会加载错误,例如: RuntimeError: Error(s) in loading state_dict for LeNet5: size mismatch for conv1.weight: 是否可以将更改的大小加载到模型? 填充其余权重
torch.save(self.state_dict(), file)
并载有:
self.load_state_dict(torch.load(file))
但如果参数更改,模型将不会加载错误,例如:
RuntimeError: Error(s) in loading state_dict for LeNet5:
size mismatch for conv1.weight:
是否可以将更改的大小加载到模型?
填充其余权重的一种方式,如初始化(如果有更多权重)和剪裁(如果权重较少)?没有自动完成的方法,因为您需要明确地决定当事情不匹配时要做什么 就我个人而言,当我需要在一个稍微改变的模型上“强制”一个预先训练好的砝码时。我发现使用
state\u dict
本身是最方便的方法
new_model = model( ... ) # construct the new model
new_sd = new_model.state_dict() # take the "default" state_dict
pre_trained_sd = torch.load(file) # load the old version pre-trained weights
# merge information from pre_trained_sd into new_sd
# ...
# after merging the state dict you can load it:
new_model.load_state_dict(new_sd)