如何为TensorFlow变量分配值? [英] How to assign a value to a TensorFlow variable?
问题描述
我正在尝试为python中的tensorflow变量分配一个新值.
I am trying to assign a new value to a tensorflow variable in python.
import tensorflow as tf
import numpy as np
x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
print(x.eval())
x.assign(1)
print(x.eval())
但是我得到的输出是
0
0
因此该值未更改.我想念什么?
So the value has not changed. What am I missing?
推荐答案
在TF1中,语句 tf.Operation
,您必须明确地 run 来更新变量.*调用 Operation.run()
或
In TF1, the statement x.assign(1)
does not actually assign the value 1
to x
, but rather creates a tf.Operation
that you have to explicitly run to update the variable.* A call to Operation.run()
or Session.run()
can be used to run the operation:
assign_op = x.assign(1)
sess.run(assign_op) # or `assign_op.op.run()`
print(x.eval())
# ==> 1
(*实际上,它返回与变量的更新值相对应的tf.Tensor
,以便更轻松地进行链式分配.)
(* In fact, it returns a tf.Tensor
, corresponding to the updated value of the variable, to make it easier to chain assignments.)
但是,在TF2中, x.assign(1)
现在将分配渴望价值:
However, in TF2 x.assign(1)
will now assign the value eagerly:
x.assign(1)
print(x.numpy())
# ==> 1
这篇关于如何为TensorFlow变量分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!