我在Udacity的课程(使用Python编程的人工智能)中进行项目2的工作。
我已经训练了一个模型并将其保存为checkpoint.pth,现在我想加载checkpoint.pth以重建模型。
我已经编写了保存checkpoint.pth和加载检查点的代码。
model.class_to_idx = image_datasets['train_dir'].class_to_idxmodel.cpu()checkpoint = {'input_size': 25088, 'output_size': 102, 'hidden_layers': 4096, 'epochs': epochs, 'optimizer': optimizer.state_dict(), 'state_dict': model.state_dict(), 'class_to_index' : model.class_to_idx }torch.save(checkpoint, 'checkpoint.pth')def load_checkpoint(filepath): checkpoint = torch.load(filepath) model = checkpoint.Network(checkpoint['input_size'], checkpoint['output_size'], checkpoint['hidden_layers'], checkpoint['epochs'], checkpoint['optimizer'], checkpoint['class_to_index'] ) model.load_state_dict(checkpoint['state_dict']) return modelmodel = load_checkpoint('checkpoint.pth')
在加载checkpoint.pth时,我遇到了一个错误:
AttributeError: 'dict' object has no attribute 'Network'
我想成功加载检查点。
谢谢
回答:
更新:通过查看完整代码,我认为问题出在实现上。torch.load会从文件中反序列化加载信息到字典中。这会加载为原始的字典对象,因此在函数中,你应该期望checkpoint == checkpoint(原始定义)。
在这种情况下,我认为你实际上是想调用保存为checkpoint.pth
的文件上的加载操作,第一个调用可能不是必要的。
def load_checkpoint(filepath): model = torch.load(filepath) return model
另一种可能性是嵌套对象必须是对象的名称,然后只需做一个小的调整:
def load_checkpoint(filepath): checkpoint = torch.load(filepath) model = torch.load_state_dict(checkpoint['state_dict']) return model
最可能的问题是你正在调用Network类,而这个类并不包含在检查点字典对象中。
我无法谈论实际的课程或课程中的其他细微差别,最简单的解决方案可能是直接使用检查点字典中已有的变量调用Network类定义,如下所示:
model = Network(checkpoint['input_size'], checkpoint['output_size'], checkpoint['hidden_layers'], checkpoint['epochs'], checkpoint['optimizer'], checkpoint['class_to_index'])model.load_state_dict(checkpoint['state_dict'])return model
检查点字典可能只有你期望的值(如’input_size’、’output_size’等),但这是我看到的最明显的问题。