Skip to main content
 首页 » 编程设计

python之在 Tensorflow 中使用 tf.while_loop 更新变量

2024年12月31日28lyhabc

我想更新 Tensorflow 中的一个变量,因此我使用 tf.while_loop 如下:

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' object has no attribute '_lazy_read'。在 Tensorflow 中更新变量的合适方法是什么?

请您参考如下方法:

在编写代码并执行之前,这一点并不明显。是这样的pattern

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

输出是

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

  1. tf.get_variable使用这些参数获取现有变量或创建新变量。
  2. tf.control_dependencies这是一种发生在之前的关系。在这种情况下,我知道 scatter_update 发生在 while 递增和返回之前。没有这个它就不会更新。

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