tensorflow的变量命名空间问题

tf.get_variable 和tf.Variable不同的一点是,前者拥有一个变量检查机制,会检测已经存在的变量是否设置为共享变量,如果已经存在的变量没有设置为共享变量,TensorFlow 运行到第二个拥有相同名字的变量的时候,就会报错。后者会直接复制生成一个新变量。

import tensorflow as tf 

with tf.variable_scope('a_1'):
    a = tf.Variable(1, name='a')
    b = tf.Variable(1, name='a')
    print(a.name) # a_1/a:0
    print(b.name) # a_1/a_1:0 

    c = tf.get_variable('a', 1) 
    print(c.name) # a_1/a_2:0
    d = tf.get_variable('a', 1) 
    print(d.name) # ValueError: Variable a_1/a already exists, disallowed. 
                  #Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

为了解决上述问题,TensorFlow 又提出了 tf.variable_scope 函数:它的主要作用是,在一个作用域 scope 内共享一些变量,可以使用reuse重用变量。

import tensorflow as tf 

with tf.variable_scope("a_1"):
    a = tf.get_variable("v", [1])
    print(a.name) # a_1/v:0

with tf.variable_scope("a_1", reuse = True): #注意reuse的作用。
    c = tf.get_variable("v", [1]) 
    print(c.name) # a_1/v:0

print(a is c) # True, 两个变量重用了,变量地址一致

对于tf.name_scope来说,tf.name_scope 只能管住tf.get_variable函数操作 Ops 的名字,而管不住变量 Variables 的名字,但是他可以管住tf.Variable创建的变量,看下例:

import tensorflow as tf 

with tf.name_scope('a_1'):
    with tf.name_scope('a_2'):
        with tf.variable_scope('a_3'):
            d = tf.Variable(1, name='d')
            d_1 = tf.Variable(1, name='d')
            d_get = tf.get_variable('d', 1)
            x = 1.0 + d_get
            print(d.name)    #输出a_1/a_2/a_3/d:0
            print(d_1.name) #输出a_1/a_2/a_3/d_1:0
            print(d_get.name) #输出a_3/d:0
            print(x.name) # 输出a_1/a_2/a_3/add:0

        with tf.variable_scope('a_3'):
            e = tf.Variable(1, name='d')
            print(e.name)    #输出a_1/a_2/a_3_1/d:0

参考:1.https://blog.csdn.net/legend_hua/article/details/78875625

   2.https://www.cnblogs.com/Charles-Wan/p/6200446.html