【问题标题】:What is the difference between tf.variable_scope() and tf.train.Saver()?tf.variable_scope() 和 tf.train.Saver() 有什么区别?
【发布时间】:2018-03-13 22:24:26
【问题描述】:

我正在构建一个神经网络。我在火车部分使用tf.variable_scope(),对测试部分使用相同的范围(reset=True)。我想知道如果我使用tf.train.Saver() 将变量保存在火车部分并使用tf.train.restore() 恢复测试部分的变量,是否会得到不同的结果? 基本上,我想确保将训练后的变量复制到测试部分。

例如,在下面的示例中,变量 v1 和 v_1 具有相同的值,那么,在这种情况下,我是否需要使用 tf.train.Saver() 才能获得正确的结果? 将张量流导入为 tf tf.reset_default_graph()

# Create some variables.
with tf.variable_scope("first_model"):
    v1 = tf.get_variable("v1", shape=[3], initializer = tf.zeros_initializer)
    v2 = tf.get_variable("v2", shape=[5], initializer = tf.zeros_initializer)

    inc_v1 = v1.assign(v1+2)
    dec_v2 = v2.assign(v2-1)



with tf.variable_scope("first_model", reuse=True):
    # Create some variables.
    v_1 = tf.get_variable("v1", shape=[3])
    v_2 = tf.get_variable("v2", shape=[5])

    inc_v_1 = v1.assign(v1+2)
    dec_v_2 = v2.assign(v2-1)

 # Add an op to initialize the variables.
init_op = tf.global_variables_initializer()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, and save the
# variables to disk.
with tf.Session() as sess:
  sess.run(init_op)
  # Do some work with the model.
  inc_v1.op.run()
  dec_v2.op.run()

  inc_v_1.op.run()
  dec_v_2.op.run()
  # Save the variables to disk.
  save_path = saver.save(sess, "/tmp/model_2.ckpt")
  print("Model saved in path: %s" % save_path)


  print("v1 : %s" % v1.eval())
  print("v2 : %s" % v2.eval())

  print("v_1 : %s" % v_1.eval())
  print("v_2 : %s" % v_2.eval())

【问题讨论】:

    标签: python tensorflow neural-network


    【解决方案1】:

    tf.variable_scope() 更改您的变量名称。

    例如,考虑创建一个带和不带variable_scope的变量:

    x = tf.Variable(1.0, name='myvar')
    <tf.Variable 'myvar:0' shape=() dtype=float32_ref>
    

    注意变量名为myvar:0,当您使用tf.train.Saver() 保存检查点时,这将是该变量的名称。当您使用 tf.train.restore() 恢复检查点时,您最好在图表中添加一个名为 myvar:0 的变量,否则它将不知道将变量恢复到何处。

    现在tf.variable_scope() 也一样:

    with tf.variable_scope('newscope'):
      x = tf.Variable(1.0, name='myvar')
    
    <tf.Variable 'newscope/myvar:0' shape=() dtype=float32_ref>
    

    请注意,名称现在是 newscope/myvar:0。变量的名称已更改。这使您可以保持变量命名空间井井有条。它主要用于调试和可视化 tensorboard 中的事物。

    当您保存和恢复模型时,您可以采用 2 种方法。

    基本检查点仅保存与模型关联的数据(这似乎是您在问题中引用的内容)。在此范例中,您需要在加载检查点之前重新创建图表中的所有变量,并且您的名称最好全部匹配(如果您在训练中使用 variable_scope,则最好在测试中也这样做)。这是我通常遵循的方法,我建议您将所有 tensorflow 操作放在一个名为 build_graph() 的函数中。然后为您的训练或测试重新构建图表,您只需调用该函数,瞧,图表是相同的,保存/恢复函数按预期工作。

    您可能还注意到,您可以保存 meta_graph,不仅可以恢复变量,还可以恢复图形定义(您正在执行的实际操作)。在此范例中,您首先加载 meta_graph 定义,然后加载检查点,您无需在测试环境中重新定义图。这个方法我用的不多,所以就不详细介绍了。

    【讨论】:

    • 我明白了。现在我的问题只是使用 tf.variable_scope() 我可以访问火车部分中的变量,那么为什么我需要tf.train.Saver()。我更新了我的问题以进一步澄清它。 @大卫公园
    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    • 2012-02-06
    • 2011-02-25
    • 2011-11-22
    • 2015-03-26
    相关资源
    最近更新 更多