Pytorch转为onnx模型 (torch.onnx)

需要导入训练好的权重

import torch
from torch import nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.softmax(x, dim=1)
        return output


pytorch_model = Net()
pytorch_model.load_state_dict(torch.load('pytorch_model.pt'))
pytorch_model.eval()
dummy_input = torch.zeros(1,1,28,28)
torch.onnx.export(pytorch_model, dummy_input, 'onnx_model.onnx', verbose=True)

会生成

Pytorch转为onnx模型 (torch.onnx)_第1张图片

和load的那个权重一样大小

Pytorch转为onnx模型 (torch.onnx)_第2张图片

 

后续如果想将project做成demo或者想通过网页直观展示模型效果, 可以通过onnx.js

https://www.youtube.com/watch?v=Vs730jsRgO8

GShang2018/pytorch-to-javascript-with-onnx-js

你可能感兴趣的:(Pytorch)