【问题标题】:Tensorflow Convert pb file to TFLITE using pythonTensorflow 使用 python 将 pb 文件转换为 TFLITE
【发布时间】:2018-05-31 20:17:50
【问题描述】:

我有一个训练后保存为 pb 文件的模型,我想使用 tensorflow mobile,使用 TFLITE 文件很重要。 问题是我在谷歌搜索转换器后发现的大多数示例都是终端或 cmd 上的命令。 可以分享一下使用python代码转换为tflite文件的例子吗?

【问题讨论】:

    标签: python tensorflow tensorflow-lite


    【解决方案1】:

    您可以直接在python中直接转换为tflite。你必须freeze the graph 并使用toco_convert。它需要在调用 API 之前确定输入和输出名称和形状,就像在命令行情况下一样。

    示例代码 sn-p

    复制自 documentation,其中将“冻结”(无变量)图定义为代码的一部分:

    import tensorflow as tf
    
    img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
    val = img + tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
    out = tf.identity(val, name="out")
    with tf.Session() as sess:
      tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [img], [out])
      open("test.tflite", "wb").write(tflite_model)
    

    在上面的示例中,没有冻结图步骤,因为没有变量。如果你有变量并且在没有冻结图形的情况下运行 toco,即先将这些变量转换为常量,那么 toco 会抱怨!

    如果你已经冻结了 graphdef 并且知道输入和输出

    那么你就不需要会话了。可以直接调用toco API:

    path_to_frozen_graphdef_pb = '...'
    input_tensors = [...]
    output_tensors = [...]
    frozen_graph_def = tf.GraphDef()
    with open(path_to_frozen_graphdef_pb, 'rb') as f:
      frozen_graph_def.ParseFromString(f.read())
    tflite_model = tf.contrib.lite.toco_convert(frozen_graph_def, input_tensors, output_tensors)
    

    如果你有非冻结的 graphdef 并且知道输入和输出

    然后你必须在调用 toco 之前先加载会话并冻结图形:

    path_to_graphdef_pb = '...'
    g = tf.GraphDef()
    with open(path_to_graphdef_pb, 'rb') as f:
      g.ParseFromString(f.read())
    output_node_names = ["..."]
    input_tensors = [..]
    output_tensors = [...]
    
    with tf.Session(graph=g) as sess:
      frozen_graph_def = tf.graph_util.convert_variables_to_constants(
          sess, sess.graph_def, output_node_names)
    # Note here we are passing frozen_graph_def obtained in the previous step to toco.
    tflite_model = tf.contrib.lite.toco_convert(frozen_graph_def, input_tensors, output_tensors)
    

    如果你不知道图表的输入/输出

    如果您没有定义图表,例如,这可能会发生。您从某个地方下载了图表或使用了高级 API,例如 tf.estimators 对您隐藏图表。在这种情况下,您需要在调用 toco 之前加载图形并四处寻找输入和输出。请参阅我对this SO question 的回复。

    【讨论】:

      【解决方案2】:

      按照TF example,您可以在运行 retrain.py 脚本之前传递“--Saved_model_dir”参数以将 saved_model.pb 和变量文件夹导出到某个目录(不存在的目录):

      python retrain.py ...... --saved_model_dir /home/..../export

      为了将您的模型转换为 tflite,您需要使用以下行:

      convert_saved_model.convert(saved_model_dir='/home/.../export',output_arrays="final_result",output_tflite='/home/.../export/graph.tflite')
      

      注意:需要导入convert_saved_model:

      从 tensorflow.contrib.lite.python 导入 convert_saved_model

      请记住,您可以通过 2 种方式转换为 tflite:

      但是最简单的方法是使用变量导出 saved_model.pb,以防您想避免使用像 Bazel 这样的构建工具。

      【讨论】:

        【解决方案3】:

        这对我有用:(SSD_InceptionV2 模型

        1. 完成培训后。我使用了 object_detection 文件夹中的 model_main.py。 TFv1.11
        2. 将图表导出为 TFLITE:
        python /tensorflow/models/research/object_detection/export_tflite_ssd_graph.py
        
        --pipeline_config_path annotations/ssd_inception_v2_coco.config 
        --trained_checkpoint_prefix trained-inference-graphs/inference_graph_v7.pb/model.ckpt 
        --output_directory trained-inference-graphs/inference_graph_v7.pb/tflite 
        --max_detections 3
        
        1. 这会生成一个 .pb 文件,因此您可以像这样从中生成 tflite 文件:
        tflite_convert 
        --output_file=test.tflite 
        --graph_def_file=tflite_graph.pb 
        --input_arrays=normalized_input_image_tensor 
        --output_arrays='TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1','TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3'
        
        --input_shape=1,300,300,3 
        --allow_custom_ops
        

        现在输入/输出我不是 100 确定如何得到这个,但这段代码以前对我有帮助:

        import tensorflow as tf
        frozen='/tensorflow/mobilenets/mobilenet_v1_1.0_224.pb'
        gf = tf.GraphDef()
        gf.ParseFromString(open(frozen,'rb').read())
        [n.name + '=>' +  n.op for n in gf.node if n.op in ( 'Softmax','Placeholder')]    
        [n.name + '=>' +  n.op for n in gf.node if n.op in ( 'Softmax','Mul')]
        

        【讨论】:

          【解决方案4】:
          converter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(
              frozen_model_filename, INPUT_NODE, OUTPUT_NODE)
          
          tflite_model = converter.convert()
          open(TFLITE_OUTPUT_FILE, "wb").write(tflite_model)
          

          INPUT_NODE 和 OUTPUT_NODE 分别是输入和输出名称的列表。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-08
            • 1970-01-01
            • 1970-01-01
            • 2018-01-11
            • 2018-12-09
            相关资源
            最近更新 更多