ขอขอบคุณที่เข้าร่วม Google I/O ดูเซสชั่นทั้งหมดตามความต้องการ ดูตามความต้องการ

การอนุมาน 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 APIs ไม่ใช่เป้าหมายที่ชัดเจนและคาดว่าจะมีความแปรปรวนระหว่างภาษา

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

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

ใน 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 (รวมถึง 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 รับสามอาร์กิวเมนต์:

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

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

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

อีกวิธีหนึ่งในการเรียกใช้การอนุมานเมื่อโมเดลไม่มีลายเซ็นที่กำหนดไว้ เพียงแค่เรียก 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 ด้วย แต่เข้ารหัสต่างจากประเภทดั้งเดิม โดยเฉพาะอย่างยิ่ง รูปร่างของสตริง Tensor กำหนดจำนวนและการจัดเรียงของสตริงใน Tensor โดยแต่ละองค์ประกอบจะเป็นสตริงที่มีความยาวผันแปรได้ ในแง่นี้ ขนาด (ไบต์) ของ Tensor ไม่สามารถคำนวณจากรูปร่างและประเภทเพียงอย่างเดียว และด้วยเหตุนี้จึงไม่สามารถระบุสตริงเป็นอาร์กิวเมนต์ 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 แสดงในข้อมูลโค้ดด้านล่าง ควรสังเกตว่า:

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

import numpy as np
import tensorflow as tf

img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
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
with tf.Session() as sess:
  converter = tf.lite.TFLiteConverter.from_session(sess, [img], [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++ {.new-tab} ```c++ // ปรับขนาดเทนเซอร์อินพุตก่อนจัดสรรเทนเซอร์ ล่าม->ResizeInputTensor(/*tensor_index=*/0, std::vector {3,10}); ล่าม -> จัดสรร Tensors (); ``` ###### Python {.new-tab} ```python # โหลดโมเดล TFLite ในล่าม TFLite Interpreter = tf.lite.Interpreter(model_path=TFLITE_FILE_PATH) # ปรับขนาดรูปร่างอินพุตสำหรับโมเดลรูปร่างไดนามิกและจัดสรร tensor interpreter.resize_tensor_input(interpreter.get_input_details()[0]['index'], [3, 10]) Interpreter.allocate_tensors() # รับอินพุตและเอาต์พุตเทนเซอร์ input_details = Interpreter.get_input_details() output_details = Interpreter.get_output_details() ```

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

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