在pytorch模型中,我正在像这样初始化我的模型和优化器。
model = MyModelClass(config, shape, x_tr_mean, x_tr,std)
optimizer = optim.SGD(model.parameters(), lr=config.learning_rate)
这是我的检查点文件的路径。
checkpoint_file = os.path.join(config.save_dir,“ checkpoint.pth”)
要加载此检查点文件,请检查并查看该检查点文件是否存在,然后再加载该文件以及模型和优化器。
if os.path.exists(checkpoint_file):
if config.resume:
torch.load(checkpoint_file)
model.load_state_dict(torch.load(checkpoint_file))
optimizer.load_state_dict(torch.load(checkpoint_file))
此外,这就是我保存模型和优化器的方式。
torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'iter_idx': iter_idx, 'best_va_acc': best_va_acc}, checkpoint_file)
由于某种原因,每当我运行此代码时,我总是收到一个奇怪的错误。
model.load_state_dict(torch.load(checkpoint_file))
File "/home/Josh/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 769, in load_state_dict
self.__class__.__name__, "\n\t".join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for MyModelClass:
Missing key(s) in state_dict: "mean", "std", "attribute.weight", "attribute.bias".
Unexpected key(s) in state_dict: "model", "optimizer", "iter_idx", "best_va_acc"
有人知道我为什么收到此错误吗?
答案 0 :(得分:2)
您已将模型参数保存在字典中。您应该使用先前保存时使用的密钥来加载模型检查点和state_dict
,如下所示:
if os.path.exists(checkpoint_file):
if config.resume:
checkpoint = torch.load(checkpoint_file)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
您可以在PyTorch网站上查看官方tutorial以获得更多信息。