tensorflow模型转换成tensorflow lite模型

本文详细介绍了如何将预训练的Mobilenet_v1_1.0_224模型从TensorFlow GraphDef格式转换为Frozen Graph及TFLite格式,适用于移动端部署。同时,分享了将自定义训练模型转换为TFLite格式的方法,包括直接使用toco工具和通过Python API实现。

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

1、转换mobilenet_v1_1.0_224模型

之前实践过,但是由于长时间没做,当时也没写笔记所以后续也浪费了一点时间

对应的google已经训练好的模型可以在这里下载

https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md

其中frozen_graph的输入文件使用到的有mobilenet_v1_1.0_224.ckpt.*+mobilenet_v1_1.0_224_eval.pbtxt

使用的命令如下:

freeze_graph

--input_graph=C:\Users\judy.yuan\_bazel_judy.yuan\i7fa2ce7\execroot\org_tensorflow\bazel-out\x64_windows-opt\bin\tensorflow\lite\toco\test\mobilenet_v1_1.0_224_eval.pbtxt

--input_checkpoint=C:\Users\judy.yuan\_bazel_judy.yuan\i7fa2ce7\execroot\org_tensorflow\bazel-out\x64_windows-opt\bin\tensorflow\lite\toco\test\mobilenet_v1_1.0_224.ckpt

--output_graph=C:\Users\judy.yuan\_bazel_judy.yuan\i7fa2ce7\execroot\org_tensorflow\bazel-out\x64_windows-opt\bin\tensorflow\lite\toco\test\mobilenet_v1_1.0_224_frozen_judy.pb

--output_node_names=MobilenetV1/Predictions/Reshape_1

执行该命令之后会生成frozen的pb文件

 

生成冻图之后需要的是生成tflite的文件

toco

--input_file=C:\Users\hui.yuan\_bazel_judy.yuan\i7fa2ce7\execroot\org_tensorflow\bazel-out\x64_windows-opt\bin\tensorflow\lite\toco\test\mobilenet_v1_1.0_224_frozen_judy.pb

--output_file=C:\Users\hui.yuan\_bazel_judy.yuan\i7fa2ce7\execroot\org_tensorflow\bazel-out\x64_windows-opt\bin\tensorflow\lite\toco\test\mobilenet_v1_1.0_224_frozen_judy.tflite

--input_shape="1,224, 224,3"

--input_array=input

--output_array=MobilenetV1/Predictions/Reshape_1

2、转换自己训练的module

第一种方法是直接在toco cmd

toco --input_file=****_frozen.pb --output_file=****.tflite --input_shape="1,49" --input_array=inputs/input --output_array=layer5/logits

执行该命令一定需要在toco应用程序所在目录

还有一种方法目前正在尝试

import tensorflow as tf
convert=tf.lite.TFLiteConverter.from_frozen_graph("model_proc_mobile_fps.pb",input_arrays=["inputs/input"],output_arrays=["layer5/logits"],
                                                  input_shapes={"inputs/input":[1,49]})
convert.post_training_quantize=False
tflite_model=convert.convert()
open("quantized_model.tflite","wb").write(tflite_model)

其中对应的tensorflow的版本为1.13.1

 

进行toco转换的时候需要输入--input_array= 和 --output_array= 这些信息可以由下面这个脚本得出

    gf = tf.GraphDef()
    gf.ParseFromString(open('save/model.pb','rb').read())
    for n in gf.node:
        print ( n.name +' ===> '+n.op )

实例

import tensorflow as tf
import numpy as np
from tensorflow.python.framework import graph_util

with tf.Session(graph=tf.Graph()) as sess:
    # 使用 NumPy 生成假数据(phony data), 总共 100 个点.
    with tf.name_scope("input"):
        x = tf.placeholder(tf.float32, [1, 10], name='input0')
    
    
    x_data = np.float32(np.random.rand(1, 10)) # 随机输入
    print(x_data)
    
    # 构造一个线性模型
    # 
    with tf.name_scope('bias'):
        b = tf.Variable(tf.zeros([1]), name='b')
        print(b)
    with tf.name_scope('weight'):
        W = tf.Variable(tf.random_uniform([1, 1], -1.0, 1.0), name='weight')
        print(W)
    with tf.name_scope('output'):
        y = tf.matmul(W,x) + b
        print(y)
    
    """
    # 最小化方差
    with tf.name_scope('mean'):
        loss = tf.reduce_mean(tf.square(y))
        print("loss")
        print(loss)
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    print("optimizer")
    print(optimizer)
    train = optimizer.minimize(loss)
    print("train")
    print(train)
    """
    
    # 初始化变量
    init = tf.initialize_all_variables()
    
    # 启动图 (graph)
    sess.run(init)
    
    # 拟合平面
    for step in range(0, 201):
        
        #sess.run(train, feed_dict)
        if step % 20 == 0:
            print(step, sess.run(W), sess.run(b))
    input_x = np.float32([[1,2,0,0,0,0,0,0,0,0]])
    feed_dict = {x: input_x}
    print(sess.run(y, feed_dict))
    constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['output/add'])
    
    saver = tf.train.Saver()
    model_path = "kk/model.ckpt"
    save_path = saver.save(sess, model_path)
    
    with tf.gfile.GFile('kk/model.pb', mode='wb') as f: #模型的名字是model.pb
        f.write(constant_graph.SerializeToString())
    
    gf = tf.compat.v1.GraphDef()
    gf.ParseFromString(open('kk/model.pb','rb').read())
    print("\n\n\n")
    for n in gf.node:
        print ( n.name +' ===> '+n.op )
    
    
    convert=tf.lite.TFLiteConverter.from_frozen_graph("kk/model.pb",input_arrays=["input/input0"],output_arrays=["output/add"],
                                                  input_shapes={"input/input0":[1,10]})
    convert.post_training_quantize=False
    tflite_model=convert.convert()
    open("kk/model.tflite","wb").write(tflite_model)
    

输入是10组数据,输出也是10组数据

1, 2, 0, 0, 0, 0, 0, 0, 0, 0],

放在手机中解析后,使用模型推理出来的结果如下:

Loaded model model.tflite
resolved reporter
num 0batch 1
invoked
average time: 0.011 ms
Inference output 0 value is -0.0405481
Inference output 1 value is -0.0810962
Inference output 2 value is 0
Inference output 3 value is 0
Inference output 4 value is 0
Inference output 5 value is 0
Inference output 6 value is 0
Inference output 7 value is 0
Inference output 8 value is 0
Inference output 9 value is 0
grade(0-4), Inference grade is :2
num 1batch 1

### TensorFlow模型转换为TensorFlow Lite的方法教程 将TensorFlow模型转换为TensorFlow Lite(TFLite)是一个常见的需求,尤其是在需要在移动设备或嵌入式系统上部署机器学习模型时。以下是关于这一过程的具体方法和注意事项。 #### 1. 使用`tf.lite.TFLiteConverter`进行模型转换 TensorFlow提供了专门用于模型转换的工具——`TFLiteConverter`类。该工具可以根据不同的输入源执行转换操作[^3]。对于Keras模型文件(`.h5`),可以按照以下方式进行处理: ```python import tensorflow as tf # 加载Keras模型 model = tf.keras.models.load_model('path_to_your_model.h5') # 创建TFLite转换器实例 converter = tf.lite.TFLiteConverter.from_keras_model(model) # 执行转换 tflite_model = converter.convert() # 将转换后的模型保存到本地 with open('converted_model.tflite', 'wb') as f: f.write(tflite_model) ``` 上述代码展示了如何加载一个已有的Keras模型并将其转换为TFLite格式。 --- #### 2. 自定义激活函数的支持 如果模型中包含了自定义层或激活函数,则需要通过`CustomObjectScope`来注册这些对象以便于成功完成转换。例如,在实现ReLU6激活函数的情况下,可以通过如下方式解决兼容性问题: ```python from tensorflow.python.keras import backend as K from tensorflow.python.keras.utils import CustomObjectScope def relu6(x): return K.relu(x, max_value=6) # 注册自定义激活函数 with CustomObjectScope({'relu6': relu6}): # 加载带有自定义激活函数的Keras模型 model = tf.keras.models.load_model('custom_model.h5') # 进行TFLite转换 converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # 存储转换后的模型 with open('custom_converted_model.tflite', 'wb') as f: f.write(tflite_model) ``` 这段代码说明了当模型依赖特定功能(如ReLU6)时应采取的操作步骤[^2]。 --- #### 3. 验证转换后的模型性能 为了确保转换过程中不会丢失精度或者引入错误行为,建议验证原始TensorFlow模型与新生成的TFLite版本之间的预测一致性。这通常涉及以下几个方面: - **数据准备**:选取一组测试样本。 - **推理比较**:分别利用两种形式的模型计算输出并向量间差异评估其相似度水平。 --- #### 4. 参考Google官方语音命令识别案例 除了基本流程外,还可以参照由谷歌提供的实际应用范例进一步加深理解。比如下面链接中的项目就演示了一个完整的端到端解决方案,其中包括训练音频分类网络以及最终导出轻量化版供安卓客户端调用等功能模块[^4]: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/speech_commands --- #### 总结 综上所述,无论是标准架构还是特殊定制化场景下都可以借助内置API轻松达成目标;与此同时也要注意某些特殊情况下的额外配置工作以保障整个迁移链条顺畅无误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值