Tensorflow变量作用域tf.variable_scope()

开始之前先了解一下Tensorflow的变量,有两种方式创建变量
1)tf.get_variable(name, shape, initializer): 获取已有变量,如果不存在,就创建一个
name: 变量的名字
shape: 变量的形状/维度
initializer: 变量的初始化方式,初始化方式有以下几种

  • tf.constant_initializer:常量初始化函数 tf.random_normal_initializer:正态分布
  • tf.truncated_normal_initializer:截取的正态分布
  • tf.random_uniform_initializer:均匀分布 tf.zeros_initializer:全部是0
  • tf.ones_initializer:全是1
  • tf.uniform_unit_scaling_initializer:满足均匀分布,但不影响输出数量级的随机值

该函数的使用:正常来讲,不同的变量不能有相同的名字,所以为了实现变量共享,tensorflow使用tf.get_variable联合tf.variable_scope以及reuse共同实现。

2)tf.Variable(initializer,name)
initializer: 初始化值
name:可自定义的变量名称
生成一个初始值为initial-value的变量。必须指定初始化值

tf.variable_scope的使用
with tf.variable_scope(“one”):
v1 = tf.get_variable(“v”, [1])
with tf.variable_scope(“one”, reuse = True):
v2 = tf.get_variable(“v”, [1])
assert v1 == v2 #如果没有reuse= true会报错,提示变量已经存在
v3 = tf.Variable(0, name=“v”,expected_shape = [1])
assert v2 == v3 #error
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(v2.name) #one/v:0
print(v3.name) #one_1/v:0
assert v2==v3 #error

注意点:1.如果在一个开启的作用域里使用预先定义的作用域,会跳过当前的作用域,保持预先存在的作用域不变
with tf.variable_scope(“foo”) as foo_scope:
assert foo_scope.name == “foo”
with tf.variable_scope(“bar”)
with tf.variable_scope(“baz”) as other_scope: #相对于bar缩放
assert other_scope.name == “bar/baz”
with tf.variable_scope(foo_scope) as foo_scope2:#相对于other_scope缩放
assert foo_scope2.name == “foo” # 保持不变

tf.variable_scope()对变量,操作均有效,如fooz作用域下的一个操作
x = 1.0 + v #x.op.name = foo/add

tf.name_scope()的使用
对操作tf.Variable()建立的变量有效,但对tf.get_variable()建立的变量无效,如例子:
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
assert v.name == “foo/v:0”
assert b.name == “foo/bar/b:0”
assert x.op.name == “foo/bar/add”

tf.name_scope()返回的是一个字符串,如上述的"bar" 。name_scope 对用
get_variable()创建的变量的名字不会有任何影响,而Variable()创建的操作会被加上前缀,并且会给操作加上名字前缀。

你可能感兴趣的:(tensorflow)