微控制器使用入门

本文档介绍如何使用微控制器训练模型和进行推断。

Hello World 示例

Hello World 示例旨在演示使用适用于微控制器的 TensorFlow Lite 的绝对基础知识。我们训练并运行一个复制正弦函数的模型,即它将单个数字作为输入,并输出该数字的正弦值。部署到微控制器后,其预测将用于闪烁 LED 或控制动画。

端到端工作流包括以下步骤:

  1. 训练模型(在 Python 中):一个 Python 文件,用于训练、转换和优化模型以供设备端使用。
  2. 运行推断(在 C++ 17 中):使用 C++ 库对模型运行推断的端到端单元测试。

获取受支持的设备

我们将使用的示例应用在以下设备上进行了测试:

如需详细了解支持的平台,请参阅适用于微控制器的 TensorFlow Lite

训练模型

使用 train.py 进行 hello world 模型训练以进行正波识别

运行:bazel build tensorflow/lite/micro/examples/hello_world:train bazel-bin/tensorflow/lite/micro/examples/hello_world/train --save_tf_model --save_dir=/tmp/model_created/

运行推理

为了在设备上运行该模型,我们将逐步完成 README.md 中的说明:

Hello World README.md

以下部分介绍了示例的 evaluate_test.cc,该单元测试演示了如何使用适用于微控制器的 TensorFlow Lite 进行推理。它会加载模型并运行多次推断。

1. 添加库头文件

如需使用适用于微控制器的 TensorFlow Lite 库,我们必须添加以下头文件:

#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/version.h"

2. 添加模型标头

适用于微控制器的 TensorFlow Lite 解释器要求模型以 C++ 数组的形式提供。模型在 model.hmodel.cc 文件中定义。标题包含以下行:

#include "tensorflow/lite/micro/examples/hello_world/model.h"

3. 添加单元测试框架头文件

为了创建单元测试,我们添加了以下代码行,以添加适用于微控制器的 TensorFlow Lite 单元测试框架:

#include "tensorflow/lite/micro/testing/micro_test.h"

该测试使用以下宏进行定义:

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(LoadModelAndPerformInference) {
  . // add code here
  .
}

TF_LITE_MICRO_TESTS_END

现在,我们讨论上述宏中包含的代码。

4. 设置日志记录

如需设置日志记录,请使用指向 tflite::MicroErrorReporter 实例的指针创建 tflite::ErrorReporter 指针:

tflite::MicroErrorReporter micro_error_reporter;
tflite::ErrorReporter* error_reporter = &micro_error_reporter;

此变量将传递给解释器,以便其写入日志。由于微控制器通常具有多种日志记录机制,因此 tflite::MicroErrorReporter 的实现需要根据您的特定设备进行自定义。

5. 加载模型

在以下代码中,使用 char 数组 (g_model) 中的数据对模型进行了实例化,该数组在 model.h 中声明。然后,我们会检查模型以确保其架构版本与我们所使用的版本兼容:

const tflite::Model* model = ::tflite::GetModel(g_model);
if (model->version() != TFLITE_SCHEMA_VERSION) {
  TF_LITE_REPORT_ERROR(error_reporter,
      "Model provided is schema version %d not equal "
      "to supported version %d.\n",
      model->version(), TFLITE_SCHEMA_VERSION);
}

6. 实例化操作解析器

声明了 MicroMutableOpResolver 实例。解释器将使用它来注册和访问模型使用的操作:

using HelloWorldOpResolver = tflite::MicroMutableOpResolver<1>;

TfLiteStatus RegisterOps(HelloWorldOpResolver& op_resolver) {
  TF_LITE_ENSURE_STATUS(op_resolver.AddFullyConnected());
  return kTfLiteOk;

MicroMutableOpResolver 需要一个模板参数,以指明将注册的操作数量。RegisterOps 函数向解析器注册操作。

HelloWorldOpResolver op_resolver;
TF_LITE_ENSURE_STATUS(RegisterOps(op_resolver));

7. 分配内存

我们需要为输入数组、输出数组和中间数组预先分配一定量的内存。这以大小为 tensor_arena_sizeuint8_t 数组的形式提供:

const int tensor_arena_size = 2 * 1024;
uint8_t tensor_arena[tensor_arena_size];

所需大小取决于您使用的模型,可能需要通过实验确定。

8. 实例化解释器

我们创建一个 tflite::MicroInterpreter 实例,传入之前创建的变量:

tflite::MicroInterpreter interpreter(model, resolver, tensor_arena,
                                     tensor_arena_size, error_reporter);

9. 分配张量

我们指示解释器从 tensor_arena 为模型张量分配内存:

interpreter.AllocateTensors();

10. 验证输入形状

MicroInterpreter 实例可以通过调用 .input(0) 向我们提供指向模型输入张量的指针,其中 0 表示第一个(也是唯一一个)输入张量:

  // Obtain a pointer to the model's input tensor
  TfLiteTensor* input = interpreter.input(0);

然后检查此张量,确认其形状和类型是否符合我们的预期:

// Make sure the input has the properties we expect
TF_LITE_MICRO_EXPECT_NE(nullptr, input);
// The property "dims" tells us the tensor's shape. It has one element for
// each dimension. Our input is a 2D tensor containing 1 element, so "dims"
// should have size 2.
TF_LITE_MICRO_EXPECT_EQ(2, input->dims->size);
// The value of each element gives the length of the corresponding tensor.
// We should expect two single element tensors (one is contained within the
// other).
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[0]);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[1]);
// The input is a 32 bit floating point value
TF_LITE_MICRO_EXPECT_EQ(kTfLiteFloat32, input->type);

枚举值 kTfLiteFloat32 是对某种 TensorFlow Lite 数据类型的引用,在 common.h 中定义。

11. 请提供输入值

为了向模型提供输入,我们设置输入张量的内容,如下所示:

input->data.f[0] = 0.;

在本例中,我们输入表示 0 的浮点值。

12. 运行模型

如需运行模型,我们可以对 tflite::MicroInterpreter 实例调用 Invoke()

TfLiteStatus invoke_status = interpreter.Invoke();
if (invoke_status != kTfLiteOk) {
  TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed\n");
}

我们可以检查返回值 TfLiteStatus,以确定运行是否成功。TfLiteStatus 的可能值为 kTfLiteOkkTfLiteError(在 common.h 中定义)。

以下代码断言值为 kTfLiteOk,这意味着推断已成功运行。

TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, invoke_status);

13. 获取输出

可以通过对 tflite::MicroInterpreter 调用 output(0) 来获取模型的输出张量,其中 0 表示第一个(也是唯一一个)输出张量。

在本例中,模型的输出是 2D 张量中包含的单个浮点值:

TfLiteTensor* output = interpreter.output(0);
TF_LITE_MICRO_EXPECT_EQ(2, output->dims->size);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[0]);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[1]);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteFloat32, output->type);

我们可以直接从输出张量中读取该值,并断言该值是我们预期:

// Obtain the output value from the tensor
float value = output->data.f[0];
// Check that the output value is within 0.05 of the expected value
TF_LITE_MICRO_EXPECT_NEAR(0., value, 0.05);

14. 再次运行推理

代码的其余部分会多次进行推断。在每个实例中,我们为输入张量分配一个值,调用解释器,并从输出张量中读取结果:

input->data.f[0] = 1.;
interpreter.Invoke();
value = output->data.f[0];
TF_LITE_MICRO_EXPECT_NEAR(0.841, value, 0.05);

input->data.f[0] = 3.;
interpreter.Invoke();
value = output->data.f[0];
TF_LITE_MICRO_EXPECT_NEAR(0.141, value, 0.05);

input->data.f[0] = 5.;
interpreter.Invoke();
value = output->data.f[0];
TF_LITE_MICRO_EXPECT_NEAR(-0.959, value, 0.05);