下面的Tensorflow代码工作良好,v1
变为1.、1.、1。
v1 = tf.get_variable('v1', shape=[3], initializer=tf.zeros_initializer)
v1 = v1 + 1
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print (v1.eval())
下面的代码段也给出了与上面的结果完全相同的结果。如果我们运行v1
,那么sess.run(inc_v1)
就变成1.,1,1。
v1 = tf.get_variable('v1', shape=[3], initializer=tf.zeros_initializer)
inc_v1 = v1.assign(v1 + 1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(inc_v1)
print (v1.eval())
但是,下面的代码会导致错误。
v1 = tf.get_variable('v1', shape=[3], initializer=tf.zeros_initializer)
v1 = v1 + 1
inc_v1 = v1.assign(v1 + 1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(inc_v1)
print (v1.eval())
错误如下:
AttributeError: 'Tensor' object has no attribute 'assign'
你能告诉我为什么会出错吗?
发布于 2018-07-04 06:35:41
张量和变量是TensorFlow中的不同对象。
import tensorflow as tf
def inspect(t):
print('\n %s\n-------' % t.name)
print(type(t))
print(t.op.outputs)
print('has assign method' if 'assign' in dir(t) else 'has no assign method')
v1 = tf.get_variable('v1', shape=[3], initializer=tf.zeros_initializer)
inspect(v1)
v2 = v1 + 1
inspect(v2)
给出
v1:0
-------
<class 'tensorflow.python.ops.variables.Variable'>
[<tf.Tensor 'v1:0' shape=(3,) dtype=float32_ref>]
has assign method
add:0
-------
<class 'tensorflow.python.framework.ops.Tensor'>
[<tf.Tensor 'add:0' shape=(3,) dtype=float32>]
has no assign method
因此,v1:0
本身就是变量,而v1
有方法assign
。这是有意义的,因为它只是对浮点值的引用。另一方面,v2 = v1 + 1
会导致add
操作的输出。因此,v2
不再是一个变量,您不能将一个新值赋给v2
。在这种情况下,您希望更新add
的哪个操作数?每当您使用v1
时,请考虑使用v1
中的read_value()
操作:
v1 = tf.get_variable('v1', shape=[3], initializer=tf.zeros_initializer)
inspect(v1)
w = v1.read_value()
inspect(w)
v2 = v1.read_value() + 1
inspect(v2)
给出
v1:0
-------
<class 'tensorflow.python.ops.variables.Variable'>
[<tf.Tensor 'v1:0' shape=(3,) dtype=float32_ref>]
has assign method
read:0
-------
<class 'tensorflow.python.framework.ops.Tensor'>
[<tf.Tensor 'read:0' shape=(3,) dtype=float32>]
has no assign method
add:0
-------
<class 'tensorflow.python.framework.ops.Tensor'>
[<tf.Tensor 'add:0' shape=(3,) dtype=float32>]
has no assign method
https://stackoverflow.com/questions/51166162
复制相似问题