開始使用微控制器

本文件說明如何訓練模型,並使用微控制器執行推論。

Hello World 範例

Hello World 範例旨在示範使用 TensorFlow Lite for Microcontrollers 的絕對基礎知識。我們會訓練並執行複製正弦函式的模型 (也就是使用單一數字做為輸入),然後輸出這個數字的 sine 值。部署至微控制器時,其預測結果會用於閃爍 LED 或控制動畫。

端對端工作流程包含下列步驟:

  1. 訓練模型 (Python):這個 Python 檔案用於訓練、轉換及最佳化模型,以便用於裝置端用途。
  2. 執行推論 (在 C++ 17 中):使用 C++ 程式庫在模型上執行推論的端對端單元測試。

取得支援的裝置

稍後會使用的應用程式範例已在下列裝置上經過測試:

如要進一步瞭解支援的平台,請參閱 TensorFlow Lite for Microcontrollers

訓練模型

使用 train.py 進行 Hello 世界模型訓練,以便進行聲波辨識

執行: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 中的操作說明:

向 World README.md 問好

以下各節將逐步說明範例的 evaluate_test.cc,此單元測試示範如何使用 TensorFlow Lite for Microcontrollers 執行推論。模型會載入模型並執行推論多次。

1. 加入程式庫標頭

如要使用 TensorFlow Lite for Microcontrollers 程式庫,我們必須納入下列標頭檔案:

#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 for Microcontrollers 解譯器會預期以 C++ 陣列提供模型。模型是在 model.hmodel.cc 檔案中定義。標頭包含下列程式碼:

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

3. 加入單元測試架構標題

為了建立單元測試,我們納入 TensorFlow Lite for Microcontrollers 單元測試架構,內容如下:

#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. 載入模型

在下列程式碼中,模型會使用來自 model.h 中宣告的 char 陣列 g_model 資料例項化。然後,我們會檢查模型,確認其結構定義版本與我目前使用的版本相容:

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,判斷執行是否成功。common.h 中定義的 TfLiteStatus 可能值為 kTfLiteOkkTfLiteError

以下程式碼宣告值為 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);