使用TensorFlow Lite在边缘设备上进行机器学习

304 阅读7分钟

使用TensorFlow Lite在边缘设备上进行机器学习

边缘设备是生活在网络 "边缘 "的计算设备,在需要的确切位置执行工作。边缘设备包括物联网设备智能家居设备和作为家用或工业物品嵌入的计算机。物联网设备正在快速增长,并在未来几年内继续增长。

img

img

图片来源。Udacity

上图显示了机器学习系统中的传统数据流。一个设备从环境中收集信息,这些信息通过网络连接发送到执行推理的后端服务器。如果有必要,服务器会将一些数据发回给设备。

img

图片来源。Udacity

但我们可以在设备本身进行推理,我们可以跳过一堆步骤。这有很大的好处

  • 带宽。我们可以使用设备上的推理,在需要时发送少量的数据,而不是将大量的数据发送到服务器上再返回。这对于没有适当互联网的偏远地区很有用。
  • 延迟。向服务器发送数据涉及到一个往返的延迟,这在处理实时数据时很碍事。当我们的模型在边缘时,这就不再是一个问题了。当推理速度超快时,我们可以解决高性能的行动,如机器人的实时物体跟踪。
  • 隐私和安全。当数据停留在设备上时,用户可以从增加的隐私和安全中受益,因为个人信息从未离开他们的设备。这有利于对隐私敏感的应用,如安全网络摄像机和医疗保健数据。

RaspberryPi + TensorFlow Lite

树莓派(R Pi)是一种低成本、非常小的计算机,运行基于Linux的操作系统,称为Raspbian或Raspberry Pi OS。它经常被用来构建原型设备,因为它有相当典型的硬件规格,而且很容易连接到传感器和外围设备,如摄像头。

TensorFlow是一个流行的开源机器学习框架,它被用于各种任务。TensorFlow Lite是一个轻量级库,用于在移动和嵌入式设备上部署模型。它是一个较轻的、功能较少的深度学习框架,用于设备上的推理。TensorFlow lite提供了Python(我们将在Raspberry Pi上使用)、Java(用于Android)和Swift(用于iOS)的API。我们可以在日常应用中看到Tensorflow lite的作用,例如--Gmail将TensorFlow Lite用于智能回复和自动补全。谷歌助理将其用于自然语言处理和理解。TensorFlow Lite可以用在开发、推断和部署TensorFlow模型在内存或CPU容量方面效率不高的地方。

如何使用TensorFlow lite

TensorFlow lite有两个主要组件。

  • TensorFlow Lite转换器。训练神经网络是一个耗时的过程,尤其是在一个大数据集上。因此,我们 保存训练神经网络是一个耗时的过程,尤其是在大型数据集上。 .h5SavedModel 。保存一个模型使其更容易分享和部署该模型。TensorFlow lite转换器被用来将这些模型转换为有效的形式供解释器使用。

一个在MNIST数据上训练的简单图像分类模型的SavedModel ,其大小为1.5 MB,同样的模型转换为.tflite ,约为300 KB。

  • TensorFlow Lite 解释器。TensorFlow Lite解释器在许多不同的硬件类型上运行特别优化的模型,包括移动电话、嵌入式Linux设备和微控制器。

使用TensorFlow lite的开发工作流程包括以下步骤。

  1. 选择一个模型。一个模型是一个数据结构,它包含了为解决一个特定问题而训练的机器学习网络的逻辑和知识。我们可以为定制的业务问题训练我们自己的模型,或者从TensorFlow Hub获得一个预训练的模型。
  2. 转换模型。TensorFlow lite被设计为在移动和其他嵌入式设备上有效地执行模型,其计算和内存资源有限。这种效率的一部分来自于使用一种特殊的格式来存储模型。TensorFlow模型在被TensorFlow Lite使用之前必须被转换为这种格式。TensorFlow Lite转换器是一个以Python API形式提供的工具,它将训练好的TensorFlow模型转换为TensorFlow Lite格式。
  3. 用模型运行推理。推理是通过一个模型运行数据以获得预测的过程。它需要一个模型,一个解释器,和输入数据。
  4. 优化模型。TensorFlow Lite提供工具来优化你的模型的大小和性能,通常对精度的影响最小。模型优化工具包

开始使用

运行TensorFlow lite解释器的最佳方式是运行python脚本。你可以从源代码构建Tensorflow或使用pip 安装Tensorflow lite解释器包。对于前一种方法,请访问文档指南。当你想转换一个模型或训练一个模型时,从源码构建是很有用的。

TensorFlow lite的厉害之处在于,你不需要成为一个机器学习专家就可以开始做很酷的实验。唯一的先决条件是有Python的基本知识。深度学习的最常见的应用(如物体检测、姿势估计、智能回复......)已经被社区实现了,它们可供开发者现成使用。在这篇文章中,我们将进行图像分类,这是深度学习中最常见的应用之一。

图像分类

一个图像分类模型需要一个图像文件并预测该图像是什么或代表什么。一个图像分类模型被训练来识别各种类别的图像。在本教程中,我们将使用mnist 数据集并训练一个神经网络来识别手写数字(最常用的数据集)。我使用TensorFlow 2(而不是TensorFlow lite)来建立一个模型并进行训练,然后将该模型转换成TF lite模型。

要安装Tensorflow:pip install tensorflow

import tensorflow as tf
# prepping the data
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.0
test_images = test_images / 255.0

#building the model
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

#train the model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10)

#converting to TF Lite
model.save("my_model)
converter = tf.lite.TFLiteConverter.from_saved_model("my_model")
tflite_model = converter.convert()
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

使用预训练模型进行图像分类

在命令行中运行以下命令来设置下载文件和软件。

pip3 install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl

$ wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/mobilenet_v1_1.0_224_quant_and_labels.zip

我们使用MobileNet图像分类模型。MobileNet是一个预训练的模型,这意味着它已经在一个非常大的数据集上进行了训练,对超过1000类的图像进行分类,包括人物、物体、动物等。

image-classification.py

img

图片来源。TensorFlow.org

from tflite_runtime.interpreter import Interpreter
from PIL import Image
import numpy as np
#load the model
interpreter = Interpreter(model_path="mobilenet_v1_1.0.224.tflite")
#allocate memory for the model
interpreter.allocate_tensors()
#get model input tensors details.
input_details = interpreter.get_input_details()
#gets model output details. Returns a list of output details.
output_details = interpreter.get_ouptut_details()
#load image from memory
img = Image.open(filename).convert("RGB")
#preprocess the image
img = img.resize((224, 224))
#converting image to an numpy array
input_data = np.array(img)
#np.expand_dims expands the shape of an array. This is done to take into account the *batch* dimension.
input_data = np.expand_dims(input_data, axis=0)
#Point data to be used for testing the interpreter and run it
interpreter.set_tensor(input_details[0]["index"], input_data)
#invoke the interpreter for inference
interpreter.invoke()
#Obtain Results. The function get_tensor() returns a copy of the tensor data.
predictions = interpreter.get_tensor(output_details[0]["index"])
#The model outputs a probability for every class it has been trained on, we take the top 10 most probable classes.
top_indices = np.argsort(predictions)[::-1][:10]

print(labels[top_indices[0]], predictions[top_indices[0]])

我们可以预期样本的输入和输出是。

img

TensorFlow Lite和TensorFlow的兼容性

TensorFlow lite支持一些用于获得预测的TensorFlow操作。由于TensorFlow操作是为TensorFlow lite优化的,它们可以被省略或组合。由于TensorFlow Lite的操作集比TensorFlow的小,所以不是每个模型都可以转换。即使是支持的操作,有时也会因为性能的原因,预计会有非常特殊的使用模式。请参考本指南,了解支持和不支持的操作的完整列表。

结论

机器学习是一个强大的工具,它可以帮助自动化许多超出经典编程范围的任务,它被认为需要一个强大的带有GPU的计算机器来训练模型。但随着硬件的发展和低端计算设备软件的优化,我们可以在微控制器、移动电话、智能家居设备等设备上执行复杂的机器学习任务。