【问题标题】:tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)) in tensorflow张量流中的 tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS))
【发布时间】:2018-12-14 02:35:40
【问题描述】:

张量流中tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS))的用途是什么?

更多上下文:

    optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
        train_op = optimizer.minimize(loss_fn, var_list=tf.trainable_variables())

【问题讨论】:

  • 这段代码在batch_normalization中吗?

标签: python tensorflow deep-learning


【解决方案1】:

tf.control_dependencies 方法允许确保用作上下文管理器输入的操作在上下文管理器内部定义的操作之前运行。

例如:

count = tf.get_variable("count", shape=(), initializer=tf.constant_initializer(1), trainable=False)
count_increment = tf.assign_add(count, 1)
c = tf.constant(2.)
with tf.control_dependencies([count_increment]):
    d = c + 3
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print("eval count", count.eval())
    print("eval d", d.eval())
    print("eval count", count.eval())

打印出来:

eval count 1
eval d 5.0 # Running d make count_increment operation being run
eval count 2 # count_increment operation has be run and now count hold 2.

因此,在您的情况下,每次运行 train_op 操作时,它都会首先运行 tf.GraphKeys.UPDATE_OPS 集合中定义的所有操作。

【讨论】:

  • 但是使用tf.control_dependencies的真正实际用例是什么?
  • 如果您将变量a 重命名为count,使其不可训练并将操作b 重命名为increment_count,您可以有一个计数器来记录您调用的次数操作d.
  • 这是一个很好的用例,即控制评估张量的顺序:stackoverflow.com/questions/53725512/…
【解决方案2】:

如果您使用例如tf.layers.batch_normalization,该层将创建一些操作,需要在每个训练步骤运行(更新变量的移动平均值和方差)。

tf.GraphKeys.UPDATE_OPS 是这些变量的集合,如果你把它放在tf.control_dependencies 块中,这些操作将在训练操作运行之前执行。

https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization

【讨论】:

  • 除了batch_normalization还有其他用例吗?
  • 我不知道。通过在 TF 文档中快速搜索,它看起来可能在 tf.metrics 包中使用,但看起来这些函数只返回一个更新操作,您需要手动将其放入集合中。
  • 更多关于tf.GraphKeys.UPDATE_OPS stackoverflow.com/a/48261613/1179925的背景信息
猜你喜欢
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 2021-05-17
相关资源
最近更新 更多