pytorch转onnx模型(支持batch输入)

1.简略版-python转化代码: 

import torch
import torchvision

# use Trace to export onnx model
dummy_input = torch.randn(10, 3, 224, 224, device='cuda')  # 定义模型的输入shape
model = torchvision.models.alexnet(pretrained=True).cuda()  # if delete cuda(), will generate onnx model with no cuda.

input_names = ['inputs']
output_names = ['outputs']

torch.onnx.export(model, dummy_input, f='alexnet.onnx', verbose=True, input_names=input_names,
                  output_names=output_names, opset_version=10)  # generate onnx model of 244M



生成的onnx结构

2.完整版

import numpy as np
import onnx
import onnxruntime
from torch import nn
import torch.nn.init as init
import torch.utils.model_zoo as model_zoo
import torch.onnx

# super resolution
# https://arxiv.org/abs/1609.05158

"""
save pytorch model to torch.onnx model

and verify the model by using onnx.
"""


class SuperResolutionNet(nn.Module):
    def __init__(self, upscale_factor, inplace=False):
        super(SuperResolutionNet, self).__init__()

        self.relu = nn.ReLU(inplace=inplace)
        self.conv1 = nn.Conv2d(1, 64, (5, 5), 1, 2)
        self.conv2 = nn.Conv2d(64, 64, (3, 3), 1, 1)
        self.conv3 = nn.Conv2d(64, 32, (3, 3), 1, 1)
        self.conv4 = nn.Conv2d(32, upscale_factor ** 2, (3, 3), 1, 1)
        self.pixel_shuffle = nn.PixelShuffle(upscale_factor=upscale_factor)

        self._initialize_weights()

    def forward(self, x):
        x = self.relu(self.conv1(x))
        x = self.relu(self.conv2(x))
        x = self.relu(self.conv3(x))
        x = self.pixel_shuffle(self.conv4(x))
        return x

    def _initialize_weights(self):
        init.orthogonal_(self.conv1.weight, gain=init.calculate_gain('relu'))
        init.orthogonal_(self.conv2.weight, gain=init.calculate_gain('relu'))
        init.orthogonal_(self.conv3.weight, gain=init.calculate_gain('relu'))
        init.orthogonal_(self.conv4.weight)


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


if __name__ == '__main__':
    # Create the super-resolution model by using the above model definition
    torch_model = SuperResolutionNet(upscale_factor=3)

    model_url = 'https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr.Q

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

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

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

打赏作者

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

抵扣说明:

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

余额充值