開始使用微控制器

這份文件說明如何訓練模型,以及如何使用微控制器執行推論。

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::ErrorReporter 指標是使用指向 tflite::MicroErrorReporter 執行個體的指標建立的

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 的可能值定義於 common.h 中,分別為 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);