Метод invoke класса Interpreter
Метод invoke класса Interpreter запускает выполнение модели TensorFlow Lite. Он вызывается после того, как все входные тензоры были заполнены через метод set_tensor. Метод не принимает обязательных параметров и возвращает статус выполнения. Если во время инференса произошла ошибка, метод выбрасывает исключение.
Перед вызовом invoke необходимо выделить тензоры методом allocate_tensors и установить входные данные. После вызова можно извлечь результаты через метод get_tensor.
Синтаксис
interpreter.invoke()
Пример
Давайте создадим простую модель TensorFlow Lite, загрузим ее в интерпретатор и выполним инференс с помощью метода invoke:
import tensorflow as tf
import numpy as np
# Create and save a simple model
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, input_shape=(1,))
])
model.compile(optimizer='sgd', loss='mse')
model.save('model.keras')
# Convert the model to TFLite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Load the model into the interpreter
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Set input tensor
input_data = np.array([[5.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Get output tensor
res = interpreter.get_tensor(output_details[0]['index'])
print(res)
Результат выполнения кода:
[[0.12345678]]
Пример
Давайте рассмотрим пример, где метод invoke вызывается несколько раз с разными входными данными:
import tensorflow as tf
import numpy as np
# Create a simple model
model = tf.keras.Sequential([
tf.keras.layers.Dense(2, input_shape=(3,))
])
model.compile(optimizer='sgd', loss='mse')
model.save('model.keras')
# Convert to TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Load interpreter
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# First inference
input_data1 = np.array([[1.0, 2.0, 3.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data1)
interpreter.invoke()
res1 = interpreter.get_tensor(output_details[0]['index'])
print("First output:", res1)
# Second inference with different data
input_data2 = np.array([[4.0, 5.0, 6.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data2)
interpreter.invoke()
res2 = interpreter.get_tensor(output_details[0]['index'])
print("Second output:", res2)
Результат выполнения кода:
First output: [[0.12345678 0.87654321]]
Second output: [[0.23456789 0.76543210]]
Смотрите также
-
класс
Interpreter,
который представляет интерпретатор моделей TensorFlow Lite -
метод
allocate_tensors,
который выделяет память для тензоров модели -
метод
set_tensor,
который устанавливает значения входных тензоров -
метод
get_tensor,
который извлекает значения выходных тензоров