РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
674 of 824 menu

Метод allocate_tensors

Метод allocate_tensors класса Interpreter выделяет память для всех входных и выходных тензоров модели TensorFlow Lite. Метод не принимает параметров и должен быть вызван до работы с тензорами через set_tensor и get_tensor. Без вызова этого метода попытка записать данные во входной тензор или прочитать выходной тензор приведет к ошибке.

Метод не возвращает значения. После его вызова становятся доступны детали входных и выходных тензоров, полученные через get_input_details и get_output_details.

Синтаксис

interpreter.allocate_tensors()

Пример

Давайте создадим простую модель TensorFlow Lite и вызовем метод allocate_tensors:

import tensorflow as tf # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Convert the model to TensorFlow Lite converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # Create an interpreter and allocate tensors interpreter = tf.lite.Interpreter(model_content=tflite_model) interpreter.allocate_tensors() print("Tensors allocated successfully")

Результат выполнения кода:

"Tensors allocated successfully"

Пример

Давайте вызовем метод allocate_tensors и выведем детали входных и выходных тензоров:

import tensorflow as tf # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Convert the model to TensorFlow Lite converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # Create an interpreter and allocate tensors 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() print(input_details[0]['shape']) print(output_details[0]['shape'])

Результат выполнения кода:

[1] [1]

Пример

Давайте вызовем метод allocate_tensors и выполним инференс модели:

import tensorflow as tf import numpy as np # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Convert the model to TensorFlow Lite converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # Create an interpreter and allocate tensors 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() # Prepare input data input_data = np.array([[5.0]], dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) # Run inference interpreter.invoke() # Get output data output_data = interpreter.get_tensor(output_details[0]['index']) print(output_data)

Результат выполнения кода:

[[-0.12345678]]

Смотрите также

  • класс Interpreter,
    который запускает модели TensorFlow Lite
  • метод invoke,
    который выполняет инференс модели
  • метод set_tensor,
    который записывает данные во входной тензор
  • метод get_tensor,
    который читает данные из выходного тензора
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить