最近在看TensorFlow的变量管理,发现很多代码中tf.variable_scope()参数的数量及意义还不太清楚,特此记录:

def __init__(self,
name_or_scope,
default_name=None,
values=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None,
constraint=None,
auxiliary_name_scope=True):
"""Initialize the context manager.
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
default_name: The default name to use if the `name_or_scope` argument is
`None`, this name will be uniquified. If name_or_scope is provided it
won't be used and therefore it is not required and can be None.
values: The list of `Tensor` arguments that are passed to the op function.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
reuse: `True`, None, or tf.AUTO_REUSE; if `True`, we go into reuse mode
for this scope as well as all sub-scopes; if tf.AUTO_REUSE, we create
variables if they do not exist, and return them otherwise; if None, we
inherit the parent scope's reuse flag. When eager execution is enabled,
this argument is always forced to be tf.AUTO_REUSE.
dtype: type of variables created in this scope (defaults to the type
in the passed scope, or inherited from parent scope).
use_resource: If False, all variables will be regular Variables. If True,
experimental ResourceVariables with well-defined semantics will be used
instead. Defaults to False (will later change to True). When eager
execution is enabled this argument is always forced to be True.
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.
auxiliary_name_scope: If `True`, we create an auxiliary name scope with
the scope. If `False`, we don't touch name scope.
Returns:
A scope that can be captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope.
TypeError: when the types of some arguments are not appropriate.
"""
上面的代码是tf.variable函数的定义,其中
name_or_scope: `string` or `VariableScope`: the scope to open. 是变量空间的名称
default_name: 当name_or_scope 使用时它就可以忽略,基本没什么用
values: 传入该scope的tensor参数
initializer=None: 默认的参数初始化函数
regularizer: d默认的正则化函数
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
reuse: `True`, None, or tf.AUTO_REUSE; if `True`, we go into reuse mode
for this scope as well as all sub-scopes; if tf.AUTO_REUSE, we create
variables if they do not exist, and return them otherwise; if None, we
inherit the parent scope's reuse flag. When eager execution is enabled,
this argument is always forced to be tf.AUTO_REUSE
reuse有三种取值,默认取值是None:

True: 参数空间使用reuse 模式,即该空间下的所有tf.get_variable()函数将直接获取已经创建的变量,如果参数不存在tf.get_variable()函数将会报错。

AUTO_REUSE:若参数空间的参数不存在就创建他们,如果已经存在就直接获取它们。

None 或者False 这里创建函数tf.get_variable()函数只能创建新的变量,当同名变量已经存在时,函数就报错

下面是几个例子:

with tf.variable_scope("foo"):
v = tf.get_variable("v", [1], initializer=tf.constant_initializer(1.0))

#with tf.variable_scope("foo"):
# v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
print(v == v1)

#with tf.variable_scope("bar", reuse=True):
# v = tf.get_variable("v", [1])
输出是True

with tf.variable_scope("root"): # reuse 在默认情况下为false 或者和 上一层保持一致
print(tf.get_variable_scope().reuse)

with tf.variable_scope("foo", reuse=True):
print(tf.get_variable_scope().reuse)

with tf.variable_scope("bar"):
print(tf.get_variable_scope().reuse)

print(tf.get_variable_scope().reuse)

tf.name_scope和tf.variable_scope的关系

tf.name_scope和tf.variable_scope是两个作用域,主要与创建/调用变量函数tf.Variable() 和tf.get_variable()搭配使用。首先说tf.Variable() 和tf.get_variable()的区别:

tf.Variable() 每次调用都会产生一个新的变量,他会自动检测命名冲突并自行处理,变量名称是一个可选参数,例如:

a1 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')

print(a1.name)

print(a2.name)

print(a1==a2)

运行结果:

f1/a1:0
f1/a1_1:0

False    # a2实际变成了a1_1并且和a1 不是同一个变量

而tf.get_variable()则不同,遇到重命名的变量创建且变量名没有设置成共享变量(所谓的共享是指在同一参数空间下的共享,参数空间名称不一样就不能共享了)时,就会报错 ;相对应的,变量名称这个参数是必填参数,tf.get_variable()会根据这个参数去创建或者获取变量。

tf.name_scope()主要用于管理图中各种op,而tf.variable_scope()主要用于管理图中变量的名字,在 tf.name_scope下时,tf.get_variable()创建的变量名不受 name_scope 的影响(不受它的约束)

import tensorflow as tf

with tf.variable_scope('f2'):
#a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
a1 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a5 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))

with tf.variable_scope('f2', reuse=True):
a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))

a4 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a2')

print(a1.name)
print(a2.name)
print(a1==a2)
print(a5.name)
print(a3.name)
print(a4.name)
运行结果:

f2/a1:0
f2/a1_1:0
False
f2/a1_2:0
f2/a1_2:0
f2_1/a2:0

---------------------
作者:hyxing520
来源:CSDN
原文:https://blog.csdn.net/hyxing520/article/details/80889496
版权声明:本文为博主原创文章,转载请附上博文链接!

tf.variable_scope 参数的更多相关文章

  1. 深度学习原理与框架-Alexnet(迁移学习代码) 1.sys.argv[1:](控制台输入的参数获取第二个参数开始) 2.tf.split(对数据进行切分操作) 3.tf.concat(对数据进行合并操作) 4.tf.variable_scope(指定w的使用范围) 5.tf.get_variable(构造和获得参数) 6.np.load(加载.npy文件)

    1. sys.argv[1:]  # 在控制台进行参数的输入时,只使用第二个参数以后的数据 参数说明:控制台的输入:python test.py what, 使用sys.argv[1:],那么将获得w ...

  2. tf.variable和tf.get_Variable以及tf.name_scope和tf.variable_scope的区别

    在训练深度网络时,为了减少需要训练参数的个数(比如具有simase结构的LSTM模型).或是多机多卡并行化训练大数据大模型(比如数据并行化)等情况时,往往需要共享变量.另外一方面是当一个深度学习模型变 ...

  3. TF.VARIABLE、TF.GET_VARIABLE、TF.VARIABLE_SCOPE以及TF.NAME_SCOPE关系

    1. tf.Variable与tf.get_variable tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要 ...

  4. 理解 tf.Variable、tf.get_variable以及范围命名方法tf.variable_scope、tf.name_scope

    tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要将变量通过参数的形式到处传递. 1. tf.Variable( ...

  5. tf.name_scope()和tf.variable_scope() (转)

    网络层中变量存在两个问题: 随着层数的增多,导致变量名的增多: 在调用函数的时候,会重复生成变量,但他们存储的都是一样的变量.   tf.variable不能解决这个问题. 变量作用域使用tf.var ...

  6. 彻底弄懂tf.Variable、tf.get_variable、tf.variable_scope以及tf.name_scope异同

    https://blog.csdn.net/qq_22522663/article/details/78729029 1. tf.Variable与tf.get_variabletensorflow提 ...

  7. Tensorflow函数——tf.variable_scope()

    Tensorflow函数——tf.variable_scope()详解 https://blog.csdn.net/yuan0061/article/details/80576703 2018年06月 ...

  8. TensorFlow基础笔记(13) tf.name_scope tf.variable_scope学习

    转载http://blog.csdn.net/jerr__y/article/details/60877873 1. 首先看看比较简单的 tf.name_scope(‘scope_name’). tf ...

  9. tensorflow中共享变量 tf.get_variable 和命名空间 tf.variable_scope

    tensorflow中有很多需要变量共享的场合,比如在多个GPU上训练网络时网络参数和训练数据就需要共享. tf通过 tf.get_variable() 可以建立或者获取一个共享的变量. tf.get ...

随机推荐

  1. Kibana将语言设置为中文

    6.7以后系统开始支持中文了,修改语言只需要添加一行配置即可. 设置方法 在kibana.yml配置文件中添加一行配置 i18n.locale: "zh-CN" 修改后重启,可以看 ...

  2. Java 1.8 Stream 用例测试

    package stream; import model.Student; import org.junit.jupiter.api.Test; import java.util.*; import ...

  3. Django创建对象的create和save方法

    Django的模型(Model)的本质是类,并不是一个具体的对象(Object).当你设计好模型后,你就可以对Model进行实例化从而创建一个一个具体的对象.Django对于创建对象提供了2种不同的s ...

  4. BootstrapValidator实现注册校验和登录错误提示效果(转)

    使用BootstrapValidator进行注册校验和登录错误提示,具体内容如下 1.介绍 在AdminEAP框架中,使用了BootstrapValidator校验框架,本文以注册校验的用户名.登录名 ...

  5. Hashkell 第一篇

    心情极差.................. 无事可做,其实是没心情去做事情,只好又翻起了haskell入门 记下几点,以备查询: 1. 函数名首字符是不可以大写的, 而且名称中可以有单引号,这也是合 ...

  6. PyCharm 头文件设置及作用

    PyCharm 头文件 设置 进入File --->settings---->Editor---->File and Code Templates----->Python Sc ...

  7. 【JZOJ4782】【NOIP2016提高A组模拟9.15】Math

    题目描述 输入 输出 样例输入 3 5 样例输出 -1 数据范围 解法 观察式子,可以得知整个式子与d(i*j)的奇偶性有关. d(n)为奇数当且仅当n是完全平方数. 对于一个i,如果d(i*j) ( ...

  8. 如何在Liferay 7中创建一个简单的JSF Portlet

    这个将在Liferay IDE 3.1 M3的发布版中提供创建的选项,但是你也可以通过命令行来创建. 1.这是Liferay JSF团队的官网:http://liferayfaces.org/ 你能在 ...

  9. Hdu 2522 hash

    题目链接 题意:输入整数n (1<= abs(n) <= 10^5) , 输出 1/n. 这题不是自己做出来的...看了网上的思路.这种题目都能想到用hash..反正我是没往那里想,看到循 ...

  10. 在IDEA中实战Git 合并&提交&切换&创建分支

    工作中多人使用版本控制软件协作开发,常见的应用场景归纳如下: 假设小组中有两个人,组长小张,组员小袁 场景一:小张创建项目并提交到远程Git仓库 场景二:小袁从远程Git仓库上获取项目源码 场景三:小 ...