【问题标题】:Update a variable with tf.while_loop in Tensorflow在 Tensorflow 中使用 tf.while_loop 更新变量
【发布时间】:2018-09-10 15:13:05
【问题描述】:

我想在 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 中更新变量的适当方法是什么?

【问题讨论】:

标签: python tensorflow


【解决方案1】:

这在编写代码并执行之前并不明显。是这样的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]))

输出是

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

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

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

【讨论】:

  • 非常感谢您的宝贵时间。我明白你的意思,这对我有用。
猜你喜欢
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多