您的位置:首页 > 运维架构

Notes on tensorflow(六)variable_scope

2017-04-28 13:33 417 查看
https://www.tensorflow.org/programmers_guide/variable_scope

Scope与Share机制

tensorflow 引入了namespace机制, 也就是scope, 可以方便地命名、共享变量. 当需要共享变量时, 创建变量使用
tf.get_variable
方法而不是
tf.Variable
.

import tensorflow as tf
with tf.variable_scope('foo'):
v1 = tf.get_variable('v1', [1])
print v1.name
with tf.variable_scope('foo', reuse = True):
v2 = tf.get_variable('v1')
#v3 = tf.get_variable('v3', [3]) 会报错
print v2.name

assert v2 is v1


foo/v1:0
foo/v1:0


一个scope对应一个namespace,当在scope里创建任意有name的东西时, 它的name为:
scope_name/var_name


reuse = True
不可少。它是
variable_scope
的一个属性, 直接决定如何创建变量。

reuse = False
时, 先检查是否已经存在相同name的Variable, 如果有, 报错。然后以对应name创建一个新的Variable

reuse = True
时,不会创建新的Variable。直接查找自己name对应的variable, 如果没有, 则报错。

reuse
属性可继承:在
reuse = True
的scope里创建子scope时, 子scope的
reuse==True


import tensorflow as tf
with tf.variable_scope('foo', reuse = True) as foo:
print foo.reuse
with tf.variable_scope('doo') as doo:
print doo.reuse


True
True


variable_scope与name_scope

它们在效果上的区别是
variable_scope
会影响它内部创建的所有有name属性的节点, 但
name_scope
只影响Operator节点的命名。 用处之一是在多gpu训练时在不同的device上, 使用相同的
variable_scope
, 但使用不同的
namescope


import tensorflow as tf
with tf.variable_scope('foo'):
with tf.name_scope('ns'):
a = tf.get_variable('a', [1])
b = a + 1;
print a.name
print b.name
print b.op.name


foo/a:0
foo_2/ns/add:0
foo_2/ns/add


为variable_scope指定默认的initializer

为variable_scope指定默认initializer的好处是不用在每次调用创建变量的方法时传入初始值了。它也是可以继承的。

import tensorflow as tf
def show(v):
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print v.eval()

with tf.variable_scope('foo', initializer = tf.constant_initializer(0.2)):
cv1 = tf.get_variable('cv1', [1])
show(cv1)

with tf.variable_scope('sub_foo'):
cv2 = tf.get_variable('cv2', [1])
show(cv2)

with tf.variable_scope('sub_sub_foo', initializer = tf.constant_initializer(0.1)):
cv3 = tf.get_variable('cv3', [1])
show(cv3)


[ 0.2]
[ 0.2]
[ 0.1]



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tensorflow