tf.variable_scope官方文档
2018-02-25 11:15
351 查看
Class variable_scope
定义于tensorflow/python/ops/variable_scope.py。variable_scope是一个上下文管理器,在创建变量(variables)时使用。
这个上下文管理器有三个功能:
表明values来自于同一个graph
确保graph是默认graph
推出一个名称空间和变量空间
If
name_or_scopeis not None, it is used as is. If
scopeis None, the
default_nameis used. 不懂
如果在同一个变量范围(scope)中,有相同的变量名,则tensorflow会自动在变量名上加后缀
_N。
在你不小心创建或共享变量的时候,变量范围(variable scope)可以提供保护性检查。下面是一个创建新变量的例子:
with tf.variable_scope("foo"): with tf.varible_scope("bar"): v = tf.get_variable("v", [1]) assert v.name == "foo/bar/v:0"
下面是一个使用
AUTO_REUSE共享变量的例子:
def foo(): with tf.variable_scope("foo", reuse=tf.AUTO_REUSE): v = tf.get_variable("v", [1]) return v v1 = foo() # Create v. v2 = foo() # Gets the same, exiting v. assert v1 == v2
下面是一个使用
reuse=True共享变量的例子:
with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) with tf.variable_scope("foo", reuse=True): v1 = tf.get_variable("v", [1]) assert v1 == v
另一种共享变量的例子,直接对scope进行操作:
with tf.variable_scope("foo") as scope: v = tf.get_variable("v", [1]) scope.reuse_variables() v1 = tf.get_variable("v", [1]) assert v1 == v
为了避免共享变量时发生意外,我们可以设置异常机制。当在none-reusing scope中创建同名变量时,抛出异常。例子:
with tf.variable_scope("foo"): v = tf.get_variable("v", [1]) v1 = tf.get_variable("v", [1]) # Raises ValueError("... v already exists ...")
相应的,在reuse mode中,如果我们创建的变量不存在,也抛出异常。例子:
with tf.variable_scope("foo", reuse=True): v = tf.get_variable("v", [1]) # Raises ValueError("... v does not exists ...")
PS:
reuse状态是自动继承的:如果我们创建一个reusing scope,那么它所有的sub-scope都是resue的。
总结
variable_scope是一个名称空间,名称空间在编译时,作为变量名的前缀可以自动保证变量名的唯一性。同时variable_scope提供了reuse机制,使我们可以重用定义过的变量。相关文章推荐
- tf.variable_scope官方文档
- tf.variable_scope官方文档
- tensorflow的共享变量,tf.Variable(),tf.get_variable(),tf.Variable_scope(),tf.name_scope()联系与区别:
- 彻底弄懂tf.Variable、tf.get_variable、tf.variable_scope以及tf.name_scope异同
- tf.variable_scope与tf.name_scope不同之处
- tensorflow 变量生成 变量管理 tf.Variable & tf.get_variable & tf.variable_scope
- tf.get_variable 和tf.variable_scope
- (Tensorflow之十九)tf.variable_scope的命名空间管理
- TensorFlow 官方文档中文版解读之2——tf.sparse_to_dense的用法
- tf.name_scope() 与 tf.variable_scope() 的区别
- TensorFlow 学习(一)—— tf.get_variable() vs tf.Variable(),tf.name_scope() vs tf.variable_scope()
- TensorFlow 官方文档中文版解读之1 ——tf.concat的用法的用法
- tensorflow学习笔记十五:tensorflow官方文档学习 Logging and Monitoring Basics with tf.contrib.learn
- Understand on the tf.variable_scope and tf.name_scope
- tf.variable_scope()和tf.name_scope(),tf.Variable()和tf.get_variable()
- tensorflow的共享变量,tf.Variable(),tf.get_variable(),tf.Variable_scope(),tf.name_scope()联系与区别
- Tensorflow中tf.get_variable和tf.variable_scope的使用
- tf.name_scope&tf.variable scope
- tf.get_variable tf.variable_scope tf.name_scope
- tf.variable_scope()和tf.name_scope()函数的区别