Метод resize_tensor_input
Метод resize_tensor_input класса Interpreter
позволяет изменить форму входного тензора
интерпретатора TensorFlow Lite. Это необходимо,
когда модель была сконвертирована с одной
входной формой, а подавать данные требуется
с другой формой, например при работе с
изображениями разного разрешения.
Первым параметром метод принимает индекс
входного тензора, вторым - кортеж или список
с новой формой тензора. После изменения формы
требуется повторно выделить память для тензоров
методом allocate_tensors.
Синтаксис
interpreter.resize_tensor_input(tensor_index, tensor_size)
Пример
Давайте создадим простую модель, сконвертируем ее и изменим размер входного тензора:
import tensorflow as tf
import numpy as np
# Create a simple model with fixed input shape
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(4,)),
tf.keras.layers.Dense(2)
])
# Convert the model to TensorFlow Lite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Create the interpreter
interpreter = tf.lite.Interpreter(model_content=tflite_model)
# Get the input details
input_details = interpreter.get_input_details()
print(input_details[0]['shape'])
Результат выполнения кода:
[1 4]
Пример
Давайте изменим форму входного тензора
на 1 на 8 и выделим память заново:
import tensorflow as tf
import numpy as np
# Create a simple model with fixed input shape
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(4,)),
tf.keras.layers.Dense(2)
])
# Convert the model to TensorFlow Lite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Create the interpreter
interpreter = tf.lite.Interpreter(model_content=tflite_model)
# Resize the input tensor to shape (1, 8)
interpreter.resize_tensor_input(0, [1, 8])
# Allocate tensors again after resizing
interpreter.allocate_tensors()
# Check the new input shape
input_details = interpreter.get_input_details()
print(input_details[0]['shape'])
Результат выполнения кода:
[1 8]
Пример
Давайте изменим форму входного тензора и выполним вывод модели на новых данных:
import tensorflow as tf
import numpy as np
# Create a simple model with fixed input shape
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(4,)),
tf.keras.layers.Dense(2)
])
# Convert the model to TensorFlow Lite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Create the interpreter
interpreter = tf.lite.Interpreter(model_content=tflite_model)
# Resize the input tensor to shape (1, 8)
interpreter.resize_tensor_input(0, [1, 8])
# Allocate tensors again after resizing
interpreter.allocate_tensors()
# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Prepare input data with the new shape
input_data = np.array([[1, 2, 3, 4, 5, 6, 7, 8]], dtype=np.float32)
# Set the input tensor
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Get the output
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
Результат выполнения кода:
[[-2.0268388 1.3958839]]
Смотрите также
-
класс
Interpreter,
который запускает модели TensorFlow Lite -
метод
allocate_tensors,
который выделяет память для тензоров -
метод
get_input_details,
который возвращает информацию о входных тензорах -
метод
invoke,
который выполняет вывод модели