TensorFlow:使用 Tensorflow 2.2.0 将 SavedModel.pb 文件转换为 .tflite

TensorFlow: Converting SavedModel.pb file to .tflite using Tensorflow 2.2.0


OS: Windows 10

张量流版本:2.2.0

模型类型:SavedModel (.pb)

所需模型类型:Tensorflow Lite (.tflite)


我一直在无休止地寻找 python 脚本或命令行函数来将 .pb 文件转换为 .tflite。我尝试使用 tflite_convert,但它 return 出现错误:

OSError: SavedModel file does not exist at: C:/tensorflowTraining/export_dir/saved_model.pb/{saved_model.pbtxt|saved_model.pb}

我也尝试过一些脚本,例如:

import tensorflow as to

gf = tf.compat.v1.GraphDef()

m_file = open('saved_model.pb', 'rb')

gf.ParseFromString(m_file.read())

with open('somefile.txt', 'a') as the_file:

    for n in gf.node:

        the_file.write(n.name+'\n')

file = open('somefile.txt', 'r')

data = file.readlines()

print("output name = ")

print(data[len(data)-1])


print("Input name = ")

file.seek(0)

print(file.readline())

这个returns:

Exception has occurred: DecodeError

Unexpected end-group tag.

这个错误发生在第 4 行:

 gf.ParseFromString(m_file.read())

如果有人能提供一个有效的脚本或命令行函数,那将非常有帮助,正如我研究过的那样 return 错误或无法正常运行。

谢谢!

您可以使用 TF2.2 尝试类似下面的操作。

import tensorflow as tf 
graph_def_file = "./saved_model.pb"
tflite_file = 'mytflite.tflite'

input_arrays = ["input"]. # you need to change it based on your model
output_arrays = ["output"] # you need to change it based on your model
print("{} -> {}".format(graph_def_file, tflite_file))
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file=graph_def_file,
  input_arrays=input_arrays,
  output_arrays=output_arrays,input_shapes={'input_mel':[ 1, 50, 80]})
# If there are multiple inputs, then update the dictionary above
tflite_model = converter.convert()
open(tflite_file,'wb').write(tflite_model)

在上面的代码中,您需要使用与您的型号对应的input_arraysoutput_arraysinput_shapes