pytorch篇---权重转换之pth转onnx

pytorch 模型训练得到的权重(.pth)

转换成onnx

import io
import numpy as np
import torch
import torch.onnx
from model.nets.yolo4 import YoloBody
from conf.my_conf import anchors_path, classes_path, model_path_train


weight_file = '../data/weights/Epoch75-Total_Loss0.7506-Val_Loss1.6806.pth'
image_path = '../data/img/0617_Bin_026.jpg'
onnx_file_name = '../data/weights/Yolo_bin.onnx'
batch_size = 1
num_anchors, num_classes = 3, 3
IN_IMAGE_H = 416
IN_IMAGE_W = 416


model = YoloBody(num_anchors, num_classes)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# 加快模型训练的效率
model_dict = model.state_dict()
pretrained_dict = torch.load(weight_file, map_location=device)
pretrained_dict = {k: v for k, v in pretrained_dict.items() if np.shape(model_dict[k]) == np.shape(v)}
model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)

dummy_input1 = torch.randn((1, 3, IN_IMAGE_H, IN_IMAGE_W), requires_grad=True)
input_names = ["input"]  # onnx输入接口的名字,需要与模型输入结果对应
output_names = ["output0", "output1", "output2"]  # onnx输出接口的名字,需要与模型输出结果对应
dynamic_axes = {"input": {0: "batch_size"}, "output0": {0: "batch_size"}, "output1": {0: "batch_size"}, "output2": {0: "batch_size"}}


torch.onnx.export(model,
                  dummy_input1,
                  onnx_file_name,
                  export_params=True,
                  opset_version=11,
                  do_constant_folding=True,
                  input_names=input_names,
                  output_names=output_names,
                  dynamic_axes=dynamic_axes)

得到一个如下的权重文件
在这里插入图片描述

你可能感兴趣的:(深度学习,深度学习)