Pytorch:参数或大小发生变化时是否可以加载模型?
Pytorch: Is it possible to load model when parameters or size have changed?
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:
是否可以加载到更改大小的模型?
像初始化时那样填充其余的权重(如果有更多的权重),如果权重较少则裁剪?
没有自动执行此操作的方法 - 因为您需要明确地决定当事情不匹配时要做什么。
就个人而言,当我需要 "force" 一个 pre-trained 稍微改变模型的权重时。我发现使用 state_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)
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:
是否可以加载到更改大小的模型? 像初始化时那样填充其余的权重(如果有更多的权重),如果权重较少则裁剪?
没有自动执行此操作的方法 - 因为您需要明确地决定当事情不匹配时要做什么。
就个人而言,当我需要 "force" 一个 pre-trained 稍微改变模型的权重时。我发现使用 state_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)