tensorflowAPI笔记之变量
变量
class tf.Variable
可变辅助函数
tf.all_variables()
tf.trainable_variables()
tf.initialize_all_variables()
tf.initialize_variables(var_list, name='init')
tf.assert_variables_initialized(var_list=None)
保存和恢复变量
class tf.train.Saver
tf.train.latest_checkpoint(checkpoint_dir, latest_filename=None)
tf.train.get_checkpoint_state(checkpoint_dir, latest_filename=None)
tf.train.update_checkpoint_state(save_dir, model_checkpoint_path, all_model_checkpoint_paths=None, latest_filename=None)
共享变量
tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None, trainable=True, collections=None)
tf.get_variable_scope()
tf.variable_scope(name_or_scope, reuse=None, initializer=None)
tf.constant_initializer(value=0.0)
tf.random_normal_initializer(mean=0.0, stddev=1.0, seed=None)
tf.truncated_normal_initializer(mean=0.0, stddev=1.0, seed=None)
tf.random_uniform_initializer(minval=0.0, maxval=1.0, seed=None)
tf.uniform_unit_scaling_initializer(factor=1.0, seed=None)
tf.zeros_initializer(shape, dtype=tf.float32)
稀疏变量更新
tf.scatter_update(ref, indices, updates, use_locking=None, name=None)
tf.scatter_add(ref, indices, updates, use_locking=None, name=None)
tf.scatter_sub(ref, indices, updates, use_locking=None, name=None)
tf.sparse_mask(a, mask_indices, name=None)
class tf.IndexedSlices
讲解
变量
class tf.Variable
-
变量在调用run()时获得图中的状态。您可以通过构造类Variable的实例将变量添加到图形中。 初始值定义变量的类型和形状。
-
构造完成后,变量的类型和形状是固定的。可以使用其中一种assign方法更改该值。 如果您之后想更改变量的形状,则必须
在validate_shape=False下使用 assign操作。 -
与任何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。您可以通过运行初始化程序op,从保存文件恢复变量,或者只是运行assign为变量赋值的Op来初始化变量。实际上,变量初始化器op只是一个assign Op,它将变量的初始值赋给变量本身。
# 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()初始化所有变量,将这个Op添加到图形中。然后在启动图形后运行该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()。这可确保以正确的顺序初始化变量。
所有变量都会自动收集在创建它们的图形中。默认情况下,构造函数将新变量添加到图集合中GraphKeys.VARIABLES。便捷函数 all_variables()返回该集合的内容。
在构建机器学习模型时,通常很容易区分保持可训练模型参数的变量和其他变量,例如global step用于计算训练步骤的变量。为了使这更容易,变量构造函数支持一个trainable=参数。如果 True,新变量也会添加到图表集合中 GraphKeys.TRAINABLE_VARIABLES。便捷函数 trainable_variables()返回此集合的内容。各种Optimizer类使用此集合作为要优化的变量的默认列表。
创建变量构造函数。
tf.Variable.__init__(initial_value, trainable=True, collections=None, validate_shape=True, name=None)
使用值创建新变量initial_value。
新变量将添加到列出的图表集合中collections,默认为[GraphKeys.VARIABLES]。
如果trainable是True变量也被添加到图集合中 GraphKeys.TRAINABLE_VARIABLES。
此构造函数创建variableOp和assignOp以将变量设置为其初始值。
参数ARGS:
- initial_value:A Tensor,或可转换为Tensor的Python对象。变量的初始值。必须具有指定的形状,除非
validate_shape设置为False。 - trainable:如果True是默认值,还会将变量添加到图表集合中
- GraphKeys.TRAINABLE_VARIABLES。此集合用作类使用的默认变量列表Optimizer。
- collections:图表集合键列表。新变量将添加到这些集合中。默认为[GraphKeys.VARIABLES]。
- validate_shape:If False,允许使用未知形状的值初始化变量。如果True,默认情况下,
- initial_value必须知道形状 。
- name:变量的可选名称。默认为’Variable’自动并且不受限制。
返回:
一个变量。
Raises抛出:
ValueError: 如果初始值没有形状并且 validate_shape是True。
tf.Variable.initialized_value()
返回初始化变量的值。
您应该使用它而不是变量本身来初始化另一个变量,其值取决于此变量的值。
# Initialize 'v' with a random tensor.
v = tf.Variable(tf.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
返回:
一个Tensor,这个变量持有它初始化后的值。
更改变量值
tf.Variable.