【问题标题】:How can I know the output and input tensor names in a saved model如何知道已保存模型中的输出和输入张量名称
【发布时间】:2020-03-30 14:29:59
【问题描述】:

我知道如何加载保存的 TensorFlow 模型,但我如何知道输入和输出张量名称。

我可以使用 tf.import_graph_def 加载 protobuf 文件,然后使用函数 get_tensor_by_name 加载张量,但我如何知道任何预训练模型的张量名称。我需要检查他们的文档还是有其他方法。

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    假设输入和输出张量是占位符,这样的事情应该对你有帮助:

    X = np.ones((1,3), dtype=np.float32)
    tf.reset_default_graph()
    model_saver = tf.train.Saver(defer_build=True)
    input_pl = tf.placeholder(tf.float32, shape=[1,3], name="Input")
    w = tf.Variable(tf.random_normal([3,3], stddev=0.01), name="Weight")
    b = tf.Variable(tf.zeros([3]), name="Bias")
    output = tf.add(tf.matmul(input_pl, w), b)
    model_saver.build()
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    model_saver.save(sess, "./model.ckpt")
    

    现在,图表已构建并保存,我们可以看到如下占位符名称:

    model_loader = tf.train.Saver()
    sess = tf.Session()
    model_loader.restore(sess, "./model.ckpt")
    placeholders = [x for x in tf.get_default_graph().get_operations() if x.type == "Placeholder"]
    # [<tf.Operation 'Input' type=Placeholder>]
    

    【讨论】:

    • 是的,这样我可以得到张量的列表,但是我怎么知道输入和输出张量的模型架构。
    • 这就是为什么我在创建图表时为输入张量命名的原因。这样,在加载图表时,您就知道要获取哪些张量,以便将数据输入到图表中。
    【解决方案2】:

    您可以检查图中每个操作的名称和输入列表,以查找张量的名称。

    with tf.gfile.GFile(input_model_filepath, "rb") as f:
      graph_def = tf.GraphDef()
      graph_def.ParseFromString(f.read())
    
    with tf.Graph().as_default() as graph:
      tf.import_graph_def(graph_def)
    
    for op in graph.get_operations():
      print(op.name, [inp for inp in op.inputs])
    

    【讨论】:

      【解决方案3】:

      仅针对输入的解决方案:

      # read pb into graph_def
      with tf.gfile.GFile(input_model_filepath, "rb") as f:
          graph_def = tf.GraphDef()
          graph_def.ParseFromString(f.read())
      
      # import graph_def
      with tf.Graph().as_default() as graph:
          tf.import_graph_def(graph_def)
      
      # print operations
      for op in graph.get_operations():
          if op.type == "Placeholder":
              print(op.name)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        相关资源
        最近更新 更多