zoukankan      html  css  js  c++  java
  • 『TensorFlow』流程控制之tf.identity

    一个详细介绍

    下面程序要做的是,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
    init = tf.initialize_all_variables()
     
    with tf.Session() as session:
        init.run()
        for i in xrange(5):
            print(y.eval())
    

    由于control_dependencies的所以执行print前都会先执行x_plus_1。

    这个打印的是0,0,0,0,0 ,也就是说没有达到我们预期的效果,这是因为此时的y是一个复制了x变量的变量,并未和图上的节点相联系不接受流程控制函数的调遣,

    改成如下,

    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))
    

     <tf.Variable 'Variable:0' shape=() dtype=float32_ref>

    Tensor("add:0", shape=(), dtype=float32)

    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为:Tensor("Identity_1:0", shape=(), dtype=float32),和节点联系起来了。
    tf.identity是返回了一个一模一样新的tensor,再control_dependencies的作用块下,需要增加一个新节点到gragh中。

  • 相关阅读:
    Solr的核心操作案例
    分布式锁
    AngularJS——AngularJS实现地址栏取值
    【转】保证消息队列的高可用性
    【转】Spring线程及线程池的使用
    微信支付实现
    分布式id的生成方式——雪花算法
    重载new和delete
    C++工程实践
    语言基础(27):异常处理
  • 原文地址:https://www.cnblogs.com/hellcat/p/8568035.html
Copyright © 2011-2022 走看看