Тест модели TF-lite завершился с ошибкой во время выполнения

Я создал модель TF-lite для классификации MNIST (я использую TF 1.12.0 и запускаю ее в Google Colab), и я хочу протестировать ее с помощью интерпретатора Python TensorFlow Lite, как указано в

https://github.com/freedomtan/tensorflow/blob/deeplab_tflite_python/tensorflow/contrib/lite/examples/python/label_image.py.

Но я получаю эту ошибку, когда пытаюсь вызвать интерпретатор -

RuntimeError                              Traceback (most recent call last)
<ipython-input-138-7d35ed1dfe14> in <module>()
----> 1 interpreter.invoke()

/usr/local/lib/python3.6/dist- 
packages/tensorflow/contrib/lite/python/interpreter.py in invoke(self)
251       ValueError: When the underlying interpreter fails raise 
ValueError.
252     """
--> 253     self._ensure_safe()
254     self._interpreter.Invoke()
255 

/usr/local/lib/python3.6/dist- 
packages/tensorflow/contrib/lite/python/interpreter.py in 
_ensure_safe(self)
 97       in the interpreter in the form of a numpy array or slice. Be sure 
 to
 98       only hold the function returned from tensor() if you are using 
 raw
 ---> 99       data access.""")

101   def _get_tensor_details(self, tensor_index):

 RuntimeError: There is at least 1 reference to internal data
  in the interpreter in the form of a numpy array or slice. Be sure to
  only hold the function returned from tensor() if you are using raw
  data access.

Вот код -

import numpy as np

# Load TFLite model and allocate tensors.
interpreter = 
tf.contrib.lite.Interpreter(model_path="mnist/mnist_custom.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_details

[{'dtype': numpy.float32, 'index': 3, 'name': 'conv2d

RuntimeError                              Traceback (most recent call last)
<ipython-input-138-7d35ed1dfe14> in <module>()
----> 1 interpreter.invoke()

/usr/local/lib/python3.6/dist- 
packages/tensorflow/contrib/lite/python/interpreter.py in invoke(self)
251       ValueError: When the underlying interpreter fails raise 
ValueError.
252     """
--> 253     self._ensure_safe()
254     self._interpreter.Invoke()
255 

/usr/local/lib/python3.6/dist- 
packages/tensorflow/contrib/lite/python/interpreter.py in 
_ensure_safe(self)
 97       in the interpreter in the form of a numpy array or slice. Be sure 
 to
 98       only hold the function returned from tensor() if you are using 
 raw
 ---> 99       data access.""")

101   def _get_tensor_details(self, tensor_index):

 RuntimeError: There is at least 1 reference to internal data
  in the interpreter in the form of a numpy array or slice. Be sure to
  only hold the function returned from tensor() if you are using raw
  data access.
input', 'quantization': (0.0, 0), 'shape': array ([1, 28, 28, 1], dtype = int32)}]

test_images[0].shape

(28, 28, 1)

input_data = np.expand_dims(test_images[0], axis=0)
input_data.shape

(1, 28, 28, 1)

interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()

Проблема в том, что я не понимаю, что означает это сообщение и что с этим делать.


person Vinitha Palani    schedule 02.01.2019    source источник
comment
Хорошо .. исправлено это ..добавлен input_tensor = tf.convert_to_tensor (input_data, np.float32), затем Interterter.set_tensor (input_details [0] ['index'], input_data)   -  person Vinitha Palani    schedule 02.01.2019
comment
Привет! Вы не против уточнить свое решение? У меня такая же проблема, и я не знаю, как ее решить   -  person DallaRosa    schedule 27.03.2019
comment
Либо (i) перезапустите ноутбук jupyter, либо (ii) мне подойдет повторная загрузка модели. Ознакомьтесь с подробным объяснением в этой теме: stackoverflow.com/questions/56777704/   -  person Sanchit    schedule 19.02.2020


Ответы (1)


tf.convert_to_tensor и interpreter.set_tensor сделали работу за меня

tensor_index = interpreter.get_input_details()[0]['index']
input_tensor_z= tf.convert_to_tensor(z, np.float32)
interpreter.set_tensor(tensor_index, input_tensor_z)

Я создал пример end2end, начиная с обучения модели Keras для ее обслуживания на TensorFlow Lite здесь

Я также опубликовал тот же ответ в эта ветка

person Romeo Kienzler    schedule 25.02.2020