pytorch框架--网络方面--onnx模型-转换-保存-加载-部署

模型.pth 转换为 .onnx

# 首先正常加载模型model
# 根据图像需求输入
dummy_input = torch.randn(1, 3, 224, 224)
# 保存.onnx格式模型  
torch.onnx._export(model, dummy_input, "cnn.onnx", verbose=True)

测试onnx模型是否可用

# 测试onnx模型,需安装onnx
pip install onnx

测试代码:

import onnx
# 验证模型onnx格式
model = onnx.load('cnn.onnx')
onnx.checker.check_model(model)

加载测试模型

# 加模型必备(CPU) 如果使用GPU,目前还没尝试
pip install onnxruntime

加载代码:

import onnxruntime
# 加载模型
ort_session = onnxruntime.InferenceSession("cnn.onnx")
# 输入图像 注意:图像需要预处理,还需转np.array格式
ortvalue = onnxruntime.OrtValue.ortvalue_from_numpy(img1)

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

ort_inputs = {ort_session.get_inputs()[0].name: ortvalue}
ort_outs = ort_session.run(None, ort_inputs)


dist = {0: "猫", 1: "狗"}
# 转numpy格式,列表内取第一个
a1 = dist[ort_outs[0][0].argmax()]
print(a1)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值