การอนุมาน TensorFlow Lite

คำว่าการอนุมานหมายถึงกระบวนการเรียกใช้โมเดล TensorFlow Lite ในอุปกรณ์เพื่อคาดการณ์ตามข้อมูลอินพุต หากต้องการอนุมานด้วยโมเดล TensorFlow Lite คุณต้องเรียกใช้ผ่านล่าม อินเทอร์พรีเตอร์ของ TensorFlow Lite ออกแบบมาให้ทำงานได้ง่ายและรวดเร็วยิ่งขึ้น อินเทอร์พรีเตอร์ใช้การเรียงลำดับกราฟแบบคงที่และตัวปรับขนาดหน่วยความจำที่กำหนดเอง (แบบไดนามิกน้อยกว่า) เพื่อให้มีการโหลด การเริ่มต้นใช้งาน และเวลาในการตอบสนองของการดำเนินการน้อยที่สุด

หน้านี้อธิบายวิธีเข้าถึงอินเทอร์พรีเตอร์ของ TensorFlow Lite และดำเนินการอนุมานโดยใช้ C++, Java และ Python รวมถึงลิงก์ไปยังทรัพยากรอื่นๆ สำหรับแต่ละแพลตฟอร์มที่รองรับ

แนวคิดสำคัญ

การอนุมานของ TensorFlow Lite มักจะทำตามขั้นตอนต่อไปนี้

  1. การโหลดโมเดล

    คุณต้องโหลดโมเดล .tflite ลงในหน่วยความจำ ซึ่งมีกราฟการดำเนินการของโมเดล

  2. การเปลี่ยนรูปแบบข้อมูล

    โดยทั่วไปแล้ว ข้อมูลอินพุตดิบสำหรับโมเดลจะไม่ตรงกับรูปแบบข้อมูลอินพุตที่โมเดลคาดการณ์ เช่น คุณอาจต้องปรับขนาดรูปภาพหรือเปลี่ยนรูปแบบรูปภาพให้เข้ากันได้กับโมเดลนี้

  3. การเรียกใช้การอนุมาน

    ขั้นตอนนี้ต้องใช้ TensorFlow Lite API เพื่อเรียกใช้โมเดล ซึ่งเกี่ยวข้องกับขั้นตอนต่างๆ เช่น การสร้างอินเตอร์พรีเตอร์และจัดสรร Tensor ตามที่อธิบายไว้ในส่วนต่อไปนี้

  4. การแปลผลลัพธ์

    เมื่อได้รับผลลัพธ์จากการอนุมานโมเดล คุณต้องตีความ Tensor ให้มีความหมายซึ่งเป็นประโยชน์ในแอปพลิเคชันของคุณ

    ตัวอย่างเช่น โมเดลอาจแสดงผลเฉพาะรายการความน่าจะเป็น คุณจะต้องจับคู่ความน่าจะเป็นกับหมวดหมู่ที่เกี่ยวข้องและนำเสนอให้ผู้ใช้ปลายทางของคุณเห็น

แพลตฟอร์มที่รองรับ

API การอนุมาน TensorFlow มีให้สำหรับแพลตฟอร์มอุปกรณ์เคลื่อนที่/แบบฝังส่วนใหญ่ เช่น Android, iOS และ Linux สำหรับภาษาโปรแกรมหลายภาษา

ในกรณีส่วนใหญ่ การออกแบบ API จะสอดคล้องกับความต้องการประสิทธิภาพมากกว่าความสะดวกในการใช้งาน TensorFlow Lite ออกแบบมาเพื่อการอนุมานที่รวดเร็วในอุปกรณ์ขนาดเล็ก จึงไม่น่าแปลกใจที่ API จะพยายามหลีกเลี่ยงสำเนาที่ไม่จำเป็นโดยสะดวก ในทำนองเดียวกัน ความสอดคล้องกันของ TensorFlow API ไม่ใช่เป้าหมายที่ชัดเจนและเราคาดว่าจะมีความแปรปรวนระหว่างภาษาอยู่บ้าง

ในไลบรารีทั้งหมด TensorFlow Lite API จะช่วยให้คุณโหลดโมเดล อินพุตฟีด และดึงเอาต์พุตการอนุมานได้

แพลตฟอร์ม Android

ใน Android จะทำการอนุมาน TensorFlow Lite ได้โดยใช้ Java หรือ C++ API Java API ให้ความสะดวกและนำไปใช้ได้โดยตรงภายในคลาสกิจกรรม Android C++ API มีความยืดหยุ่นและความเร็วมากกว่า แต่อาจต้องเขียน JNI Wrapper เพื่อย้ายข้อมูลระหว่างเลเยอร์ Java และ C++

โปรดดูรายละเอียดเกี่ยวกับการใช้ C++ และ Java ด้านล่าง หรือทำตามคู่มือเริ่มใช้งาน Android ฉบับย่อเพื่อดูบทแนะนำและโค้ดตัวอย่าง

เครื่องมือสร้างโค้ด Wrapper สำหรับ Android ของ TensorFlow Lite

สำหรับโมเดล TensorFlow Lite ที่เพิ่มประสิทธิภาพด้วยข้อมูลเมตา นักพัฒนาซอฟต์แวร์สามารถใช้โปรแกรมสร้างโค้ด Wrapper สำหรับ Android ของ TensorFlow Lite เพื่อสร้างโค้ด Wrapper ที่เจาะจงแพลตฟอร์ม โค้ด Wrapper ทำให้คุณไม่ต้องโต้ตอบกับ ByteBuffer ใน Android โดยตรง นักพัฒนาซอฟต์แวร์จะโต้ตอบกับโมเดล TensorFlow Lite ด้วยออบเจ็กต์ที่พิมพ์ เช่น Bitmap และ Rect แทนได้ ดูข้อมูลเพิ่มเติมได้ที่โปรแกรมสร้างโค้ด Wrapper สำหรับ Android ของ TensorFlow Lite

แพลตฟอร์ม iOS

ใน iOS TensorFlow Lite จะใช้งานได้กับไลบรารี iOS แบบเนทีฟที่เขียนด้วยภาษา Swift และ Objective-C คุณยังใช้ C API ในโค้ด Objective-C ได้โดยตรงอีกด้วย

โปรดดูรายละเอียดเกี่ยวกับการใช้ Swift, Objective-C และ C API ด้านล่าง หรือทําตามการเริ่มต้นใช้งาน iOS อย่างรวดเร็วเพื่อดูบทแนะนำและโค้ดตัวอย่าง

แพลตฟอร์ม Linux

บนแพลตฟอร์ม Linux (รวมถึง Raspberry Pi) คุณสามารถเรียกใช้การอนุมานโดยใช้ TensorFlow Lite API ที่มีอยู่ใน C++ และ Python ดังที่แสดงในส่วนต่อไปนี้

การเรียกใช้โมเดล

การเรียกใช้โมเดล TensorFlow Lite มีขั้นตอนง่ายๆ 2-3 ขั้นตอนดังนี้

  1. โหลดโมเดลลงในหน่วยความจำ
  2. สร้าง Interpreter ตามรูปแบบที่มีอยู่
  3. ตั้งค่า Tensor อินพุต (ไม่บังคับปรับขนาด Tensor อินพุตหากไม่ต้องการขนาดที่กำหนดไว้ล่วงหน้า)
  4. ใช้การอนุมาน
  5. อ่านค่า Tensor เอาต์พุต

ส่วนต่างๆ ต่อไปนี้จะอธิบายขั้นตอนเหล่านี้ในแต่ละภาษา

โหลดและเรียกใช้โมเดลใน Java

แพลตฟอร์ม: Android

Java API สำหรับเรียกใช้การอนุมานด้วย TensorFlow Lite ออกแบบมาเพื่อใช้กับ Android เป็นหลัก จึงมีให้ใช้เป็นทรัพยากร Dependency ของไลบรารี Android ดังนี้ org.tensorflow:tensorflow-lite

ใน Java คุณจะใช้คลาส Interpreter เพื่อโหลดโมเดลและการอนุมานโมเดลไดรฟ์ ในหลายๆ กรณี นี่อาจเป็น API เดียวที่คุณจำเป็นต้องใช้

คุณสามารถเริ่มต้น Interpreter โดยใช้ไฟล์ .tflite ดังนี้

public Interpreter(@NotNull File modelFile);

หรือด้วย MappedByteBuffer:

public Interpreter(@NotNull MappedByteBuffer mappedByteBuffer);

ในทั้ง 2 กรณี คุณต้องระบุโมเดล TensorFlow Lite ที่ถูกต้อง ไม่เช่นนั้น API จะส่ง IllegalArgumentException หากคุณใช้ MappedByteBuffer เพื่อเริ่มต้น Interpreter ก็จะต้องไม่มีการเปลี่ยนแปลงตลอดอายุของ Interpreter

วิธีที่แนะนำในการใช้การอนุมานบนโมเดลคือการใช้ลายเซ็น ใช้ได้กับโมเดลที่แปลงแล้วตั้งแต่ Tensorflow 2.5

try (Interpreter interpreter = new Interpreter(file_of_tensorflowlite_model)) {
  Map<String, Object> inputs = new HashMap<>();
  inputs.put("input_1", input1);
  inputs.put("input_2", input2);
  Map<String, Object> outputs = new HashMap<>();
  outputs.put("output_1", output1);
  interpreter.runSignature(inputs, outputs, "mySignature");
}

เมธอด runSignature มีอาร์กิวเมนต์ 3 รายการ ดังนี้

  • อินพุต : จับคู่อินพุตจากชื่ออินพุตในลายเซ็นไปยังออบเจ็กต์อินพุต

  • เอาต์พุต : แมปสำหรับการแมปเอาต์พุตจากชื่อเอาต์พุตในลายเซ็นไปยังข้อมูลเอาต์พุต

  • ชื่อลายเซ็น (ไม่บังคับ): ชื่อลายเซ็น (เว้นว่างไว้ได้หากโมเดลมีลายเซ็นเดียว)

วิธีเรียกใช้การอนุมานอีกวิธีเมื่อโมเดลไม่มีลายเซ็น เพียงโทรไปที่ Interpreter.run() เช่น

try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) {
  interpreter.run(input, output);
}

เมธอด run() จะใช้เพียงอินพุตเดียวและแสดงผลเพียง 1 รายการ ดังนั้นหากโมเดลของคุณมีอินพุตหลายรายการหรือเอาต์พุตหลายรายการ ให้ใช้

interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs);

ในกรณีนี้ แต่ละรายการใน inputs จะสอดคล้องกับ Tensor อินพุตและ map_of_indices_to_outputs แมปดัชนี Tensor เอาต์พุตกับข้อมูลเอาต์พุตที่เกี่ยวข้อง

ในทั้ง 2 กรณี ดัชนี Tensor ควรสอดคล้องกับค่าที่คุณกำหนดให้กับ TensorFlow Lite Converter เมื่อสร้างโมเดล โปรดทราบว่าลำดับของ Tensor ใน input ต้องตรงกับลำดับที่กำหนดให้กับ TensorFlow Lite Converter

คลาส Interpreter ยังมีฟังก์ชันที่สะดวกสำหรับการรับดัชนีอินพุตหรือเอาต์พุตโมเดลใดๆ โดยใช้ชื่อการดำเนินการ ดังนี้

public int getInputIndex(String opName);
public int getOutputIndex(String opName);

หาก opName ไม่ใช่การดำเนินการที่ถูกต้องในโมเดล ระบบจะแสดงข้อผิดพลาด IllegalArgumentException

และโปรดระวังว่า Interpreter เป็นเจ้าของทรัพยากร เพื่อหลีกเลี่ยงการรั่วไหลของหน่วยความจำ คุณจะต้องปล่อยทรัพยากรหลังการใช้งานโดย

interpreter.close();

สำหรับตัวอย่างโปรเจ็กต์ที่มี Java โปรดดูตัวอย่างการจัดประเภทรูปภาพ Android

ประเภทข้อมูลที่รองรับ (ใน Java)

หากต้องการใช้ TensorFlow Lite ประเภทข้อมูลของ Tensor อินพุตและเอาต์พุตต้องเป็นหนึ่งในประเภทพื้นฐานต่อไปนี้

  • float
  • int
  • long
  • byte

ระบบรองรับประเภท String ด้วย แต่จะเข้ารหัสแตกต่างจากประเภทพื้นฐาน โดยรูปร่างของสตริง Tensor จะเป็นตัวกำหนดจำนวนและการจัดเรียงสตริงใน Tensor โดยองค์ประกอบแต่ละรายการเป็นสตริงที่มีความยาวที่ปรับเปลี่ยนได้ ในความหมายนี้ ขนาด (ไบต์) ของ Tensor จะคำนวณจากรูปร่างและประเภทเพียงอย่างเดียวไม่ได้ และจะทำให้ระบุสตริงเป็นอาร์กิวเมนต์ ByteBuffer แบบเดี่ยวเดี่ยวไม่ได้

หากมีการใช้ข้อมูลประเภทอื่นๆ ซึ่งรวมถึงประเภทแบบกล่อง เช่น Integer และ Float ระบบจะส่ง IllegalArgumentException

อินพุต

อินพุตแต่ละรายการควรเป็นอาร์เรย์หรืออาร์เรย์หลายมิติข้อมูลของประเภทพื้นฐานที่รองรับ หรือ ByteBuffer ดิบของขนาดที่เหมาะสม หากอินพุตเป็นอาร์เรย์หรืออาร์เรย์หลายมิติ tensor ของอินพุตที่เกี่ยวข้องจะถูกปรับขนาดตามขนาดของอาร์เรย์ในเวลาการอนุมาน หากอินพุตเป็น ByteBuffer ผู้โทรควรปรับขนาด Tensor อินพุตที่เกี่ยวข้องด้วยตนเอง (ผ่าน Interpreter.resizeInput()) ก่อนที่จะเรียกใช้การอนุมาน

เมื่อใช้ ByteBuffer เราขอแนะนำให้ใช้บัฟเฟอร์ไบต์โดยตรงเพราะจะช่วยให้ Interpreter หลีกเลี่ยงสำเนาที่ไม่จำเป็นได้ หาก ByteBuffer เป็นบัฟเฟอร์ไบต์โดยตรง ลำดับจะต้องเป็น ByteOrder.nativeOrder() หลังจากใช้การอนุมานโมเดลแล้ว จะไม่มีการเปลี่ยนแปลงจนกว่าจะการอนุมานโมเดลเสร็จสิ้น

เอาต์พุต

เอาต์พุตแต่ละรายการควรเป็นอาร์เรย์หรืออาร์เรย์หลายมิติข้อมูลของประเภทดั้งเดิมที่รองรับ หรือ ByteBuffer ที่มีขนาดที่เหมาะสม โปรดทราบว่าบางโมเดลมีเอาต์พุตแบบไดนามิก ซึ่งรูปร่างของ Tensor เอาต์พุตอาจแตกต่างกันไปโดยขึ้นอยู่กับอินพุต ไม่มีวิธีที่ตรงไปตรงมาในการจัดการปัญหานี้ด้วย Java Inference API ที่มีอยู่ แต่ส่วนขยายที่วางแผนไว้จะช่วยให้ดำเนินการนี้ได้

โหลดและเรียกใช้โมเดลใน Swift

แพลตฟอร์ม: iOS

Swift API พร้อมให้บริการในพ็อด TensorFlowLiteSwift จาก Cocoapods

ก่อนอื่น คุณต้องนำเข้าโมดูล TensorFlowLite

import TensorFlowLite
// Getting model path
guard
  let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite")
else {
  // Error handling...
}

do {
  // Initialize an interpreter with the model.
  let interpreter = try Interpreter(modelPath: modelPath)

  // Allocate memory for the model's input `Tensor`s.
  try interpreter.allocateTensors()

  let inputData: Data  // Should be initialized

  // input data preparation...

  // Copy the input data to the input `Tensor`.
  try self.interpreter.copy(inputData, toInputAt: 0)

  // Run inference by invoking the `Interpreter`.
  try self.interpreter.invoke()

  // Get the output `Tensor`
  let outputTensor = try self.interpreter.output(at: 0)

  // Copy output to `Data` to process the inference results.
  let outputSize = outputTensor.shape.dimensions.reduce(1, {x, y in x * y})
  let outputData =
        UnsafeMutableBufferPointer<Float32>.allocate(capacity: outputSize)
  outputTensor.data.copyBytes(to: outputData)

  if (error != nil) { /* Error handling... */ }
} catch error {
  // Error handling...
}

โหลดและเรียกใช้โมเดลใน Objective-C

แพลตฟอร์ม: iOS

Objective-C API มีอยู่ในพ็อด TensorFlowLiteObjC จาก Cocoapods

ก่อนอื่น คุณต้องนำเข้าโมดูล TensorFlowLite

@import TensorFlowLite;
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];
NSError *error;

// Initialize an interpreter with the model.
TFLInterpreter *interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath
                                                                  error:&error];
if (error != nil) { /* Error handling... */ }

// Allocate memory for the model's input `TFLTensor`s.
[interpreter allocateTensorsWithError:&error];
if (error != nil) { /* Error handling... */ }

NSMutableData *inputData;  // Should be initialized
// input data preparation...

// Get the input `TFLTensor`
TFLTensor *inputTensor = [interpreter inputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }

// Copy the input data to the input `TFLTensor`.
[inputTensor copyData:inputData error:&error];
if (error != nil) { /* Error handling... */ }

// Run inference by invoking the `TFLInterpreter`.
[interpreter invokeWithError:&error];
if (error != nil) { /* Error handling... */ }

// Get the output `TFLTensor`
TFLTensor *outputTensor = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { /* Error handling... */ }

// Copy output to `NSData` to process the inference results.
NSData *outputData = [outputTensor dataWithError:&error];
if (error != nil) { /* Error handling... */ }

การใช้ C API ในโค้ด Objective-C

ปัจจุบัน Objective-C API ไม่รองรับผู้รับมอบสิทธิ์ หากต้องการใช้ผู้รับมอบสิทธิ์กับโค้ด Objective-C คุณต้องเรียกใช้ C API ที่เกี่ยวข้องโดยตรง

#include "tensorflow/lite/c/c_api.h"
TfLiteModel* model = TfLiteModelCreateFromFile([modelPath UTF8String]);
TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate();

// Create the interpreter.
TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options);

// Allocate tensors and populate the input tensor data.
TfLiteInterpreterAllocateTensors(interpreter);
TfLiteTensor* input_tensor =
    TfLiteInterpreterGetInputTensor(interpreter, 0);
TfLiteTensorCopyFromBuffer(input_tensor, input.data(),
                           input.size() * sizeof(float));

// Execute inference.
TfLiteInterpreterInvoke(interpreter);

// Extract the output tensor data.
const TfLiteTensor* output_tensor =
    TfLiteInterpreterGetOutputTensor(interpreter, 0);
TfLiteTensorCopyToBuffer(output_tensor, output.data(),
                         output.size() * sizeof(float));

// Dispose of the model and interpreter objects.
TfLiteInterpreterDelete(interpreter);
TfLiteInterpreterOptionsDelete(options);
TfLiteModelDelete(model);

โหลดและเรียกใช้โมเดลใน C++

แพลตฟอร์ม: Android, iOS และ Linux

ใน C++ ระบบจะจัดเก็บโมเดลไว้ในคลาส FlatBufferModel ซึ่งรวมโมเดล TensorFlow Lite และคุณสร้างโมเดลได้ด้วย 2 วิธีที่แตกต่างกัน โดยขึ้นอยู่กับตำแหน่งที่จัดเก็บโมเดล ดังนี้

class FlatBufferModel {
  // Build a model based on a file. Return a nullptr in case of failure.
  static std::unique_ptr<FlatBufferModel> BuildFromFile(
      const char* filename,
      ErrorReporter* error_reporter);

  // Build a model based on a pre-loaded flatbuffer. The caller retains
  // ownership of the buffer and should keep it alive until the returned object
  // is destroyed. Return a nullptr in case of failure.
  static std::unique_ptr<FlatBufferModel> BuildFromBuffer(
      const char* buffer,
      size_t buffer_size,
      ErrorReporter* error_reporter);
};

ตอนนี้คุณมีโมเดลเป็นออบเจ็กต์ FlatBufferModel แล้ว คุณจะเรียกใช้โมเดลด้วย Interpreter ได้ สามารถใช้ FlatBufferModel รายการเดียวพร้อมกันได้โดย Interpreter มากกว่า 1 รายการ

ส่วนที่สำคัญของ Interpreter API จะแสดงอยู่ในข้อมูลโค้ดด้านล่าง โปรดทราบว่า

  • Tensor จะแสดงด้วยจำนวนเต็มเพื่อหลีกเลี่ยงการเปรียบเทียบสตริง (และการอ้างอิงแบบคงที่ในไลบรารีสตริง)
  • ต้องไม่มีการเข้าถึงล่ามจากชุดข้อความที่ทำงานพร้อมกัน
  • การจัดสรรหน่วยความจำสำหรับ Tensor อินพุตและเอาต์พุตต้องทริกเกอร์โดยการเรียกใช้ AllocateTensors() ทันทีหลังจากที่ปรับขนาด Tensor

การใช้งาน TensorFlow Lite กับ C++ ที่ง่ายที่สุดมีดังนี้

// Load the model
std::unique_ptr<tflite::FlatBufferModel> model =
    tflite::FlatBufferModel::BuildFromFile(filename);

// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);

// Resize input tensors, if desired.
interpreter->AllocateTensors();

float* input = interpreter->typed_input_tensor<float>(0);
// Fill `input`.

interpreter->Invoke();

float* output = interpreter->typed_output_tensor<float>(0);

สำหรับโค้ดตัวอย่างเพิ่มเติม โปรดดู minimal.cc และ label_image.cc

โหลดและเรียกใช้โมเดลใน Python

แพลตฟอร์ม: Linux

Python API สำหรับการเรียกใช้การอนุมานส่วนใหญ่ต้องใช้เพียง tf.lite.Interpreter เพื่อโหลดโมเดลและเรียกใช้การอนุมานเท่านั้น

ตัวอย่างต่อไปนี้แสดงวิธีใช้อินเทอร์พรีเตอร์ Python เพื่อโหลดไฟล์ .tflite และเรียกใช้การอนุมานด้วยข้อมูลอินพุตแบบสุ่ม

ขอแนะนำตัวอย่างนี้หากคุณแปลงจาก SavedModel ซึ่งมี SignatureDef ที่กำหนด ใช้งานได้ตั้งแต่ TensorFlow 2.5

class TestModel(tf.Module):
  def __init__(self):
    super(TestModel, self).__init__()

  @tf.function(input_signature=[tf.TensorSpec(shape=[1, 10], dtype=tf.float32)])
  def add(self, x):
    '''
    Simple method that accepts single input 'x' and returns 'x' + 4.
    '''
    # Name the output 'result' for convenience.
    return {'result' : x + 4}


SAVED_MODEL_PATH = 'content/saved_models/test_variable'
TFLITE_FILE_PATH = 'content/test_variable.tflite'

# Save the model
module = TestModel()
# You can omit the signatures argument and a default signature name will be
# created with name 'serving_default'.
tf.saved_model.save(
    module, SAVED_MODEL_PATH,
    signatures={'my_signature':module.add.get_concrete_function()})

# Convert the model using TFLiteConverter
converter = tf.lite.TFLiteConverter.from_saved_model(SAVED_MODEL_PATH)
tflite_model = converter.convert()
with open(TFLITE_FILE_PATH, 'wb') as f:
  f.write(tflite_model)

# Load the TFLite model in TFLite Interpreter
interpreter = tf.lite.Interpreter(TFLITE_FILE_PATH)
# There is only 1 signature defined in the model,
# so it will return it by default.
# If there are multiple signatures then we can pass the name.
my_signature = interpreter.get_signature_runner()

# my_signature is callable with input as arguments.
output = my_signature(x=tf.constant([1.0], shape=(1,10), dtype=tf.float32))
# 'output' is dictionary with all outputs from the inference.
# In this case we have single output 'result'.
print(output['result'])

อีกตัวอย่างหนึ่งคือกรณีที่โมเดลไม่มีการกำหนด SignatureDefs

import numpy as np
import tensorflow as tf

# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test the model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

นอกจากการโหลดโมเดลเป็นไฟล์ .tflite ที่แปลงไว้ล่วงหน้าแล้ว คุณยังสามารถรวมโค้ดกับ TensorFlow Lite Converter Python API ได้ด้วย ซึ่งช่วยให้คุณแปลงโมเดล Keras เป็นรูปแบบ TensorFlow Lite แล้วเรียกใช้การอนุมานได้ ดังนี้

import numpy as np
import tensorflow as tf

img = tf.keras.Input(shape=(64, 64, 3), name="img")
const = tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
val = img + const
out = tf.identity(val, name="out")

# Convert to TF Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(tf.keras.models.Model(inputs=[img], outputs=[out]))
tflite_model = converter.convert()

# Load the TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

# Continue to get tensors and so forth, as shown above...

ดูโค้ดตัวอย่าง Python เพิ่มเติมได้ที่ label_image.py

เรียกใช้การอนุมานด้วยโมเดลรูปร่างแบบไดนามิก

หากต้องการเรียกใช้โมเดลที่มีรูปร่างอินพุตแบบไดนามิก ให้ปรับขนาดรูปร่างอินพุตก่อนที่จะเรียกใช้การอนุมาน มิเช่นนั้น รูปร่าง None ในโมเดล Tensorflow จะแทนที่ด้วยตัวยึดตำแหน่ง 1 ในโมเดล TFLite

ตัวอย่างต่อไปนี้แสดงวิธีปรับขนาดรูปร่างอินพุตก่อนเรียกใช้การอนุมานในภาษาต่างๆ ตัวอย่างทั้งหมดจะถือว่ารูปร่างอินพุตกำหนดเป็น [1/None, 10] และต้องปรับขนาดเป็น [3, 10]

ตัวอย่าง C++

// Resize input tensors before allocate tensors
interpreter->ResizeInputTensor(/*tensor_index=*/0, std::vector<int>{3,10});
interpreter->AllocateTensors();

ตัวอย่าง Python

# Load the TFLite model in TFLite Interpreter
interpreter = tf.lite.Interpreter(model_path=TFLITE_FILE_PATH)

# Resize input shape for dynamic shape model and allocate tensor
interpreter.resize_tensor_input(interpreter.get_input_details()[0]['index'], [3, 10])
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

การดำเนินการที่รองรับ

TensorFlow Lite รองรับการดำเนินการ TensorFlow ชุดย่อยพร้อมข้อจำกัดบางอย่าง ดูรายการการดำเนินการและข้อจำกัดทั้งหมดได้ที่หน้าการดำเนินการของ TF Lite