TF:tensorflow框架中常用函数介绍—tf.Variable()和tf.get_variable()用法及其区别
TF:tensorflow框架中常用函数介绍—tf.Variable()和tf.get_variable()用法及其区别
目录
tensorflow框架
tensorflow.Variable()函数
tensorflow.get_variable()函数
tensorflow框架
tf.Variable()和tf.get_variable()在创建变量的过程基本一样。它们之间最大的区别在于指定变量名称的参数。
- tf.Variable(),变量名称name是一个可选的参数。
- tf.get_variable(),变量名称是一个必填的参数。
tensorflow.Variable()函数
@tf_export("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 avariable 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 thetype and shape of the variable. After construction, the type and shape ofthe variable are fixed. The value can be changed using one of the assignmethods.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 asinputs for other Ops in the graph. Additionally, all the operatorsoverloaded 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)```When you launch the graph, variables have to be explicitly initialized beforeyou can run Ops that use their value. You can initialize a variable byrunning its *initializer op*, restoring the variable from a save file, orsimply running an `assign` Op that assigns a value to the variable. In fact,the variable *initializer op* is just an `assign` Op that assigns thevariable'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 initializesall 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 anothervariable, use the other variable's `initialized_value()`. This ensures thatvariables are initialized in the right order.All variables are automatically collected in the graph where they arecreated. By default, the constructor adds the new variable to the graphcollection `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 distinguishbetween variables holding the trainable model parameters and other variablessuch as a `global step` variable used to count training steps. To make thiseasier, 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. Thevarious `Optimizer` classes use this collection as the default list ofvariables to optimize.WARNING: tf.Variable objects have a non-intuitive memory model. A Variable isrepresented internally as a mutable Tensor which can non-deterministicallyalias other Tensors in a graph. The set of operations which consume a Variableand can lead to aliasing is undetermined and can change across TensorFlowversions. Avoid writing code which relies on the value of a Variable eitherchanging or not changing as other operations happen. For example, usingVariable objects or simple functions thereof as predicates in a `tf.cond` isdangerous 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 anynondeterminism issues.To use the replacement for variables which doesnot 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 eagerexecution and 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"""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 thevariable 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 havea shape specified unless `validate_shape` is set to False. Can also be acallable with no argument that returns the initial value when called. Inthat case, `dtype` must be specified. (Note that initializer functionsfrom 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 graphcollection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used asthe default list of variables to use by the `Optimizer` classes.collections: List of graph collections keys. The new variable is added tothese collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.validate_shape: If `False`, allows the variable to be initialized with avalue of unknown shape. If `True`, the default, the shape of`initial_value` must be known.caching_device: Optional device string describing where the Variableshould be cached for reading. Defaults to the Variable's device.If not `None`, caches on another device. Typical use is to cacheon the device where the Ops using the Variable reside, to deduplicatecopying through `Switch` and other conditional statements.name: Optional name for the variable. Defaults to `'Variable'` and getsuniquified automatically.variable_def: `VariableDef` protocol buffer. If not `None`, recreatesthe 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` isa Tensor), or `convert_to_tensor` will decide.expected_shape: A TensorShape. If set, initial_value is expectedto 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 variableafter being updated by an `Optimizer` (e.g. used to implement normconstraints or value constraints for layer weights). The function musttake as input the unprojected Tensor representing the value of thevariable and return the Tensor for the projected value(which must have the same shape). Constraints are not safe touse 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 ashape 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
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)
TF:tensorflow框架中常用函数介绍—tf.Variable()和tf.get_variable()用法及其区别相关推荐
- 【python】tensorflow框架中的tf.gather_nd()函数对应的 pytorch框架的gather_nd()函数
tf.gather_nd 函数对应的pytorch函数 1. 简单介绍 2. 步入正题 2.1 tensorflow tf.gather_nd() 2.2 pytorch框架手动实现gather_nd ...
- Pandas入门之常用函数介绍
一.Pandas简介 pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的. Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具. pan ...
- php spl函数,PHP SPL标准库中的常用函数介绍
这篇文章主要介绍了PHP SPL标准库中的常用函数介绍,本文着重讲解了spl_autoload_extensions().spl_autoload_register().spl_autoload()三 ...
- 帝国cms cj1.php,帝国cms源码中常用函数所在位置
帝国cms源码中常用函数所在位置 发布时间:2014-03-28 15:00:26 作者:佚名 我要评论 帝国cms常用函数所在位置归总,使用帝国cms的朋友可以收藏下 帝国cms常用函数所在 ...
- oracle常用函数number,Oracle 常用函数介绍
Oracle常用函数介绍,包括日期函数.类型转换函数 常用日期函数 1.add_months()函数可以得到指定日期之前或之后n个月的日期 date_value:=add_months(date_va ...
- Py之Numpy:Numpy库中常用函数的简介、应用之详细攻略
Py之Numpy:Numpy库中常用函数的简介.应用之详细攻略 目录 Numpy库中常用函数的简介.应用 1.X, Y = np.meshgrid(X, Y) 相关文章 Py之Numpy:Numpy库 ...
- oracle中各种函数,oracle中常用函数大全
1.数值型常用函数 函数 返回值 样例 显示 ceil(n) 大于或等于数值n的最小整数 select ceil(10.6) from dual; 11 floor(n) 小于等于数值n的最大整数 s ...
- concat函数_三、P57-61 MySQL中常用函数
本部分主要讲解MySQL数据库中常用函数的使用. P57 SQL中的函数类型:字符串函数.数值函数.日期和时间函数.流程函数.其他常用函数: P58 第1部分:字符串函数 1.concat函数 con ...
- 计算机应用常用的30个函数,Excel中常用函数的使用
ISSN 1009-30" 咖船r Kno别b内e and伯叻肋叻电奠知识'i技术 V01.6,No.30,October20lO,pP.8523-8524E-mail:x8jl@cccc. ...
最新文章
- Oracle安装完成后如何创建表空间及用户
- DXPerience6.x 使用体会(二)
- 【c++】 类与对象
- spring 面向接口编程_Spring面向方面的编程
- RestQL:现代化的 API 开发方式
- ssh user@host command 与login host运行shell的区别
- shell-最近7天目录
- .NET笔试题(关于迭代的:遍历XML中的FileName)
- 批处理也玩创建快捷方式
- Kicad快捷键大全
- 简单的springboot应用,日志,静态资源配置
- 高速公路的一些线路计算
- 稳定状态模型 (三):Volterra 模型
- UEFI学习(一)-EDK II环境搭建
- 设计模式 - 状态模式
- 逆向经验 + 逆向工具
- 图像语义分割及神经网络
- Java 位运算详解
- linux eval命令详解,linux命令详解——eval
- ARIMA模型来预测股票数据
热门文章
- ubuntu用不了root用户:~$ su - root Password: su: Authentication failure怎么办?
- [备忘]macOS和Windows下很赞的软件
- 在weka中配置自己的算法 zz
- python实现e2lsh高维数据集k近邻搜索——实现流程
- 【目录】python全栈工程师自动化+Py全栈+爬虫+Ai+python全栈工程师
- 翻翻git之---溜的飞起的载入效果AVLoadingIndicatorView
- case分支 shell函数 字符串的处理
- 链路层的封装方式与IP选路 (二)
- OpenResty 概要及原理科普
- Spring Cloud Netflix项目进入维护模式之我见