如何修复加载检查点时的AttributeError?

我在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’等),但这是我看到的最明显的问题。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注