如何把Tensorflow模型转换成TFLite模型

深度学习迅猛发展,目前已经可以移植到移动端使用了,TensorFlow推出的TensorFlow Lite就是一款把深度学习应用到移动端的框架技术。

使用TensorFlowLite 需要tflite文件模型,这个模型可以由TensorFlow训练的模型转换而成。所以首先需要知道如何保存训练好的TensorFlow模型。

一般有这几种保存形式:

  1. Checkpoints
  2. HDF5
  3. SavedModel等

保存与读取CheckPoint

当模型训练结束,可以用以下代码把权重保存成checkpoint格式

model.save_weights('./MyModel',True)

checkpoints文件仅是保存训练好的权重,不带网络结构,所以做predict时需要结合model使用
如:

model = keras_segmentation.models.segnet.mobilenet_segnet(n_classes=2, input_height=224, input_width=224)
model.load_weights('./MyModel')

保存成H5

把训练好的网络保存成h5文件很简单

model.save('MyModel.h5')

H5转换成TFLite

这里是文章主要内容

我习惯使用H5文件转换成tflite文件

官网代码是这样的

converter = tf.lite.TFLiteConverter.from_keras_model_file('newModel.h5')
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

但我用的keras 2.2.4版本会报下面错误,好像说是新版的keras把relu6改掉了,找不到方法
ValueError: Unknown activation function:relu6

于是需要自己定义一个relu6

import tensorflow as tf
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}):
    converter = tf.lite.TFLiteConverter.from_keras_model_file('newModel.h5')
    tflite_model = converter.convert()
    open("newModel.tflite", "wb").write(tflite_model)

看到生成的tflite文件表示保存成功了

也可以这么查看tflite网络的输入输出

import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="newModel.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

print(input_details)
print(output_details)

输出了以下信息

[{'name': 'input_1', 'index': 115, 'shape': array([  1, 224, 224,   3]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}]

[{'name': 'activation_1/truediv', 'index': 6, 'shape': array([    1, 12544,     2]), 'dtype': <class 'numpy.float32'>, 'quantization': (0.0, 0)}]

两个shape分别表示输入输出的numpy数组结构,dtype是数据类型

下一篇会分享如何在PC端测试TFLite模型

### 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轻松达成目标;与此同时也要注意某些特殊情况下的额外配置工作以保障整个迁移链条顺畅无误。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DvLee1024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值