tf.assign to variable slice doesn't work inside tf.while_loop

前端 未结 3 1140
我在风中等你
我在风中等你 2021-01-13 04:32

What is wrong with the following code? The tf.assign op works just fine when applied to a slice of a tf.Variable if it happens outside of a loop.

3条回答
  •  囚心锁ツ
    2021-01-13 04:56

    I was executing this a few times and it isn't consistent. But variable slices do work inside the while loop.

    Tried to split the graph inside body because the results are incorrect sometimes.

    The correct answer (11, array([ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])) is returned sometimes but not always.

    import tensorflow as tf
    
    v = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    n = len(v)
    a1 = tf.Variable(v, name = 'a')
    
    def cond(i, _):
        return i < n
    
    s = tf.InteractiveSession()
    s.run(tf.global_variables_initializer())
    
    def body( i, _):
        x = a1[i-1]
        y = a1[i-2]
        z = tf.add(x,y)
        op = a1[i].assign( z )
        with tf.control_dependencies([op]): #Edit This fixed the inconsistency.
           increment = tf.add(i, 1)
        return increment, op
    
    print(s.run(tf.while_loop(cond, body, [2, a1])))
    

提交回复
热议问题