代码之家  ›  专栏  ›  技术社区  ›  K.Wanter

非常奇怪的张量流行为

  •  2
  • K.Wanter  · 技术社区  · 7 年前

    我有一些非常简单的线条,可以产生非常奇怪的意外行为:

    import tensorflow as tf
    
    y = tf.Variable(2, dtype=tf.int32)
    
    a1 = tf.assign(y, y + 1)
    a2 = tf.assign(y, y * 2)
    
    with tf.control_dependencies([a1, a2]):
        t = y+0
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
    
        for i in range(4):
            print('t=%d' % sess.run(t))
            print('y=%d' % sess.run(y))
    

    我们所期望的是

    t=6
    y=6
    t=14
    y=14
    t=30
    y=30
    t=62
    y=62
    

    但第一次,我得到:

    t=6
    y=6
    t=13
    y=13
    t=26
    y=26
    t=27
    y=27
    

    第二轮,我得到:

    t=3
    y=3
    t=6
    y=6
    t=14
    y=14
    t=15
    y=15
    

    第三次跑步,我得到:

    t=6
    y=6
    t=14
    y=14
    t=28
    y=28
    t=56
    y=56
    

    很可笑,多次运行会产生多个不同的输出序列,很奇怪,有人能帮忙吗?

    编辑:更改为

    import tensorflow as tf
    import os
    y = tf.Variable(2, dtype=tf.int32)
    
    a1 = tf.assign(y, y + 1)
    a2 = tf.assign(y, y * 2)
    a3 = tf.group(a1, a2)
    with tf.control_dependencies([a3]):
        t = tf.identity(y+0)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
    
        for i in range(4):
    
            print('t=%d' % sess.run(t))
            print('y=%d' % sess.run(y))
    

    。。。仍然不能正常工作。

    奇怪的是,这个代码:

    a1 = tf.assign(y, y + 1)
    with tf.control_dependencies([a1]):
      a2 = tf.assign(y, y * 2)
      with tf.control_dependencies([a2]):
        t = tf.identity(y)
    

    。。。正常工作,但只需移动 a2 至之前as

    a1 = tf.assign(y, y + 1)
    a2 = tf.assign(y, y * 2)
    with tf.control_dependencies([a1]):
      with tf.control_dependencies([a2]):
        t = tf.identity(y)
    

    。。。事实并非如此。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Maxim    7 年前

    你的方法的问题是 a1 a2 重要的是:你想要 a1级 之前进行评估 a2级 tf.control_dependencies([a1, a2]) 保证: t 在两者之后执行 a1级 a2级 ,但它们本身可以按任何顺序进行评估。

    我会选择这样的显式依赖:

    y = tf.Variable(2, dtype=tf.int32)
    a1 = tf.assign(y, y + 1)
    with tf.control_dependencies([a1]):
      a2 = tf.assign(y, y * 2)
      with tf.control_dependencies([a2]):
        t = tf.identity(y)
    
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      for i in range(4):
        print('t=%d' % sess.run(t))
        print('y=%d' % sess.run(y))
    

    输出:

    t=6
    y=6
    t=14
    y=14
    t=30
    y=30
    t=62
    y=62