【问题标题】:pytorch model loading and prediction, AttributeError: 'dict' object has no attribute 'predict'pytorch 模型加载和预测,AttributeError: 'dict' object has no attribute 'predict'
【发布时间】:2019-09-23 22:34:46
【问题描述】:
model = torch.load('/home/ofsdms/san_mrc/checkpoint/best_v1_checkpoint.pt', map_location='cpu')
results, labels = predict_function(model, dev_data, version)

> /home/ofsdms/san_mrc/my_utils/data_utils.py(34)predict_squad()
-> phrase, spans, scores = model.predict(batch)
(Pdb) n
AttributeError: 'dict' object has no attribute 'predict'

如何加载已保存的 pytorch 模型检查点,并将其用于预测。我将模型保存在 .pt 扩展名中

【问题讨论】:

    标签: python-3.x machine-learning pytorch


    【解决方案1】:

    您保存的检查点通常是state_dict:包含训练权重值的字典 - 但不是网络的实际架构。网络的实际计算图/架构被描述为一个 python 类(派生自nn.Module)。
    要使用经过训练的模型,您需要:

    1. 从实现计算图的类中实例化一个model
    2. 将保存的state_dict 加载到该实例:

      model.load_state_dict(torch.load('/home/ofsdms/san_mrc/checkpoint/best_v1_checkpoint.pt', map_location='cpu')
      

    【讨论】:

    • 我已经使用 torch.load 进行了完整的模型加载,在我的例子中,model = DocReaderModel(opt, embedding) model_file_2 = os.path.join(model_dir, 'checkpoint_{}_epoch_{} _full_model.pt'.format(version, epoch)), torch.save(model, model_file_2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2018-08-26
    • 2021-01-08
    • 2020-04-26
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多