class tf.Variable
一个变量通过调用run()来维护图中的状态,通过创建一个类实例添加一个变量到图中。
Variable()构造函数接受一个变量的初始值,该初始值可以是任何类型、任何shape的张量。初始值定义了变量的类型和shape,变量的shape通常是固定的,初始值是可以通过assign methods来改变的。
如果你想稍后改变变量的shape,需要把assign methods中的validate_shape指定为False,示例:
tf.assign(
ref,
value,
validate_shape=None,
use_locking=None,
name=None
)
#参数
ref:一个可变张量,应该来自一个变量节点,可能还未初始化
---------------------------------------------------------------------------------------------
value:一个张量,必需和ref类型相同,要分配给变量的值
---------------------------------------------------------------------------------------------
validate_shape:可选bool。默认为True。如果为true,则操作将验证“值”的形状与要分配的张量的形状相匹配。如果为false,'ref'将呈现'value'的形状
---------------------------------------------------------------------------------------------
use_locking: An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention.
---------------------------------------------------------------------------------------------
name:操作的名称(可选)
#return
张量ref,该张量具有一个新的值
就像任何其他Tensor变量一样,创建的变量Variable()可以用作图中其他Ops的输入。此外,所有为Tensor该类重载的运算符都将转化为变量,因此您还可以通过对变量进行算术将节点添加到图中
import tensorflow as tf
# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)
# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)
# The overloaded operators are available too.
z = tf.sigmoid(w + b)
# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)
启动计算图时,必须先明确初始化变量,然后才能运行使用其值的Ops。您可以通过运行初始化操作初始化变量,从保存文件中恢复变量,或者只需运行assign一个赋值给变量的操作。实际上,变量初始化器op只是一个assignOp,它将变量的初始值赋给变量本身
# Launch the graph in a session.
with tf.Session() as sess:
# Run the variable initializer.
sess.run(w.initializer)
# ...you now can run ops that use the value of 'w'...
通用的初始化模式是用一个方便的函数initialize_all_variables()来初始化所有的变量,在启动计算图后run这个op:
# Add an Op to initialize all variables.
init_op = tf.initialize_all_variables()
# Launch the graph in a session.
with tf.Session() as sess:
# Run the Op that initializes all variables.
sess.run(init_op)
# ...you can now run any Op that uses variable values...
如果您需要创建一个初始值依赖于另一个变量的变量,该初始值可通过initialized_value()函数获得,这确保变量按正确的顺序初始化
所有变量都会自动收集到创建它们的图形中。 默认情况下,构造函数将新变量添加到Graph集合GraphKeys.VARIABLES, 函数all_variables()返回该集合的内容
当我们建立模型的时候,我们需要参数变量进行更好的区分和收集,比如可训练参数weights和global step等超参数;变量构造函数提供了一个trainable=<bool>参数开关,如果 True,新变量也被添加到计算图集合 GraphKeys.TRAINABLE_VARIABLES中,trainable_variables()返回此集合的内容。各种Optimizer类将该集合收集的内容列表作为默认优化变量
Creating a variable.
tf.Variable.__init__(initial_value, trainable=True, collections=None, validate