这里涉及到了两个概念,一个是tf.variable_scope
一个是tensorflow中变量的名字。
tensorflow中变量是有名字的,就像是我们用tensorboard绘制graph的时候,每个节点都有名字一样。即使没有手动赋予的变量也会有默认的名字。这个名字可以用变量的name
方法来获得,或者是直接打印这个结点,就会显示其名字。
>>> a = tf.constant(1)
>>> a.name
'Const:0'
>>> a = tf.get_variable('v',[1],initializer=tf.constant_initializer(1.0))
>>> a
<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>
>>> a = tf.Variable(tf.constant(1.0,shape=[1]))
>>> a
<tf.Variable 'Variable_1:0' shape=(1,) dtype=float32_ref>
不同scope可以使用相同的名字
而tf.variable_scope
和tf.name_scope
,就是给出互不影响的名字的范围。比如说在两个tf.variable_scope
中,我们可以有两个相同名字的变量。在下面例子中,两个变量都叫Variable:0。当然,能够区分它们的原因也很简单,因为他们名字前加上了variable_scope的名称。
>>> with tf.variable_scope('V1'):
... a = tf.Variable(tf.constant(1.0,shape=[1]))
...
>>> a
<tf.Variable 'V1_1/Variable:0' shape=(1,) dtype=float32_ref>
>>> with tf.variable_scope('V2'):
... b = tf.Variable(tf.constant(1.0,shape=[1]))
..