如何修复加载检查点时的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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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