tensorflow=2.4.1
实践例子把Tensorflow的模型转换成tflite
import tensorflow as tf
def convert_to_tflite(model):
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tfmodel = converter.convert()
file = open('yourmodel.tflite', 'wb')
file.write(tfmodel)
file.close()
运行Tflite模型
import tensorflow as tf
def run_reference_by_tflite(input):
interpreter = tf.lite.Interpreter(model_path="yourmodel.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# input details
print(input_details, len(input_details))
# output details
print(output_details)
# input_details[0]['index'] = the index which accepts the input
interpreter.set_tensor(input_details[0]['index'], input)
# run the inference
interpreter.invoke()
# output_details[0]['index'] = the index which provides the input
output_data = interpreter.get_tensor(output_details[0]['index'])
print('interpreter: ', output_data)
相关错误以及解决方法 1. ValueError: Cannot set tensor: Got value of type NOTYPE but expected type FLOAT32 for input 0,
或
ValueError: Cannot set tensor: Got value of type INT32 but expected type FLOAT32 for input 0,
或
ValueError: Cannot set tensor: Got value of type UINT8 but expected type FLOAT32 for input 0, name: input_1
解决方法:
under_exp = np.array(under_exp, dtype=np.float32)
参考资料
python - How to convert keras(h5) file to a tflite file? - Stack Overflow



