以下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'
能否请您告诉我为什么会导致错误?
答案 0 :(得分:3)
张量和变量是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
时,请考虑使用read_value()
中的v1
操作:
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