Pytorch模型转ONNX

参考https://blog.csdn.net/qq_37546267/article/details/106767640 利用下面代码将pth模型转换为onnx

import torch
from torch.autograd import Variable
import onnx
print(torch.__version__)
# torch  -->  onnx
input_name = ['input']
output_name = ['output']
input = Variable(torch.randn(1, 3, 224, 224)).cuda()
# model = torchvision.models.resnet50(pretrained=True).cuda()
model = torch.load('resnet50.pth', map_location="cuda:0")
torch.onnx.export(model, input, 'resnet50.onnx', input_names=input_name, output_names=output_name, verbose=True)
# 模型可视化
# netron.start('resnet50.onnx')

转换时出现 AttributeError: 'dict' object has no attribute 'training' 的问题。

通过查看https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html 关于如何使用pytroch到处到onnx,和https://pytorch.org/tutorials/beginner/saving_loading_models.html 关于torch.savetorch.load的使用。找到了之前代码中使用的是

torch.save(model.state_dict(), PATH)

这种保存的是模型的字典。

model = torch.load(PATH)

再使用torch.load时,会报错。

所以,在保存模型是,使用:

torch.save(model, PATH)

再运行最上面的转换代码。可以正常工作。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值