如何CRNN模型训练的pth模型转onnx模型

输入是不定长的文本,通过dynamic_axes={"input": {0:"batch_size",3: "img_w"}}来设置动态输入值

import torch
from lib.utils.utils import strLabelConverter
from lib.models.crnn import CRNN
from collections import OrderedDict
from torch.autograd import Variable
alphabet = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'
nh = 256
def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)
model = CRNN(32, 3, len(alphabet) + 1, 256, n_rnn=2, leakyRelu=False)
model.apply(weights_init)
new_state_dict = OrderedDict()
checkpoint = torch.load('models/checkpoint.pth')
for k, v in checkpoint.items():
    print(v)
    name = k
    if k == 'state_dict':
        continue
    if k=='epoch':
        continue
    if k == 'best_acc':
        continue
    new_state_dict[name] = v
model.load_state_dict(checkpoint['state_dict'])
converter = strLabelConverter(alphabet)
# transformer = resizeNormalize((500, 32))
model.eval()
print('Finished loading model!')
print(model)
rnn_input = torch.randn(1, 3, 32, 320)
##################export###############
input_names = ["input"]
output_names = ["out"]
onnx_file_path = 'models/checkpoint.onnx'
torch.onnx.export(model, rnn_input, onnx_file_path, verbose=False,input_names=input_names,output_names=output_names,dynamic_axes={"input": {0:"batch_size",3: "img_w"}}, keep_initializers_as_inputs=True, opset_version=11, export_params=True)
# torch.onnx.export(





如果有些变量名提示没有,那么可以通过该代码段来过滤掉:

for k, v in checkpoint.items():
    print(v)
    name = k
    if k == 'state_dict':
        continue
    if k=='epoch':
        continue
    if k == 'best_acc':
        continue
    new_state_dict[name] = v

如果你训练的单通道图像,那么下面代码中的通道值3要换成1:

model = CRNN(32, 3, len(alphabet) + 1, 256, n_rnn=2, leakyRelu=False)

alphabet值就是你自己工程里训练的字典值。

就这么多吧,还有什么疑问可以留言问,看到会回答的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序小K

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

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

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

打赏作者

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

抵扣说明:

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

余额充值