Pytorch模型转Tensorflow模型

引言

最近收到领导布置的一个小任务,需要将pth文件转换到tensorflow模型。这里将采用领导给的pytorchocr代码,来记录下如何进行模型转换。

一、基本思想

想要将pytorch训练得到的pth文件转换到tensorflow的pb文件,基本思想就是先将pth转成onnx,再又onnx转换到pb文件。整体没什么难度,我在下面直接给出代码。

二、转换代码

转换代码如下,我这里采用的是pytorchocr网络,有了具体网络结构就可以进行onnx转换,最后到tensorflow转换。

复制代码
import torch
import torchvision
import tensorflow as tf
from onnx_tf.backend import prepare
from pytorchocr.base_ocr_v20 import BaseOCRV20
import onnx

det_model_path = "E:\File\ckpt\pytorch\det.pth"
# det_model_path = r"D:\File_save\pycharm\demo\Script\ckpt\pytorch\rec.pth"

class PPOCRv3DetConverter(BaseOCRV20):
    def __init__(self, config, **kwargs):
        super(PPOCRv3DetConverter, self).__init__(config, **kwargs)
        # self.load_paddle_weights(paddle_pretrained_model_path)
        self.net.eval()
        # self.training = False


cfg = {'model_type':'det',
           'algorithm':'DB',
           'Transform':None,
           'Backbone':{'name':'MobileNetV3', 'model_name':'large', 'scale':0.5, 'disable_se':True},
           'Neck':{'name':'RSEFPN', 'out_channels':96, 'shortcut': True},
           'Head':{'name':'DBHead', 'k':50}

       }

# cfg = {'model_type': 'rec',
#        'algorithm': 'CRNN',
#        'Transform': None,
#        'Backbone': {'name': 'MobileNetV1Enhance',
#                     'scale': 0.5,
#                     'last_conv_stride': [1, 2],
#                     'last_pool_type': 'avg'},
#        'Neck': {'name': 'SequenceEncoder',
#                 'dims': 64,
#                 'depth': 2,
#                 'hidden_dims': 120,
#                 'use_guide': True,
#                 'encoder_type': 'svtr'},
#        'Head': {'name': 'CTCHead', 'fc_decay': 2e-05}
#        }

converter = PPOCRv3DetConverter(cfg)
converter.load_state_dict(torch.load(det_model_path))
# det
dummy_input = torch.randn(1, 3, 640, 640)
# rec
# dummy_input = torch.randn(1, 3, 48, 320)

det_model = converter.net

# 设置模型为评估模式
converter.net.eval()

# 导出模型为ONNX格式
# torch.onnx.export(det_model, dummy_input, 'rec_model.onnx', verbose=False, opset_version=11)
# torch.onnx.export(det_model, dummy_input, 'det_model.onnx', verbose=False, opset_version=12)

# 加载ONNX模型
onnx_model = onnx.load('E:\File\ckpt\onnx\det_model.onnx')
# onnx_model = onnx.load(r'D:\File_save\pycharm\demo\Script\ckpt\rec_model.onnx')
#
# 转换为TensorFlow模型
tf_model = prepare(onnx_model, strict=False)
#
# 保存为TensorFlow模型文件
tf_model.export_graph('det_model.pb')
# tf_model.export_graph('rec_model.pb')
# #
# tf.compat.v1.reset_default_graph()
# with tf.compat.v1.Session() as sess:
#     with tf.gfile.GFile('det_model.onnx', 'rb') as f:
#         graph_def = tf.compat.v1.GraphDef()
#         graph_def.ParseFromString(f.read())
#         tf.import_graph_def(graph_def, name='')
#
#     # 保存为.pb文件
#     tf.io.write_graph(sess.graph, '', 'det_model.pb', as_text=False)
相关推荐
a1117764 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得04 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
ar01234 小时前
AR远程协助作用
人工智能·ar
北京青翼科技4 小时前
PCIe接口-高速模拟采集—高性能计算卡-青翼科技高品质军工级数据采集板-打造专业工业核心板
图像处理·人工智能·fpga开发·信号处理·智能硬件
软件聚导航5 小时前
马年、我用AI写了个“打工了马” 小程序
人工智能·ui·微信小程序
陈天伟教授6 小时前
人工智能应用-机器听觉:7. 统计合成法
人工智能·语音识别
笨蛋不要掉眼泪6 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
昨夜见军贴06166 小时前
IACheck AI审核技术赋能消费认证:为智能宠物喂食器TELEC报告构筑智能合规防线
人工智能·宠物
摘星编程6 小时前
OpenHarmony + RN:Calendar日期选择功能
python
DisonTangor6 小时前
阿里开源语音识别模型——Qwen3-ASR
人工智能·开源·语音识别