一、两种scope:variable与name
tf.variable_scope()是对变量进行命名管理,而tf.name_scope()是对算子(op)进行命名管理,二者相互不影响。见下例:
import tensorflow as tf
for i in range(10):
with tf.name_scope('test'):
a = tf.constant([1])
b = tf.constant([1])
c = a + b
with tf.variable_scope("foo",reuse=True): # 设定为重用模式,
v = tf.get_variable("v", [1])
v1 = tf.get_variable("v", [1])
print(v)
print(v1)
assert v is v1
print(c)
结果中算子c的名称会随着循环的增加而改变:"test_1_2_..._9/add:0"。而v和v1两个变量始终都是'foo/v:0'。
二、variable_scope的reuse方法
如果需要同一个参数参与不同的运算,可以使用reuse构建不同的指针指向相同的variable。例如在tf中想在多GPU上进行并行计算,需要使用reuse完成模型的复制。
import tensorflow as tf
with tf.variable_scope("foo",reuse=False): # 只有在false下才能新增变量
v = tf.get_variable("v", [1]) # 创建新变量
tf.get_variable_scope().reuse_variables() # 开启reuse模式,不能够再新建变量
v1 = tf.get_variable("v", [1]) # 自动reuse变量v
print(v)
print(v1)
assert v is v1
for i in range(10):
with tf.variable_scope("foo",reuse=True): # 开启reuse模式
v = tf.get_variable("v", [1]) # 自动reuse变量v
print(v)
最终结果:全为'foo/v:0'
官方示例:
import tensorflow as tf
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
注:可以在后续对scope的reuse模式进行改变,从而新增变量。reuse的本质是为创建好的variable添加指针。
参考内容:
https://www.jianshu.com/p/ab0d38725f88
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)