TF:tensorflow框架中常用函数介绍—tf.Variable()和tf.get_variable()用法及其区别

TF:tensorflow框架中常用函数介绍—tf.Variable()和tf.get_variable()用法及其区别tensorflow框架tf.Variable()和tf.get_variable()在创建变量的过程基本一样。它们之间最大的区别在于指定变量名称的参数。tf.Variable(),变量名称name是一个可选的参数。tf.get_variable(),变量名称是一个必填的参数。tensorflow.Variable()函数@tf_export("Variable")class Variable(checkpointable.CheckpointableBase):"""See the @{$variables$Variables How To} for a high level overview.A variable maintains state in the graph across calls to `run()`. You add a  variable to the graph by constructing an instance of the class `Variable`.The `Variable()` constructor requires an initial value for the variable, which can be a `Tensor` of any type and shape. The initial value defines the  type and shape of the variable. After construction, the type and shape ofthe variable are fixed. The value can be changed using one of the assign  methods.If you want to change the shape of a variable later you have to use an  `assign` Op with `validate_shape=False`.Just like any `Tensor`, variables created with `Variable()` can be used as inputs for other Ops in the graph. Additionally, all the operators overloaded for the `Tensor` class are carried over to variables, so you canalso add nodes to the graph by just doing arithmetic on variables.```pythonimport 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 + y)# Assign a new value to the variable with `assign()` or a related method.w.assign(w + 1.0)w.assign_add(1.0)@tf_export(“变量”)类变量(checkpointable.CheckpointableBase):查看@{$variables$ variables How To}获取高级概述。一个变量在调用“run()”时维护图中的状态。通过构造类“variable”的一个实例,可以将一个变量添加到图形中。'Variable()’构造函数需要一个变量的初值,它可以是任何类型和形状的'张量’。初始值定义变量的类型和形状。施工后,的类型和形状变量是固定的。可以使用指定方法之一更改值。如果以后要更改变量的形状,必须使用' assign ' Op和' validate_shape=False '。与任何“张量”一样,用“Variable()”创建的变量可以用作图中其他操作的输入。此外,“张量”类的所有运算符都重载了,因此可以转移到变量中还可以通过对变量进行运算将节点添加到图中。”“python导入tensorflow作为tf创建一个变量。w =特遣部队。变量(name = <可选名称> <初值>)像使用任何张量一样使用图中的变量。y =特遣部队。matmul (w,…另一个变量或张量……)重载的操作符也是可用的。z =特遣部队。乙状结肠(w + y)用' Assign() '或相关方法为变量赋值。w。分配(w + 1.0)w.assign_add (1.0)' ' 'When you launch the graph, variables have to be explicitly initialized before you can run Ops that use their value. You can initialize a variable by running its *initializer op*, restoring the variable from a save file, or simply running an `assign` Op that assigns a value to the variable. In fact,  the variable *initializer op* is just an `assign` Op that assigns the variable's initial value to the variable itself.```python# 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'...```The most common initialization pattern is to use the convenience function global_variables_initializer()` to add an Op to the graph that initializes  all the variables. You then run that Op after launching the graph.```python# Add an Op to initialize global variables.init_op = tf.global_variables_initializer()# Launch the graph in a session.with tf.Session() as sess:# Run the Op that initializes global variables.sess.run(init_op)# ...you can now run any Op that uses variable values...```If you need to create a variable with an initial value dependent on another variable, use the other variable's `initialized_value()`. This ensures that variables are initialized in the right order. All variables are automatically collected in the graph where they are created. By default, the constructor adds the new variable to the graph  collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function`global_variables()` returns the contents of that collection.When building a machine learning model it is often convenient to distinguish  between variables holding the trainable model parameters and other variables  such as a `global step` variable used to count training steps. To make this  easier, the variable constructor supports a `trainable=<bool>` parameter. If `True`, the new variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. The convenience function `trainable_variables()` returns the contents of this collection. The various `Optimizer` classes use this collection as the default list of  variables to optimize.WARNING: tf.Variable objects have a non-intuitive memory model. A Variable is represented internally as a mutable Tensor which can non-deterministically alias other Tensors in a graph. The set of operations which consume a Variable  and can lead to aliasing is undetermined and can change across TensorFlow versions. Avoid writing code which relies on the value of a Variable either  changing or not changing as other operations happen. For example, using Variable objects or simple functions thereof as predicates in a `tf.cond` is  dangerous and error-prone:```v = tf.Variable(True)tf.cond(v, lambda: v.assign(False), my_false_fn)  # Note: this is broken.```Here replacing tf.Variable with tf.contrib.eager.Variable will fix any nondeterminism issues.To use the replacement for variables which does not have these issues:* Replace `tf.Variable` with `tf.contrib.eager.Variable`;* Call `tf.get_variable_scope().set_use_resource(True)` inside a  `tf.variable_scope` before the `tf.get_variable()` call.@compatibility(eager)`tf.Variable` is not compatible with eager execution.  Use  `tf.contrib.eager.Variable` instead which is compatible with both eager  execution and graph construction.  See [the TensorFlow Eager Execution  guide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers)for details on how variables work in eager execution.@end_compatibility"""启动图形时,必须显式初始化变量,然后才能运行使用其值的操作。您可以通过运行它的*initializer op*来初始化一个变量,也可以从保存文件中恢复这个变量,或者简单地运行一个' assign ' op来为这个变量赋值。实际上,变量*初始化器op*只是一个' assign ' op,它将变量的初始值赋给变量本身。”“python在会话中启动图形。session()作为sess:#运行变量初始化器。sess.run (w.initializer)#……现在可以运行使用'w'值的ops…' ' '最常见的初始化模式是使用方便的函数global_variables_initializer() '将Op添加到初始化所有变量的图中。然后在启动图形之后运行该Op。”“python#添加一个Op来初始化全局变量。init_op = tf.global_variables_initializer ()在会话中启动图形。session()作为sess:运行初始化全局变量的Op。sess.run (init_op)#……您现在可以运行任何使用变量值的Op…' ' '如果需要创建一个初始值依赖于另一个变量的变量,请使用另一个变量的' initialized_value() '。这样可以确保以正确的顺序初始化变量。所有变量都自动收集到创建它们的图中。默认情况下,构造函数将新变量添加到图形集合“GraphKeys.GLOBAL_VARIABLES”中。方便的功能' global_variables() '返回该集合的内容。在构建机器学习模型时,通常可以方便地区分包含可训练模型参数的变量和其他变量,如用于计算训练步骤的“全局步骤”变量。为了简化这一点,变量构造函数支持一个' trainable=<bool> '参数。</bool>如果为True,则新变量也将添加到图形集合“GraphKeys.TRAINABLE_VARIABLES”中。便利函数' trainable_variables() '返回这个集合的内容。各种“优化器”类使用这个集合作为要优化的默认变量列表。警告:tf。变量对象有一个不直观的内存模型。一个变量在内部被表示为一个可变张量,它可以不确定性地混叠一个图中的其他张量。使用变量并可能导致别名的操作集是未确定的,可以跨TensorFlow版本更改。避免编写依赖于变量值的代码,这些变量值随着其他操作的发生而改变或不改变。例如,在“tf”中使用变量对象或其简单函数作为谓词。cond’是危险的,容易出错的:' ' 'v = tf.Variable(真正的)特遣部队。cond(v, lambda: v.assign(False), my_false_fn) #注意:这个坏了。' ' '这里替换特遣部队。与tf.contrib.eager变量。变量将修复任何非决定论的问题。使用替换变量不存在以下问题:*取代“特遣部队。变量与“tf.contrib.eager.Variable”;*在一个tf中调用' tf.get_variable_scope().set_use_resource(True) '。在调用tf.get_variable()之前调用variable_scope。@compatibility(渴望)“特遣部队。变量'与立即执行不兼容。使用“tf.contrib.eager。变量',它与立即执行和图形构造都兼容。参见[TensorFlow Eager执行指南](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#变量和优化器)有关变量在立即执行中如何工作的详细信息。@end_compatibility”“”Args:initial_value: A `Tensor`, or Python object convertible to a `Tensor`,   which is the initial value for the Variable. The initial value must have  a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. In  that case, `dtype` must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.)trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.validate_shape: If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of initial_value` must be known. caching_device: Optional device string describing where the Variable  should be cached for reading.  Defaults to the Variable's device.   If not `None`, caches on another device.  Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate  copying through `Switch` and other conditional statements.name: Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically.variable_def: `VariableDef` protocol buffer. If not `None`, recreates the Variable object with its contents, referencing the variable's nodesin the graph, which must already exist. The graph is not changed. `variable_def` and the other arguments are mutually exclusive.dtype: If set, initial_value will be converted to the given type.  If `None`, either the datatype will be kept (if `initial_value` is  a Tensor), or `convert_to_tensor` will decide.expected_shape: A TensorShape. If set, initial_value is expected  to have this shape.import_scope: Optional `string`. Name scope to add to the   `Variable.` Only used when initializing from protocol buffer.constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must  take as input the unprojected Tensor representing the value of the   variable and return the Tensor for the projected value   (which must have the same shape). Constraints are not safe to  use when doing asynchronous distributed training.Raises:ValueError: If both `variable_def` and initial_value are specified.ValueError: If the initial value is not specified, or does not have a shape and `validate_shape` is `True`.RuntimeError: If eager execution is enabled.@compatibility(eager)`tf.Variable` is not compatible with eager execution.  Use`tfe.Variable` instead which is compatible with both eager executionand graph construction.  See [the TensorFlow Eager Executionguide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers)for details on how variables work in eager execution.@end_compatibility参数:initial_value:一个“张量”,或者Python对象可转换成一个“张量”,它是变量的初始值。除非将“validate_shape”设置为False,否则必须指定初始值的形状。也可以是可调用的,没有参数,调用时返回初始值。在这种情况下,必须指定' dtype '。(注意,在这里使用初始化器函数之前,init_ops.py必须先绑定到一个形状上。)可训练的:如果“True”是默认值,那么也会将变量添加到图形集合“GraphKeys.TRAINABLE_VARIABLES”中。此集合用作“优化器”类使用的默认变量列表。集合:图形集合键的列表。新变量被添加到这些集合中。默认为“[GraphKeys.GLOBAL_VARIABLES]”。validate_shape:如果为“False”,则允许使用未知形状的值初始化变量。如果' True '是默认值,则必须知道initial_value '的形状。caching_device:可选的设备字符串,用于描述变量应该被缓存到什么地方以便读取。变量设备的默认值。如果不是“None”,则缓存到另一个设备上。典型的用法是在使用变量驻留的操作系统所在的设备上进行缓存,通过“Switch”和其他条件语句进行重复复制。name:变量的可选名称。默认值为“变量”,并自动uniquified。variable_def: ' VariableDef '协议缓冲区。如果不是“None”,则使用其内容重新创建变量对象,并引用变量的节点在图中,它必须已经存在。图形没有改变。' variable_def '和其他参数是互斥的。如果设置了,initial_value将转换为给定的类型。如果'None’,那么数据类型将被保留(如果'initial_value’是一个张量),或者'convert_to_张量’将决定。expected_shape: TensorShape。如果设置了,initial_value将具有此形状。import_scope:可选“字符串”。将作用域命名为“变量”。仅在从协议缓冲区初始化时使用。约束:一个可选的投影函数,在被“优化器”更新后应用到变量上(例如,用于实现规范约束或层权重的值约束)。函数必须将表示变量值的未投影张量作为输入,并返回投影值的张量(其形状必须相同)。在进行异步分布式培训时使用约束是不安全的。提出了:ValueError:如果同时指定了' variable_def '和initial_value。ValueError:如果没有指定初始值,或者没有形状,并且'validate_shape’为'True’。RuntimeError:如果启用了立即执行。@compatibility(渴望)“特遣部队。变量'与立即执行不兼容。使用tfe。变量',而不是与两个立即执行兼容和图施工。参见[TensorFlow立即执行]指南](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md # variables-and-optimizers)有关变量在立即执行中如何工作的详细信息。@end_compatibility@tf_export("Variable")class Variable(checkpointable.CheckpointableBase): """See the @{$variables$Variables How To} for a high level overview. A variable maintains state in the graph across calls to `run()`. You add a variable to the graph by constructing an instance of the class `Variable`. The `Variable()` constructor requires an initial value for the variable, which can be a `Tensor` of any type and shape. The initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods. If you want to change the shape of a variable later you have to use an `assign` Op with `validate_shape=False`. Just like any `Tensor`, variables created with `Variable()` can be used as inputs for other Ops in the graph. Additionally, all the operators overloaded for the `Tensor` class are carried over to variables, so you can also add nodes to the graph by just doing arithmetic on variables. ```python 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 + y) # Assign a new value to the variable with `assign()` or a related method. w.assign(w + 1.0) w.assign_add(1.0) ``` When you launch the graph, variables have to be explicitly initialized before you can run Ops that use their value. You can initialize a variable by running its *initializer op*, restoring the variable from a save file, or simply running an `assign` Op that assigns a value to the variable. In fact, the variable *initializer op* is just an `assign` Op that assigns the variable's initial value to the variable itself. ```python # 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'... ``` The most common initialization pattern is to use the convenience function `global_variables_initializer()` to add an Op to the graph that initializes all the variables. You then run that Op after launching the graph. ```python # Add an Op to initialize global variables. init_op = tf.global_variables_initializer() # Launch the graph in a session. with tf.Session() as sess: # Run the Op that initializes global variables. sess.run(init_op) # ...you can now run any Op that uses variable values... ``` If you need to create a variable with an initial value dependent on another variable, use the other variable's `initialized_value()`. This ensures that variables are initialized in the right order. All variables are automatically collected in the graph where they are created. By default, the constructor adds the new variable to the graph collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function `global_variables()` returns the contents of that collection. When building a machine learning model it is often convenient to distinguish between variables holding the trainable model parameters and other variables such as a `global step` variable used to count training steps. To make this easier, the variable constructor supports a `trainable=<bool>` parameter. If `True`, the new variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. The convenience function `trainable_variables()` returns the contents of this collection. The various `Optimizer` classes use this collection as the default list of variables to optimize. WARNING: tf.Variable objects have a non-intuitive memory model. A Variable is represented internally as a mutable Tensor which can non-deterministically alias other Tensors in a graph. The set of operations which consume a Variable and can lead to aliasing is undetermined and can change across TensorFlow versions. Avoid writing code which relies on the value of a Variable either changing or not changing as other operations happen. For example, using Variable objects or simple functions thereof as predicates in a `tf.cond` is dangerous and error-prone: ``` v = tf.Variable(True) tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken. ``` Here replacing tf.Variable with tf.contrib.eager.Variable will fix any nondeterminism issues. To use the replacement for variables which does not have these issues: * Replace `tf.Variable` with `tf.contrib.eager.Variable`; * Call `tf.get_variable_scope().set_use_resource(True)` inside a `tf.variable_scope` before the `tf.get_variable()` call. @compatibility(eager) `tf.Variable` is not compatible with eager execution. Use `tf.contrib.eager.Variable` instead which is compatible with both eager execution and graph construction. See [the TensorFlow Eager Execution guide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers) for details on how variables work in eager execution. @end_compatibility """ def __init__(self, initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None, constraint=None): """Creates a new variable with value `initial_value`. The new variable is added to the graph collections listed in `collections`, which defaults to `[GraphKeys.GLOBAL_VARIABLES]`. If `trainable` is `True` the variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This constructor creates both a `variable` Op and an `assign` Op to set the variable to its initial value. Args: initial_value: A `Tensor`, or Python object convertible to a `Tensor`, which is the initial value for the Variable. The initial value must have a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, `dtype` must be specified. (Note that initializer functions from init_ops.py must first be bound to a shape before being used here.) trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. validate_shape: If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of `initial_value` must be known. caching_device: Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. name: Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically. variable_def: `VariableDef` protocol buffer. If not `None`, recreates the Variable object with its contents, referencing the variable's nodes in the graph, which must already exist. The graph is not changed. `variable_def` and the other arguments are mutually exclusive. dtype: If set, initial_value will be converted to the given type. If `None`, either the datatype will be kept (if `initial_value` is a Tensor), or `convert_to_tensor` will decide. expected_shape: A TensorShape. If set, initial_value is expected to have this shape. import_scope: Optional `string`. Name scope to add to the `Variable.` Only used when initializing from protocol buffer. constraint: An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. Raises: ValueError: If both `variable_def` and initial_value are specified. ValueError: If the initial value is not specified, or does not have a shape and `validate_shape` is `True`. RuntimeError: If eager execution is enabled. @compatibility(eager) `tf.Variable` is not compatible with eager execution. Use `tfe.Variable` instead which is compatible with both eager execution and graph construction. See [the TensorFlow Eager Execution guide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers) for details on how variables work in eager execution. @end_compatibility tensorflow.get_variable()函数# The argument list for get_variable must match arguments to get_local_variable.# So, if you are updating the arguments, also update arguments to# get_local_variable below.@tf_export("get_variable")def get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, collections=None, caching_device=None, partitioner=None, validate_shape=True, use_resource=None, custom_getter=None, constraint=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAggregation.NONE): return get_variable_scope().get_variable( _get_default_variable_store(), name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections, caching_device=caching_device, partitioner=partitioner, validate_shape=validate_shape, use_resource=use_resource, custom_getter=custom_getter, constraint=constraint, synchronization=synchronization, aggregation=aggregation)

(0)

相关推荐