目录
介绍
什么是TensorFlow Lite?
TensorFlow Lite转换器
运行TensorFlow Lite模型
下一步
- 下载 g_model_BtoA_005730.zip - 124.8 MB
- 下载 g_model_AtoB_005730.zip - 124.8 MB
在本系列文章中,我们将展示一个基于循环一致对抗网络(CycleGAN)的移动图像到图像转换系统。我们将构建一个CycleGAN,它可以执行不成对的图像到图像的转换,并向您展示一些有趣但具有学术深度的例子。我们还将讨论如何将这种使用TensorFlow和Keras构建的训练有素的网络转换为TensorFlow Lite并用作移动设备上的应用程序。
我们假设您熟悉深度学习的概念,以及Jupyter Notebooks和TensorFlow。欢迎您下载项目代码。
在上一篇文章中,我们使用TensorFlow和Keras实现了CycleGAN。在本文中,我们将向您展示如何将保存的模型转换为TensorFlow Lite,作为在Android上运行它的第一步。
什么是TensorFlow Lite?TensorFlow Lite是TensorFlow的轻量级版本。此轻量级版本允许您在移动和嵌入式设备上以低延迟运行模型,同时执行分类、回归等任务。目前,TensorFlow Lite通过C++ API支持Android和iOS。此外,TensorFlow Lite有一个解释器,可以使用Android神经网络 API在支持它的Android设备上进行硬件加速。在不支持的设备上,TensorFlow Lite默认由CPU执行。在本文中,我们将重点介绍在Android应用程序中部署TensorFlow Lite。
TensorFlow Lite并非旨在训练模型。因此,通常的做法是通过TensorFlow在高功率机器上训练模型,然后将训练好的模型转换为TensorFlow Lite(.tflite格式)。然后将.tflite模型加载到解释器中,如下图所示。
TensorFlow Lite转换器将TensorFlow模型(model.h5) 转换为可作为应用程序部署在移动设备上的TensorFlow Lite (.tflite)模型。此转换器的运行方式取决于模型的保存方式。我们的CycleGAN模型被保存为Keras模型。因此,我们将使用以下脚本将其转换为TensorFlow Lite:
# Load the trained Keras CycleGAN model
from tensorflow import keras
model = keras.models.load_model('path/to/location')
# Convert the model
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
上面的脚本生成了一个.tflite模型,它几乎可以在Android上运行了。
运行TensorFlow Lite模型在设备上执行的TensorFlow Lite模型执行推理,旨在对输入数据进行预测。要使用我们的TensorFlow Lite模型执行推理,我们必须通过解释器运行它。TensorFlow Lite推理包括的最重要步骤是:
- 加载模型:首先,我们必须加载转换后的.tflite模型。
- 转换数据:如果某些输入数据不符合预期的输入大小和格式,我们可能需要执行调整大小和更改图像格式等处理。
- 运行推理:我们使用TensorFlow API执行转换后的模型。这涉及构建解释器和分配张量,我们将在下一篇文章中详细讨论。
- 解释输出:最后,我们分析模型推理得到的结果。
TensorFlow推理API以多种编程语言提供给最常见的移动/嵌入式平台,例如Android、iOS和Linux。
在这个项目中,我们的目标是在Android平台上运行移动图像到图像的转换模型。因此,我们将专注于在Android上加载和运行我们的模型。
下一步在下一篇文章中,我们将向您展示如何设置适合加载和运行我们的.tflite模型的Android Studio环境。
https://www.codeproject.com/Articles/5307457/Converting-a-Style-Transfer-Model-from-TensorFlow