pytorch模型转tflite

pytorch模型转tflite

参考文档:

1.https://blog.youkuaiyun.com/computerme/article/details/84144930

2.https://blog.youkuaiyun.com/qq_40600539/article/details/123142541

配置环境:

# tensorflow        2.4.0
# onnx              1.8.0
# onnx-tensorflow   1.8.0 [onnx-tf]
# tf-nightly        2.9.0
# pytorch           1.8.0

参考代码

import os

os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

import onnx
from onnx_tf.backend import prepare
import tensorflow as tf
from onnxsim import simplify
import onnxruntime as ort
import numpy as np
import torch.nn as nn
import torch

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        conv1 = nn.Sequential(
            nn.Conv2d(3, 32, 3, 2),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2, 2))
        conv2 = nn.Sequential(
            nn.Conv2d(32, 64, 3, 1, groups=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2, 2))
        self.feature = nn.Sequential(conv1, conv2)
        self.init_weights()

    def forward(self, x):
        return self.feature(x)

    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(
                    m.weight.data, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    m.bias.data.zero_()
            if isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

if __name__ == '__main__':
    model = Model()
    # Converting model to ONNX
    for _ in model.modules():
        _.training = False

    test_arr = np.random.randn(1, 3, 480, 640).astype(np.float32)
    sample_input = torch.tensor(test_arr)
    # sample_input = torch.randn(1, 3, 480, 640)
    input_nodes = ['input']
    output_nodes = ['output']

    model(sample_input)

    torch.onnx.export(model, sample_input, "model.onnx", export_params=True, input_names=input_nodes,
                      output_names=output_nodes, opset_version=11)

    model = onnx.load("model.onnx")
    ort_session = ort.InferenceSession('model.onnx')
    onnx_outputs = ort_session.run(None, {'input': test_arr})
    print('Export ONNX!')

    onnx_model = onnx.load("model.onnx")
    model_simp, check = simplify(onnx_model)
    assert check, "Simplified ONNX model could not be validated"

    output = prepare(model_simp)
    output.export_graph("tf_model/")
    print('Export tf_model!')

    converter = tf.lite.TFLiteConverter.from_saved_model("tf_model")
    tflite_model = converter.convert()
    open("model.tflite", "wb").write(tflite_model)
    print('Export tf lite model!')
### TFLiteONNX过程中IndexError解决方案 当尝试将TensorFlow Lite (TFLite) 模型换为ONNX格式时,如果遇到`list index out of range`错误,这通常意味着在处理模型结构或操作符映射的过程中出现了索引越界的情况。此问题可能源于几个方面: #### 错误原因分析 1. **不兼容的操作符** 不同框架支持的操作符集存在差异,在某些情况下,TFLite中的特定算子无法被正确识别并映射到ONNX中,从而导致解析过程失败[^1]。 2. **版本冲突** 使用的不同库之间可能存在版本不匹配的问题,比如tflite-converter、onnx以及相关依赖项之间的版本不一致可能导致此类异常发生[^2]。 3. **输入输出张量定义不当** 如果原始TFLite模型的输入/输出节点配置不符合预期,则可能会引起后续换流程中的数组访问超出界限等问题[^3]。 #### 解决方法建议 针对上述潜在成因,可以采取如下措施来解决问题: - 更新至最新稳定版的相关工具链(如tensorflow, tf2onnx),确保各组件间良好协作; - 对于特殊自定义层或者尚未完全适配的新特性,考虑手动调整源码实现以适应目标平台需求; - 验证原生TFLite文件是否完好无损,并仔细核对其metadata部分关于input/output tensors的信息描述准确性; - 尝试简化待迁移网络架构设计,移除不必要的复杂度直至能够顺利完成整个化链条为止。 下面给出一段Python脚本用于展示如何利用`tf2onnx.convert.from_tflite()`函数来进行基本类型的互工作,注意这里假设所有必要的环境变量均已设置完毕且不存在任何已知bug影响正常使用体验: ```python import tensorflow as tf import tf2onnx # 加载TFLITE模型 model_path = "path/to/model.tflite" interpreter = tf.lite.Interpreter(model_path=model_path) # 执行换 output_path = "converted_model.onnx" spec = (tf.TensorSpec((None, 28, 28, 1), dtype=tf.float32), ) # 替换为实际输入规格 _, _ = tf2onnx.convert.from_tflite(interpreter.get_tensor(0).shape, input_signature=spec, opset=13, output_path=output_path) print(f"Model successfully converted and saved to {output_path}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值