เริ่มต้นใช้งาน LiteRT

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

การอนุมาน LiteRT มักมีขั้นตอนดังต่อไปนี้

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

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

  3. การเรียกใช้การอนุมาน: เรียกใช้โมเดล LiteRT เพื่อคาดการณ์ ช่วงเวลานี้ ต้องใช้ LiteRT API เพื่อเรียกใช้โมเดล ซึ่งเกี่ยวข้องกับ ขั้นตอนบางอย่าง เช่น การสร้างล่ามและการจัดสรร Tensor

  4. การตีความเอาต์พุต: ตีความเทนเซอร์เอาต์พุตในลักษณะที่มีความหมายซึ่งเป็นประโยชน์ในแอปพลิเคชัน เช่น โมเดลอาจแสดงเฉพาะรายการความน่าจะเป็น ขึ้นอยู่กับคุณที่จะจับคู่ความน่าจะเป็นกับความเกี่ยวข้อง และจัดรูปแบบเอาต์พุต

คู่มือนี้จะอธิบายวิธีเข้าถึงโปรแกรมแปลภาษา LiteRT และทําการอนุมานโดยใช้ C++, Java และ Python

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

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

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

LiteRT API ช่วยให้คุณสามารถโหลดโมเดล อินพุตฟีด และ เรียกเอาต์พุตการอนุมาน

แพลตฟอร์ม Android

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

ดูข้อมูลเพิ่มเติมได้ที่ส่วน C++ และ Java หรือทำตามการเริ่มต้นใช้งาน Android อย่างรวดเร็ว

แพลตฟอร์ม iOS

ใน iOS LiteRT จะอยู่ในไลบรารี Swift และ Objective-C ของ iOS นอกจากนี้คุณยังสามารถใช้ C API ในโค้ด Objective-C โดยตรง

โปรดดู Swift, Objective-C และ C API หรือทำตามคู่มือเริ่มต้นฉบับย่อสำหรับ iOS

แพลตฟอร์ม Linux

ในแพลตฟอร์ม Linux คุณเรียกใช้การอนุมานโดยใช้ LiteRT API ได้ใน C++.

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

การโหลดและเรียกใช้โมเดล LiteRT มีขั้นตอนดังนี้

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

Android (Java)

Java API สำหรับการเรียกใช้การอนุมานด้วย LiteRT ออกแบบมาเพื่อการใช้งานเป็นหลัก กับ Android เพื่อให้พร้อมใช้งานเป็นทรัพยากร Dependency ของไลบรารี Android ดังนี้ com.google.ai.edge.litert

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

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

public Interpreter(@NotNull File modelFile);

หรือด้วย MappedByteBuffer:

public Interpreter(@NotNull MappedByteBuffer mappedByteBuffer);

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

interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs);

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

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

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

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

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

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

interpreter.close();

ดูตัวอย่างโปรเจ็กต์ที่ใช้ Java ได้ที่ตัวอย่างแอปการตรวจจับวัตถุใน Android

ประเภทข้อมูลที่รองรับ

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

  • float
  • int
  • long
  • byte

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

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

อินพุต

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

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

เอาต์พุต

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

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...
}

iOS (Objective-C)

Objective-C API มีอยู่ใน LiteRTObjC Pod จาก Cocoapods

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

@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++

C++ API สำหรับเรียกใช้การอนุมานด้วย LiteRT ใช้ได้กับ Android, iOS, และแพลตฟอร์ม Linux C++ API ใน iOS จะพร้อมใช้งานเมื่อใช้ Bazel เท่านั้น

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

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 รายการเดียวพร้อมกันได้มากกว่า 1 Interpreter

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

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

การใช้งาน LiteRT ที่ง่ายที่สุดกับ 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 needed.
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 สำหรับการเรียกใช้การอนุมานใช้เมธอด Interpreter เพื่อโหลดโมเดลและ ใช้การอนุมานได้

ติดตั้งแพ็กเกจ LiteRT โดยใช้คำสั่งต่อไปนี้

$ python3 -m pip install ai-edge-litert

นำเข้าเครื่องมือล่าม LiteRT

from ai_edge_litert.interpreter import Interpreter
Interpreter = Interpreter(model_path=args.model.file)

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

เราขอแนะนำให้ใช้ตัวอย่างนี้ หากคุณแปลงจาก savedModel โดยใช้ SignatureDef

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 LiteRT model in LiteRT Interpreter
from ai_edge_litert.interpreter import Interpreter
interpreter = 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 LiteRT model and allocate tensors.
from ai_edge_litert.interpreter import Interpreter
interpreter = Interpreter(TFLITE_FILE_PATH)
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 ที่แปลงไว้ล่วงหน้าแล้ว คุณยัง สามารถรวมโค้ดของคุณกับ LiteRT คอมไพเลอร์ ซึ่งช่วยให้คุณสามารถแปลงโมเดล Keras ของคุณเป็นรูปแบบ LiteRT แล้วเรียกใช้ การอนุมาน:

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 LiteRT format
converter = tf.lite.TFLiteConverter.from_keras_model(tf.keras.models.Model(inputs=[img], outputs=[out]))
tflite_model = converter.convert()

# Load the LiteRT model and allocate tensors.
from ai_edge_litert.interpreter import Interpreter
interpreter = 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 ในโมเดล LiteRT

ตัวอย่างต่อไปนี้แสดงวิธีปรับขนาดรูปร่างอินพุตก่อนเรียกใช้ การอนุมานในภาษาต่างๆ ตัวอย่างทั้งหมดจะถือว่ารูปร่างอินพุตได้รับการกําหนดเป็น [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 LiteRT model in LiteRT Interpreter
from ai_edge_litert.interpreter import Interpreter
interpreter = 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()