导出、校验pytorch为onnx模型

该代码示例展示了如何将一个预训练的PyTorchmobilenet_v3_large模型加载并调整,然后导出为ONNX格式。首先,模型的输出层被修改以适应特定的类别数。接着,使用torch.onnx.export函数将模型转换为ONNX模型,并进行简化。最后,使用ONNXRuntime测试转换后的模型,确保其能正确运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以torchvision中mobilenet_v3_large模型为例

import torch
import onnx

import numpy as np
import torch.nn as nn
import onnxruntime as ort

from torchvision.models import *

torch_model = torch.load("***.pth") # pytorch模型加载
model = mobilenet_v3_large(pretrained=True)
num_ftrs = model.classifier[3].in_features
model.classifier[3] = nn.Linear(num_ftrs, 7) # 类别数量

model.load_state_dict(torch_model) 
dummy_input = torch.ones(1, 3, 112, 112)  # 输入图像大小

#测试pt模型
model.eval()
outputs = model(dummy_input)
print("pt_out:",outputs[0])

export_onnx_file = "0423***.onnx"          # 目的ONNX文件名
torch.onnx.export(model.eval(), dummy_input, export_onnx_file, verbose=False, input_names=["input"], output_names=["output"], opset_version=10)
print("======================== convert onnx Finished! .... ")

try:
    import onnxsim
    onnx_model = onnx.load(export_onnx_file)
    print('\nStarting to simplify ONNX...')
    sim_onnx_model, check = onnxsim.simplify(onnx_model)
    assert check, 'assert check failed'
except Exception as e:
    print(f'Simplifier failure: {e}')
onnx.save(sim_onnx_model,export_onnx_file)
print("Success to Simplify !!!")


#测试onnx
input_onnx = dummy_input.numpy().astype(np.float32)
ort_session = ort.InferenceSession('./0423***.onnx')
outs = (ort_session.run(None, {'input': input_onnx}))
print("onnx_out:",outs[0][0])

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值