【问题标题】:Why is convert_variables_to_constants() deprecated in TF2?为什么在 TF2 中不推荐使用 convert_variables_to_constants()?
【发布时间】:2019-11-13 08:55:27
【问题描述】:

正如标题所说,为什么在 tensorflow 2 中不推荐使用 convert_variables_to_constants()?获取可保存模型以加载到下游独立应用程序以进行推理(在我的情况下,使用 C API)的简单替代方法是什么。

【问题讨论】:

    标签: c python-3.x tensorflow tensorflow2.0


    【解决方案1】:

    在 TF 2.x 中没有 tf.Session(),这是在 TF 1.x 中构建冻结模型的必要组件,在 TF 2.0 中不再存在。

    根据TensorFlow 2.0.0 release description“删除了 freeze_graph 命令行工具;应使用 SavedModel 代替冻结图。”因此,您只能使用SavedModel

    但是,如果您仍然需要冻结图表,您

    # Save model to SavedModel format
    tf.saved_model.save(model, "./models/simple_model")
    
    # Convert Keras model to ConcreteFunction
    full_model = tf.function(lambda x: model(x))
    full_model = full_model.get_concrete_function(
        x=tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))
    
    # Get frozen ConcreteFunction
    frozen_func = convert_variables_to_constants_v2(full_model)
    frozen_func.graph.as_graph_def()
    
    layers = [op.name for op in frozen_func.graph.get_operations()]
    

    然后将其保存为冻结图。

    注意:您现在应该使用 TF 1.x 加载此冻结图 函数,

    tf.io.write_graph(graph_or_graph_def=frozen_func.graph,
                      logdir="./frozen_models",
                      name="simple_frozen_graph.pb",
                      as_text=False)
    

    然后加载这个模型(TF 1.x 代码)你会做-

    with tf.io.gfile.GFile("./frozen_models/simple_frozen_graph.pb", "rb") as f:
        graph_def = tf.compat.v1.GraphDef()
        loaded = graph_def.ParseFromString(f.read())
    

    freeze_graph 减少的延迟对于应用程序可能非常重要,存储在SavedModel 中的全精度权重可能是一个问题。但是也有一些简单的方法可以解决这个问题,这超出了这个问题的范围。

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 2017-11-04
      • 2011-10-22
      • 2011-04-11
      • 2021-10-12
      • 2012-12-07
      • 2012-05-16
      • 2020-06-29
      • 2014-08-11
      相关资源
      最近更新 更多