tf.variable_scope VS tf.name_scope

本文以tf1.13版本中tf.variable_scope类和tf.name_scope为例,介绍相应类的初始化。

  def __init__(self,
               name_or_scope,       #名称或VariableScope,用作当前范围内op函数的name前缀
               default_name=None,   #name_or_scope不指定时的默认名称,全局唯一;指定name_or_scope时该变量无效,多次访问时,自动在默认名称后加_[1,2,...]
               values=None,         #输入参数列表(op的输入)
               initializer=None,    #当前scope(空间)内的所有变量的默认初始值
               regularizer=None,    #当前scope内所有变量的默认正则化值
               caching_device=None, #当前scope内所有变量的默认缓冲设备
               partitioner=None,    #当前scope内所有变量的分区 
               custom_getter=None,
               reuse=None,          #变量是否复用标志位,`True`, None, or tf.AUTO_REUSE三个值,True表示在当前空间及其子空间复用该变量, tf.AUTO_REUSE变量不存在时重建,存在时直接去之前的值;None时继承父空间的reuse标志位的值
               dtype=None,          #变量数据类型
               use_resource=None,   #标志位,False表示正则化变量,True表示使用定制好的变量
               constraint=None,
               auxiliary_name_scope=True): #标志位,False表示不使用别名,True表示创建别名或空间,
def __init__(self, 
            name,               #类空间名称,用作当前范围内op函数的name前缀
            default_name=None,  #name=None时的默认名称
            values=None):       #输入参数列表(op的输入)

这两个类函数常用来限制tf.Variabletf.get_variable类的使用范围。其中前者的基类为Variable,后者的基类为VariableScope。

  • tf.Variable和tf.get_variable
 tf.Variabletf.get_variable
name受tf.name_variable和tf.variable_scope双重影响仅受tf.variable_scope影响
重复创建时

初次创建时为本名;

重复创建时在名称后加重复次数${name}_${重复数,从1开始递增}

初次创建时,变量名不存在时直接创建,若设置reuse=True则报错,可以使用tf.AUTO_REUSE;

重复创建时,需要指定变量reuse标志位为True或tf.AUTO_REUSE

import tensorflow as tf
in_1=1
in_2=2
name=None
name='foo'

v1 = tf.get_variable('foo/var1', [1])  #若注释改行,则tf.variable_scope的reuse=tf.AUTO_REUSE,不设置或置为True均报错
for idx in range(2):
    with tf.variable_scope(name, 'V0', [in_1, in_2]) as scope:
        with tf.name_scope("bar"):
            scope.reuse_variables()  #仅当变量名已经存在时有效,即配合v1 = tf.get_variable('foo/var1', [1])使用
            #tf.get_variable_scope().reuse_variables() #仅当变量名存在时有效
            v1 = tf.get_variable("var1", [1])
            v2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
            v3 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)

    with tf.Session() as sess:
        print('##ID: {}##'.format(idx))
        print('v1 name: {}'.format(v1.name))
        print('v2 name: {}'.format(v2.name))
        print('v3 name: {}'.format(v3.name))


结果如下:
##ID: 0##
v1 name: foo/var1:0      #tf.get_variable的变量名仅依赖于tf.variable_scope作为前缀
v2 name: foo/bar/var2:0  #tf.Variable的变量名依赖于tf.variable_scope和tf.name_scope
v3 name: foo/bar/var2_1:0  #当前变量空间内重名时,名称自动改变,保持全局唯一
##ID: 1##
v1 name: foo/var1:0        #设置scope.reuse_variables(),故直接从已有变量中获得
v2 name: foo_1/bar/var2:0  #tf.Variable的变量空间重名时,名称自动改变成名称加后缀下划线和重复次数
v3 name: foo_1/bar/var2_1:0
  • arg_scope 参数空间为tf.contrib模块独有的函数,用于表示该函数模块内的所有op或scope具有相同的参数。函数参数如下:
def arg_scope(list_ops_or_scope,   #函数或空间集
             **kwargs              #参数的键值对
              ):

inception_v1结构中出现该函数。

  with variable_scope.variable_scope(scope, 'InceptionV1', [inputs]):
    with arg_scope(
        [layers.conv2d, layers_lib.fully_connected],
        weights_initializer=trunc_normal(0.01)):
      with arg_scope(
          [layers.conv2d, layers_lib.max_pool2d], stride=1, padding='SAME'):
        end_point = 'Conv2d_1a_7x7'
        net = layers.conv2d(inputs, 64, [7, 7], stride=2, scope=end_point)

参考文献:

  1. variable_scope.py
  2. TensorFlow函数:tf.variable_scope

  3. TensorFlow构建图形:tf.name_scope函数

  4. arg_scope.py

  5. inception_v1.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值