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()函数
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 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 ```python # Create a variable. # Use the variable in the graph like any Tensor. # The overloaded operators are available too. # Assign a new value to the variable with `assign()` or a related method. |
@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 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 # Launch the graph in a session. 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: ``` 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`; @compatibility(eager) |
启动图形时,必须显式初始化变量,然后才能运行使用其值的操作。您可以通过运行它的*initializer op*来初始化一个变量,也可以从保存文件中恢复这个变量,或者简单地运行一个' assign ' op来为这个变量赋值。实际上,变量*初始化器op*只是一个' assign ' op,它将变量的初始值赋给变量本身。 ”“python 最常见的初始化模式是使用方便的函数global_variables_initializer() '将Op添加到初始化所有变量的图中。然后在启动图形之后运行该Op。 ”“python 在会话中启动图形。 如果需要创建一个初始值依赖于另一个变量的变量,请使用另一个变量的' initialized_value() '。这样可以确保以正确的顺序初始化变量。所有变量都自动收集到创建它们的图中。默认情况下,构造函数将新变量添加到图形集合“GraphKeys.GLOBAL_VARIABLES”中。方便的功能 ' global_variables() '返回该集合的内容。 在构建机器学习模型时,通常可以方便地区分包含可训练模型参数的变量和其他变量,如用于计算训练步骤的“全局步骤”变量。为了简化这一点,变量构造函数支持一个' trainable=<bool> '参数。</bool>如果为True,则新变量也将添加到图形集合“GraphKeys.TRAINABLE_VARIABLES”中。便利函数' trainable_variables() '返回这个集合的内容。各种“优化器”类使用这个集合作为要优化的默认变量列表。 警告:tf。变量对象有一个不直观的内存模型。一个变量在内部被表示为一个可变张量,它可以不确定性地混叠一个图中的其他张量。使用变量并可能导致别名的操作集是未确定的,可以跨TensorFlow版本更改。避免编写依赖于变量值的代码,这些变量值随着其他操作的发生而改变或不改变。例如,在“tf”中使用变量对象或其简单函数作为谓词。cond’是危险的,容易出错的: ' ' ' 这里替换特遣部队。与tf.contrib.eager变量。变量将修复任何非决定论的问题。 使用替换变量不存在以下问题: *取代“特遣部队。变量与“tf.contrib.eager.Variable”; @compatibility(渴望) |
Args: Raises: @compatibility(eager) |
参数: 提出了: @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)
文章来源: yunyaniu.blog.csdn.net,作者:一个处女座的程序猿,版权归原作者所有,如需转载,请联系作者。
原文链接:yunyaniu.blog.csdn.net/article/details/105446022
- 点赞
- 收藏
- 关注作者
评论(0)