tf.group 中的操作是否按顺序执行? [英] Are the operations in tf.group executed in order?

查看:22
本文介绍了tf.group 中的操作是否按顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tf.group() 按顺序执行?

Are the operations in tf.group() executed in order?

如果它们不是按顺序执行的,有没有类似的操作让它们按顺序运行?或者有没有一种干净的方式来按顺序运行它们?

If they are not executed in order, is there a similar operation that makes them run in order? Or is there a clean way to run them in order?

我的目标是反复多次运行操作 A 和 B,即

My aim is to run operations A and B many times over and over again, i.e.

sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
...

推荐答案

操作不一定按顺序执行.

The operations do not necessarily execute in order.

以下是证明这一点的测试:

Here is a test that proves this:

import tensorflow as tf
sess = tf.InteractiveSession()
a = tf.Variable(1.0)
b = tf.Variable(10.0)
c = tf.Variable(0.0)
grp = tf.group(tf.assign(c, a), tf.assign(c, b)) # this is the group op
for i in range(100):
    sess.run(tf.global_variables_initializer()) # initialize c each time
    sess.run(grp) # run the group op
    print(sess.run(c)) # observe results

当我在 cpu 上运行它时,我发现一些迭代产生 1.0 和一些 10.0.

When I run this on a cpu, I get that some iterations produce 1.0 and some 10.0.

tf.group 不要求操作在同一台设备上,这意味着它们不能按照命令执行.

tf.group does not require the operations to be on the same device, which means that they could not be expected to follow an order.

如果您希望操作按顺序执行,请确保使用 构建它们control_dependencies

If you want the operations to execute in order, make sure to build them with control_dependencies

import tensorflow as tf
sess = tf.InteractiveSession()
a = tf.Variable(1.0)
b = tf.Variable(10.0)
c = tf.Variable(0.0)
op1  = tf.assign(c, a)
with tf.get_default_graph().control_dependencies([op1]):
    op2 = tf.assign(c, b) # op2 will execute only after op1
grp = tf.group(op1,op2)
for i in range(100):
    sess.run(tf.global_variables_initializer())
    sess.run(grp)
    print(sess.run(c))

这篇关于tf.group 中的操作是否按顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆