在TensorFlow中有两个作用域,一个是name_scope,另一个是variable_scope。variable_scope主要是给variable_name加前缀的,也给op_name加前缀;name_scope是给op_name加前缀。
1、variable_scope示例
variable_scope变量作用域机制在TensorFlow中主要由两部分组成:
v = tf.get_variable()#通过所给的名字创建或是返回一个变量
tf.variable_scope()#为变量指定命名空间
当reuse=False时,
with tf.variable_scope("foo") :
v = tf.get_variable("v",[1])
v2 = tf.get_variable("v",[1])
抛出错误,因为v这个变量已经被定义过了。
作用域可以共享变量:
with tf.variable_scope("foo") as scope:
v = tf.get_variable("v",[1])
with tf.variable_scope("foo",reuse=True) :
v1 = tf.get_variable("v",[1])
print(v1==v)
输出:True
1.获取变量作用域
#可以直接通过tf.variable_scope()来获取变量作用域
with tf.variable_scope("foo") as foo_scope:
v = tf.get_variable("v",[1])
with tf.variable_scope(foo_scope):
w = tf.get_variable("w",[1])
如果在开启的一个变量作用域里使用之前预先定义的一个作用域,则会跳过当前变量作用域,保持预先存在的作用域不变
with tf.variable_scope("foo") as foo_scope:
print(foo_scope.name)
with tf.variable_scope("bar") :
with tf.variable_scope("barz") as other_scope:
print(other_scope.name)
#如果在开启的一个变量作用域里使用之前预先定义的一个作用域,则会跳过当前变量的作用域,保持预先存在的作用域不变
with tf.variable_scope(foo_scope) as foo_scope2:
print(foo_scope2.name)#保持不变
输出:
foo
bar/barz
foo
2、name_scope示例
TesnsorFlow中常常会有数以千计的节点,在可视化的过程中很难一下子展示出来,因此用name_scope为变量划分范围,在可视化中,这表示在计算图中的一个层级。
with tf.name_scope('conv1') as scope:
w1 = tf.Variable([1], name='weights')
b1 = tf.Variable([0.3], name='bias')
with tf.name_scope('conv2') as scope:
w2 = tf.Variable([1], name='weights')
b2 = tf.Variable([0.3], name='bias')
print (w1.name)
print (w2.name)
print (b1.name)
print (b2.name)
输出:
conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0
name_scope会影响op_name,不会影响用get_variable()创建的变量,而会影响通过Variable()创建的变量。
import tensorflow as tf
with tf.variable_scope("foo") :
with tf.name_scope("bar"):
v = tf.get_variable("v",[1])
b = tf.Variable(tf.zeros([1]),name='b')
x = 1.0 + v
print(v.name)
print(b.name)
print(x.op.name)
输出:
foo/v:0
foo/bar/b:0
foo/bar/add
可以看出,name_scope对用get_variable创建的变量的名字不会有任何影响,而Variable创建的操作会被加上前缀,并且会给操作加上名字前缀。