天天看點

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 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)

@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.

 # 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.

 # Add an Op to initialize global variables.

 init_op = tf.global_variables_initializer()

     # 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,它将變量的初始值賦給變量本身。

在會話中啟動圖形。

session()作為sess:

#運作變量初始化器。

sess.run (w.initializer)

#……現在可以運作使用'w'值的ops…

最常見的初始化模式是使用友善的函數global_variables_initializer() '将Op添加到初始化所有變量的圖中。然後在啟動圖形之後運作該Op。

#添加一個Op來初始化全局變量。

init_op = tf.global_variables_initializer ()

運作初始化全局變量的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 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

參數:

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:如果啟用了立即執行。

“特遣部隊。變量'與立即執行不相容。使用

tfe。變量',而不是與兩個立即執行相容

和圖施工。參見[TensorFlow立即執行]

指南](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md # variables-and-optimizers)

 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

 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.

 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.

 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

 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:

 * Call `tf.get_variable_scope().set_use_resource(True)` inside a

   `tf.variable_scope` before the `tf.get_variable()` call.

 `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)

 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.

     ValueError: If the initial value is not specified, or does not have a

       shape and `validate_shape` is `True`.