Python 在Tensorflow中使用tf.while\u循环更新变量

Python 在Tensorflow中使用tf.while\u循环更新变量,python,tensorflow,Python,Tensorflow,我想更新Tensorflow中的一个变量,因此我使用tf.while\u循环,如下所示: a = tf.Variable([0, 0, 0, 0, 0, 0] , dtype = np.int16) i = tf.constant(0) size = tf.size(a) def condition(i, size, a): return tf.less(i, size) def body(i, size, a): a = tf.scatter_update(a, i ,

我想更新Tensorflow中的一个变量,因此我使用tf.while\u循环,如下所示:

a = tf.Variable([0, 0, 0, 0, 0, 0] , dtype = np.int16)

i = tf.constant(0)
size = tf.size(a)

def condition(i, size, a):
    return tf.less(i, size)

def body(i, size, a):
    a = tf.scatter_update(a, i , i)
    return [tf.add(i, 1), size, a]

r = tf.while_loop(condition, body, [i, size, a])

这是我试图做的一个例子。出现的错误是
AttributeError:'Tensor'对象没有属性'\u lazy\u read'
。更新Tensorflow中的变量的适当方法是什么?

在编码并执行之前,这并不明显。是这样的

输出为

[数组([0,1,2,3,4,5]),6]

  • 获取具有这些参数的现有变量或创建新变量
  • 这是一种先发生后发生的关系。在这种情况下,我知道
    scatter\u更新发生在
    之前,而
    增加并返回。没有这个,它不会更新

  • 注意:我没有真正理解错误的含义或原因。我也明白。

    非常感谢您抽出时间。我明白你的意思,这对我很有效。可能是重复的
    import tensorflow as tf
    
    
    def cond(size, i):
        return tf.less(i,size)
    
    def body(size, i):
    
        a = tf.get_variable("a",[6],dtype=tf.int32,initializer=tf.constant_initializer(0))
        a = tf.scatter_update(a,i,i)
    
        tf.get_variable_scope().reuse_variables() # Reuse variables
        with tf.control_dependencies([a]):
            return (size, i+1)
    
    with tf.Session() as sess:
    
        i = tf.constant(0)
        size = tf.constant(6)
        _,i = tf.while_loop(cond,
                        body,
                        [size, i])
    
        a = tf.get_variable("a",[6],dtype=tf.int32)
    
        init = tf.initialize_all_variables()
        sess.run(init)
    
        print(sess.run([a,i]))