tf.variable_scope 参数
最近在看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 参数的更多相关文章
- 深度学习原理与框架-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 ... 
- tf.variable和tf.get_Variable以及tf.name_scope和tf.variable_scope的区别
		在训练深度网络时,为了减少需要训练参数的个数(比如具有simase结构的LSTM模型).或是多机多卡并行化训练大数据大模型(比如数据并行化)等情况时,往往需要共享变量.另外一方面是当一个深度学习模型变 ... 
- TF.VARIABLE、TF.GET_VARIABLE、TF.VARIABLE_SCOPE以及TF.NAME_SCOPE关系
		1. tf.Variable与tf.get_variable tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要 ... 
- 理解 tf.Variable、tf.get_variable以及范围命名方法tf.variable_scope、tf.name_scope
		tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要将变量通过参数的形式到处传递. 1. tf.Variable( ... 
- tf.name_scope()和tf.variable_scope()  (转)
		网络层中变量存在两个问题: 随着层数的增多,导致变量名的增多: 在调用函数的时候,会重复生成变量,但他们存储的都是一样的变量. tf.variable不能解决这个问题. 变量作用域使用tf.var ... 
- 彻底弄懂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提 ... 
- Tensorflow函数——tf.variable_scope()
		Tensorflow函数——tf.variable_scope()详解 https://blog.csdn.net/yuan0061/article/details/80576703 2018年06月 ... 
- TensorFlow基础笔记(13)  tf.name_scope tf.variable_scope学习
		转载http://blog.csdn.net/jerr__y/article/details/60877873 1. 首先看看比较简单的 tf.name_scope(‘scope_name’). tf ... 
- tensorflow中共享变量 tf.get_variable 和命名空间 tf.variable_scope
		tensorflow中有很多需要变量共享的场合,比如在多个GPU上训练网络时网络参数和训练数据就需要共享. tf通过 tf.get_variable() 可以建立或者获取一个共享的变量. tf.get ... 
随机推荐
- 从0开始学习 GitHub 系列之「03.Git 速成」
			前面的 GitHub 系列文章介绍过,GitHub 是基于 Git 的,所以也就意味着 Git 是基础,如果你不会 Git ,那么接下来你完全继续不下去,所以今天的教程就来说说 Git ,当然关于 G ... 
- linux开发脚本自动部署及监控
			linux开发脚本自动部署及监控 开发脚本自动部署及监控一.编写脚本自动部署反向代理.web.nfs:要求:1.部署nginx反向代理三个web服务,调度算法使用加权轮询: #!/bin/sh ngx ... 
- Vue. 之 Element获取table中选中的行
			Vue. 之 Element获取table中选中的行 问题描述: 如下截图,在Table中选择数据后,然后在点击“统计”按钮,获取Table表中选择的行 解决方案: 1. 给“统计”这个按钮添加一个点 ... 
- 地不安装Oracle,plsql远程连接数据库
			由于Oracle的庞大,有时候我们需要在只安装Oracle客户端如plsql.toad等的情况下去连接远程数据库,可是没有安装Oracle就没有一切的配置文件去支持.最后终于发现一个很有效的方法,Or ... 
- 【水滴石穿】FirstReactNativeProject
			这个是一个小demo,项目地址为https://github.com/prsioner/FirstReactNativeProject 有注册,忘记密码还有登陆,应该是用到了react-navigat ... 
- 关于 SSD 的接口和相关名词(2019-09-10)
			关于 SSD 的接口和相关名词 了解了很多天的 SSD,太多的名词. 先记录一下. SATA MSATA M2 NVME NGFF U2 TODO: 后续收集相关信息. 
- sql函数的使用——转换函数
			转换函数用于将数据类型从一种转为另外一种,在某些情况下,oracle server允许值的数据类型和实际的不一样,这时oracle server会隐含的转化数据类型,比如: create table ... 
- 记一次Celery的仇
			背景:项目在公司的一台虚拟机上运行(32核+32G).其他人的项目也在这台物理机上运行..我的训练代码是单进程的,跑完一次需要大约10h(数据量大逮着一个核使劲跑..):训练是一个Celery定时任务 ... 
- hdu 1054 【树形dp】
			http://acm.hdu.edu.cn/showproblem.php?pid=1054 给定一棵树,点能看住与其相连的边,问最少需要选定多少个点看住所有的边. 定义dp[maxn][2],dp[ ... 
- 线段树动态开点+树链剖分BZOJ4999
			以每个一个颜色开一颗线段树,内部以dfs序作为线段树节点,权值代表出现次数,维护线段树区间和 #include<iostream> #include<stdio.h> #inc ... 
