Python 使用Tensorflow的Edgetpu编译器编译时出错
我正在尝试将一个两个输出的keras模型转换为一个编译的、量化的tflite模型,该模型将在Google Coral上工作。我以前使用过一个只有1个输出的Keras网络,它可以正常工作 以下是我的流程:Python 使用Tensorflow的Edgetpu编译器编译时出错,python,tensorflow,keras,tensorflow-lite,google-coral,Python,Tensorflow,Keras,Tensorflow Lite,Google Coral,我正在尝试将一个两个输出的keras模型转换为一个编译的、量化的tflite模型,该模型将在Google Coral上工作。我以前使用过一个只有1个输出的Keras网络,它可以正常工作 以下是我的流程: import tensorflow as tf from tensorflow.keras.applications.mobilenet import preprocess_input file = 'path/to/model-01.h5' model = tf.keras.models.l
import tensorflow as tf
from tensorflow.keras.applications.mobilenet import preprocess_input
file = 'path/to/model-01.h5'
model = tf.keras.models.load_model(file)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
os.chdir('/path/to/image/directories')#Where image directories are
directory = os.listdir()
directory
def representative_dataset_gen():
for i in directory:
count = 0
os.chdir(i)
files = os.listdir()
print(i)
for j in files:
if count<500:
img = Image.open(j)
width, height = img.size
bands = img.getbands()
array = np.asarray(img, dtype=np.float32)
array = preprocess_input(array)
count=count+1
yield[np.expand_dims(array, axis=0)]
else:
break
os.chdir('../')
converter.representative_dataset = representative_dataset_gen
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8 # or tf.uint8
converter.inference_output_type = tf.int8 # or tf.uint8
tflite_quant_model = converter.convert()
tflite_model_dir = pathlib.Path('where/i/want/to/save/')
tflite_quant_model_file = tflite_model_dir/'quantized.tflite'
tflite_quant_model_file.write_bytes(tflite_quant_model)
并收到此错误:
ERROR: :129 std::abs(input_product_scale - bias_scale) <= 1e-6 * std::min(input_product_scale, bias_scale) was not true.
ERROR: Node number 40 (FULLY_CONNECTED) failed to prepare.
Internal compiler error. Aborting!
它回来了
RuntimeError Traceback (most recent call last)
in
2 interpreter.resize_tensor_input(input_details[0]['index'], (32, 200, 200, 3))
3 interpreter.resize_tensor_input(output_details[0]['index'], (32, 5))
----> 4 interpreter.allocate_tensors()
5
~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter.py in allocate_tensors(self)
245 def allocate_tensors(self):
246 self._ensure_safe()
--> 247 return self._interpreter.AllocateTensors()
248
249 def _safe_to_run(self):
~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter_wrapper/tensorflow_wrap_interpreter_wrapper.py in AllocateTensors(self)
108
109 def AllocateTensors(self):
--> 110 return _tensorflow_wrap_interpreter_wrapper.InterpreterWrapper_AllocateTensors(self)
111
112 def Invoke(self):
RuntimeError: tensorflow/lite/kernels/kernel_util.cc:106 std::abs(input_product_scale - bias_scale) <= 1e-6 * std::min(input_product_scale, bias_scale) was not true.Node number 40 (FULLY_CONNECTED) failed to prepare.
运行时错误回溯(最近一次调用)
在里面
2.resize_tensor_input(input_details[0]['index'],(322002003))
3.调整张量输入的大小(输出详细信息[0]['index'],(32,5))
---->4.分配_张量()
5.
分配张量中的~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow\u core/lite/python/explorer.py(self)
245 def\u张量(自):
246自我确保安全()
-->247返回self.\u解释器.allocateSensors()
248
249 def安全到运行(自):
分配传感器中的~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow\u core/lite/python/explorer\u wrapper/tensorflow\u wrapper\u wrapper.py(self)
108
109 def分配器传感器(自身):
-->110返回\u tensorflow\u wrap\u解释器\u wrapper.解释器Rapper\u分配器传感器(自身)
111
112 def调用(自):
RuntimeError:tensorflow/lite/kernels/kernel\u util.cc:106 std::abs(input\u product\u scale-bias\u scale)我会为这个问题提出一个问题,因为它是tflite量化期间的一个实际错误。我非常肯定我以前见过这种情况,但不确定是否有解决办法:/
[编辑]
基本上,您可以尝试使用此脚本进行虚拟推理运行,如果在您的CPU模型上失败,那么很明显,在tflite转换之后,模型被破坏了
import numpy as np
import sys
from tflite_runtime.interpreter import Interpreter
from tflite_runtime.interpreter import load_delegate
if len(sys.argv) < 2:
print('Usage:', sys.argv[0], 'model_path')
exit()
def main():
"""Runs inference with an input tflite model."""
model_path = str(sys.argv[1])
if model_path.endswith('edgetpu.tflite'):
print('initialized for edgetpu')
delegates = [load_delegate('libedgetpu.so.1.0')]
interpreter = Interpreter(model_path, experimental_delegates=delegates)
else:
print('initialized for cpu')
interpreter = Interpreter(model_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
images = np.zeros(input_details[0]['shape'], input_details[0]['dtype'])
#print(images)
interpreter.set_tensor(input_details[0]['index'], images)
interpreter.invoke()
output_details = interpreter.get_output_details()
outputs = interpreter.get_tensor(output_details[0]['index'])
print(outputs)
print('Success.')
if __name__== '__main__':
main()
将numpy导入为np
导入系统
从tflite_runtime.解释器导入解释器
从tflite_runtime.解释器导入加载_委托
如果len(系统argv)<2:
打印('Usage:',sys.argv[0],'model_path')
退出()
def main():
“”“使用输入tflite模型运行推断。”“”
model_path=str(sys.argv[1])
如果模型_path.endswith('edgetpu.tflite'):
打印('已为edgetpu初始化')
委托=[load_delegate('libedgetpu.so.1.0')]
解释器=解释器(模型路径,实验代理=代理)
其他:
打印('为cpu初始化')
解释器=解释器(模型路径)
解释器。分配_张量()
input\u details=解释器。获取\u input\u details()
images=np.zero(输入_详细信息[0]['shape'],输入_详细信息[0]['dtype']))
#打印(图像)
解释器。设置张量(输入详细信息[0]['index'],图像)
invoke()解释器
output\u details=解释器。获取\u output\u details()
输出=解释器。获取张量(输出详细信息[0]['index'])
打印(输出)
打印('成功')
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
我在过去看到过这个问题,但不确定是否有解决方案。打开bug实际上是修复此问题的最佳方法。谢谢您。我终于能够编译了,我不知道怎么编译,也不知道为什么,你的代码帮我确认了这一点
RuntimeError Traceback (most recent call last)
in
2 interpreter.resize_tensor_input(input_details[0]['index'], (32, 200, 200, 3))
3 interpreter.resize_tensor_input(output_details[0]['index'], (32, 5))
----> 4 interpreter.allocate_tensors()
5
~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter.py in allocate_tensors(self)
245 def allocate_tensors(self):
246 self._ensure_safe()
--> 247 return self._interpreter.AllocateTensors()
248
249 def _safe_to_run(self):
~/Software/anaconda3/envs/Tensorflow2/lib/python3.7/site-packages/tensorflow_core/lite/python/interpreter_wrapper/tensorflow_wrap_interpreter_wrapper.py in AllocateTensors(self)
108
109 def AllocateTensors(self):
--> 110 return _tensorflow_wrap_interpreter_wrapper.InterpreterWrapper_AllocateTensors(self)
111
112 def Invoke(self):
RuntimeError: tensorflow/lite/kernels/kernel_util.cc:106 std::abs(input_product_scale - bias_scale) <= 1e-6 * std::min(input_product_scale, bias_scale) was not true.Node number 40 (FULLY_CONNECTED) failed to prepare.
import numpy as np
import sys
from tflite_runtime.interpreter import Interpreter
from tflite_runtime.interpreter import load_delegate
if len(sys.argv) < 2:
print('Usage:', sys.argv[0], 'model_path')
exit()
def main():
"""Runs inference with an input tflite model."""
model_path = str(sys.argv[1])
if model_path.endswith('edgetpu.tflite'):
print('initialized for edgetpu')
delegates = [load_delegate('libedgetpu.so.1.0')]
interpreter = Interpreter(model_path, experimental_delegates=delegates)
else:
print('initialized for cpu')
interpreter = Interpreter(model_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
images = np.zeros(input_details[0]['shape'], input_details[0]['dtype'])
#print(images)
interpreter.set_tensor(input_details[0]['index'], images)
interpreter.invoke()
output_details = interpreter.get_output_details()
outputs = interpreter.get_tensor(output_details[0]['index'])
print(outputs)
print('Success.')
if __name__== '__main__':
main()