pyTorch onnx小试《一》

环境安装(conda内)

conda create -n onnx python=3.7 -y
conda activate onnx
conda install -c conda-forge protobuf numpy
pip install onnx
conda install pytorch torchvision

pyTorch版本AlexNet模型转换到onnx

import torch
import torchvision

dummy_input = torch.randn(10, 3, 224, 224, device='cuda') #定义输入的数据类型(B,C,H,W)为(10,3,224,224)
model = torchvision.models.alexnet(pretrained=True).cuda() #读入torchvision中已经训练好的alxnet模型
input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ]
output_names = [ "output1" ]
torch.onnx.export(model, dummy_input, "alexnet.onnx", keep_initializers_as_inputs=True, verbose=True, input_names=input_names, output_names=output_names)

在onnx中运行:

import onnx
# Load the ONNX model
model = onnx.load("alexnet.onnx")

# Check that the IR is well formed
onnx.checker.check_model(model)

# Print a human readable representation of the graph
onnx.helper.printable_graph(model.graph)

import caffe2.python.onnx.backend as backend
import numpy as np

rep = backend.prepare(model, device="CUDA:0") # or "CPU"
# For the Caffe2 backend:
#     rep.predict_net is the Caffe2 protobuf for the network
#     rep.workspace is the Caffe2 workspace for the network
#       (see the class caffe2.python.onnx.backend.Workspace)
outputs = rep.run(np.random.randn(10, 3, 224, 224).astype(np.float32))
# To run networks with more than one input, pass a tuple
# rather than a single numpy ndarray.
print(outputs[0])

错误处理

  1. ModuleNotFoundError: No module named ‘past’
    处理方法:
pip install future
  1. IndexError: _Map_base::at
    处理方法:
    见 https://github.com/onnx/onnx/issues/2417

参考:
https://blog.youkuaiyun.com/u010946556/article/details/82734216?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
https://github.com/nilmtk/nilmtk/issues/548
https://github.com/onnx/onnx/issues/2417

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值