การอนุมาน TensorFlow Lite

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

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

แนวคิดที่สำคัญ

โดยทั่วไปการอนุมาน TensorFlow Lite จะทำตามขั้นตอนต่อไปนี้:

  1. กำลังโหลดโมเดล

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

  2. การแปลงข้อมูล

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

  3. กำลังอนุมานอยู่

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

  4. การตีความเอาท์พุท

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

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

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

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 QuickStart เพื่อดูบทช่วยสอนและโค้ดตัวอย่าง

เครื่องสร้างโค้ด wrapper ของ Android TensorFlow Lite

สำหรับโมเดล TensorFlow Lite ที่ปรับปรุงด้วย ข้อมูลเม ตา นักพัฒนาสามารถใช้ตัวสร้างโค้ด Wrapper ของ Android TensorFlow Lite เพื่อสร้างโค้ด 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 QuickStart เพื่อดูบทช่วยสอนและโค้ดตัวอย่าง

แพลตฟอร์มลินุกซ์

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

กำลังดำเนินการโมเดล

การเรียกใช้โมเดล TensorFlow Lite มีขั้นตอนง่ายๆ เพียงไม่กี่ขั้นตอน:

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

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

โหลดและรันโมเดลใน Java

แพลตฟอร์ม: แอนดรอยด์

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

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

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

public Interpreter(@NotNull File modelFile);

หรือด้วย MappedByteBuffer :

public Interpreter(@NotNull MappedByteBuffer mappedByteBuffer);

ในทั้งสองกรณี คุณต้องระบุโมเดล 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 รับสามอาร์กิวเมนต์:

  • อินพุต : แผนที่สำหรับอินพุตจากชื่ออินพุตในลายเซ็นไปยังวัตถุอินพุต

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

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

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

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

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

interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs);

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

ในทั้งสองกรณี ดัชนีเทนเซอร์ควรสอดคล้องกับค่าที่คุณให้กับ TensorFlow Lite Converter เมื่อคุณสร้างโมเดล โปรดทราบว่าลำดับของเทนเซอร์ใน 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 ประเภทข้อมูลของเทนเซอร์อินพุตและเอาต์พุตต้องเป็นประเภทพื้นฐานประเภทใดประเภทหนึ่งต่อไปนี้:

  • float
  • int
  • long
  • byte

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

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

อินพุต

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

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

เอาท์พุต

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

โหลดและรันโมเดลใน Swift

แพลตฟอร์ม: iOS

Swift API มีอยู่ใน TensorFlowLiteSwift Pod จาก 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 Pod จาก 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 และคุณสามารถสร้างได้หลายวิธี ขึ้นอยู่กับตำแหน่งที่จัดเก็บโมเดล:

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 มากกว่าหนึ่งคน

ส่วนสำคัญของ Interpreter API จะแสดงอยู่ในข้อมูลโค้ดด้านล่างนี้ ควรสังเกตว่า:

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

การใช้งานที่ง่ายที่สุดของ 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

แพลตฟอร์ม: ลินุกซ์

Python API สำหรับการเรียกใช้การอนุมานมีอยู่ในโมดูล tf.lite ซึ่งส่วนใหญ่คุณต้องการเพียง 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 ( tf.lite.TFLiteConverter ) ซึ่งช่วยให้คุณสามารถแปลงโมเดล 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();

ตัวอย่างหลาม:

# 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()