『TensorFlow』流程控制之tf.identity

2022-02-07

详细介绍

下面的程序需要做的是循环5次,每次循环给x加1,赋值给y,然后打印出来,

x = tf.Variable(0.0)
#返回一个op,表示给变量x加1的操作
x_plus_1 = tf.assign_add(x, 1)
 
#control_dependencies的意义是,在执行with包含的内容(在这里就是 y = x)前
#先执行control_dependencies中的内容(在这里就是 x_plus_1)
with tf.control_dependencies([x_plus_1]):
    y = x

图片[1]-『TensorFlow』流程控制之tf.identity-唐朝资源网

init = tf.initialize_all_variables() with tf.Session() as session: init.run() for i in xrange(5): print(y.eval())

因此,它会在执行打印之前执行。

这打印了0,0,0,0,0,表示没有达到我们预期的效果。这是因为此时的y是复制x变量的变量,与图上的节点不匹配。连接不接受流控函数的调度,

图片[2]-『TensorFlow』流程控制之tf.identity-唐朝资源网

改为以下,

import tensorflow as tf 
x = tf.Variable(0.0) 
print(x) 
x_plus_1 = tf.assign_add(x, 1) 
with tf.control_dependencies([x_plus_1]): 
    y = x + 0.0 
    print(y) #z=tf.identity(x,name='x') 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    sess.run(init) 
    for i in range(5): 
        print(sess.run(y))

(“add:0”, shape=(), dtype=)

1.0 2.0 3.0 4.0 5.0

可以看出,当y定义为节点的输出时,操作可以顺利进行。此时y成为节点的输出,可以被图识别。

如果改成这样:

x = tf.Variable(0.0)
x_plus_1 = tf.assign_add(x, 1)
 
with tf.control_dependencies([x_plus_1]):
    y = tf.identity(x)#修改部分
init = tf.initialize_all_variables()
 
with tf.Session() as session:
    init.run()

    for i in range(5):
        print(y.eval())
This works: it prints 1, 2, 3, 4, 5.

这次它打印 1、2、3、4、5

解释:

查询y为:(“:0”, shape=(), dtype=),与节点关联。

tf.返回一个相同的新的。在动作块下,需要将一个新节点添加到 gragh 中。

分类:

技术要点:

相关文章:

© 版权声明
THE END
喜欢就支持一下吧
点赞12赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容