我有tf.while_loop
,其中的条件是基于tf.Variable
中的元素。问题是当我使用tf.scatter_update
时,出现以下错误消息(注意:当我使用tf.add
时工作正常):
---> 11 var = tf.scatter_update(var, [0], tf.add(var, tf.constant([1.0])))
AttributeError: 'Tensor' object has no attribute '_lazy_read'
简化代码如下(注意:我不能使用tf.add
,因为我只想更新变量张量中的一个元素,所以我必须使用tf.scatter_update
):
def func(var1, cons):
var1, _ = tf.while_loop(cond, body, [var1, x], return_same_structure=True)
with tf.control_dependencies([var1, _]):
return var1
def cond(var, cons):
return tf.reduce_all(tf.less(var,cons))
def body(var, cons):
var = tf.scatter_update(var, [0], tf.add(var, tf.constant([1.0])))
# Works fine when using --> var = tf.add(var, tf.constant([1.0]))
return (var, cons)
with tf.Session() as sess:
x = tf.constant([10.0])
m = tf.Variable([2.0])
b = func(m, x)
init = tf.initialize_all_variables()
sess.run(init)
print sess.run(b)
答案 0 :(得分:1)
尝试tf.get_variable
。
import tensorflow as tf
def func(var1, cons):
var1, _ = tf.while_loop(cond, body, [var1, cons], return_same_structure=True)
with tf.control_dependencies([var1, _]):
return var1
def cond(var, cons):
return tf.reduce_all(tf.less(var,cons))
def body(var, cons):
var = tf.get_variable(name="m",initializer=[2.0])
var = tf.scatter_update(var, [0], tf.add(var, tf.constant([1.0])))
# var = tf.add(var, tf.constant([1.0]))
return (var, cons)
with tf.Session() as sess:
x = tf.constant([10.0])
m = tf.Variable([2.0],name='m')
b = func(m, x)
init = tf.initialize_all_variables()
sess.run(init)
print(sess.run(b))
[10.]