Python 如何为 TensorFlow 变量赋值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34220532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign a value to a TensorFlow variable?
提问by abora
I am trying to assign a new value to a tensorflow variable in python.
我正在尝试为 python 中的 tensorflow 变量分配一个新值。
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())
But the output I get is
但我得到的输出是
0
0
So the value has not changed. What am I missing?
所以价值没有改变。我错过了什么?
采纳答案by mrry
In TF1, the statement x.assign(1)does not actually assign the value 1to x, but rather creates a tf.Operationthat you have to explicitly runto update the variable.* A call to Operation.run()or Session.run()can be used to run the operation:
在 TF1 中,该语句x.assign(1)实际上并未将值分配1给x,而是创建了tf.Operation,您必须显式运行它以更新变量。* 调用Operation.run()或Session.run()可用于运行操作:
assign_op = x.assign(1)
sess.run(assign_op) # or `assign_op.op.run()`
print(x.eval())
# ==> 1
(* In fact, it returns a tf.Tensor, corresponding to the updated value of the variable, to make it easier to chain assignments.)
(* 实际上,它返回一个tf.Tensor,对应于变量的更新值,以便更容易地进行链式赋值。)
However, in TF2 x.assign(1)will now assign the value eagerly:
但是,在 TF2 中x.assign(1)现在会急切地分配值:
x.assign(1)
print(x.numpy())
# ==> 1
回答by Gordon Erlebacher
There is an easier approach:
有一个更简单的方法:
x = tf.Variable(0)
x = x + 1
print x.eval()
回答by Salvador Dali
First of all you can assign values to variables/constants just by feeding values into them the same way you do it with placeholders. So this is perfectly legal to do:
首先,您可以将值分配给变量/常量,只需像使用占位符一样将值输入它们即可。所以这样做是完全合法的:
import tensorflow as tf
x = tf.Variable(0)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(x, feed_dict={x: 3})
Regarding your confusion with the tf.assign()operator. In TF nothing is executed before you run it inside of the session. So you always have to do something like this: op_name = tf.some_function_that_create_op(params)and then inside of the session you run sess.run(op_name). Using assign as an example you will do something like this:
关于您对tf.assign()运算符的混淆。在 TF 中,在会话内运行之前不会执行任何操作。所以你总是必须做这样的事情:op_name = tf.some_function_that_create_op(params)然后在你运行的会话内部sess.run(op_name)。以assign为例,您将执行以下操作:
import tensorflow as tf
x = tf.Variable(0)
y = tf.assign(x, 1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(x)
print sess.run(y)
print sess.run(x)
回答by kmario23
Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializerneed not be called explicitly since the assign operation does it for you in the background.
此外,必须注意的是,如果您正在使用your_tensor.assign(),则tf.global_variables_initializer无需显式调用 ,因为分配操作会在后台为您执行此操作。
Example:
例子:
In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)
In [214]: with tf.Session() as sess:
...: sess.run(w_new)
...: print(w_new.eval())
# output
34
However, this will not initialize all variables, but it will only initialize the variable on which assignwas executed on.
但是,这不会初始化所有变量,而只会初始化assign执行过的变量。
回答by Robin Dinse
You can also assign a new value to a tf.Variablewithout adding an operation to the graph: tf.Variable.load(value, session). This function can also save you adding placeholders when assigning a value from outside the graph and it is useful in case the graph is finalized.
您还可以在tf.Variable不向图形添加操作的情况下为 a 分配一个新值:tf.Variable.load(value, session)。此功能还可以节省您在从图形外部分配值时添加占位符的情况,并且在图形最终确定时很有用。
import tensorflow as tf
x = tf.Variable(0)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(x)) # Prints 0.
x.load(1, sess)
print(sess.run(x)) # Prints 1.
Update: This is depricated in TF2 as eager execution is default and graphs are no longer exposed in the user-facing API.
更新:这在 TF2 中已被弃用,因为 Eager Execution 是默认设置,并且图形不再在面向用户的 API 中公开。
回答by prosti
Here is the complete working example:
这是完整的工作示例:
import numpy as np
import tensorflow as tf
w= tf.Variable(0, dtype=tf.float32) #good practice to set the type of the variable
cost = 10 + 5*w + w*w
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)
print(session.run(w))
session.run(train)
print(session.run(w)) # runs one step of gradient descent
for i in range(10000):
session.run(train)
print(session.run(w))
Note the output will be:
请注意,输出将是:
0.0
-0.049999997
-2.499994
This means at the very start the Variable was 0, as defined, then after just one step of gradient decent the variable was -0.049999997, and after 10.000 more steps we are reaching -2.499994 (based on our cost function).
这意味着一开始变量是 0,正如定义的那样,然后在梯度下降一步之后,变量是 -0.049999997,再经过 10.000 步后,我们达到 -2.499994(基于我们的成本函数)。
Note: You originally used the Interactive session. Interactive session is useful when multiple different sessions needed to be run in the same script. However, I used the non interactive session for simplicity.
注意:您最初使用的是交互式会话。当需要在同一个脚本中运行多个不同的会话时,交互式会话非常有用。但是,为了简单起见,我使用了非交互式会话。
回答by Aashish Dahiya
Use Tensorflow eager execution mode which is latest.
使用最新的 Tensorflow 急切执行模式。
import tensorflow as tf
tf.enable_eager_execution()
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3])
print(my_int_variable)
回答by Prabhant Singh
So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:
所以我有一个不同的情况,我需要在运行会话之前分配值,所以这是最简单的方法:
other_variable = tf.get_variable("other_variable", dtype=tf.int32,
initializer=tf.constant([23, 42]))
here i'm creating a variable as well as assigning it values at the same time
在这里,我正在创建一个变量并同时为其赋值
回答by user5931
I answered a similar question here. I looked in a lot of places that always created the same problem. Basically, I did not want to assign a value to the weights, but simply change the weights. The short version of the above answer is:
我在这里回答了一个类似的问题。我查看了很多总是会产生相同问题的地方。基本上,我不想为权重赋值,而是简单地改变权重。上述答案的简短版本是:
tf.keras.backend.set_value(tf_var, numpy_weights)
tf.keras.backend.set_value(tf_var, numpy_weights)

