参考
《TensorFlow实战Google深度学习框架》
代码
在定义神经网络参数时,第一层的权重已经叫weights了,第二层网络的参数名如果也叫weights,就会触发变量重用的错误。为了命名的规范性,需要通过上下文管理器来统一命名生成的变量。
with tf.variable_scope("foo"):
v = tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))
因为在命名空间foo中已经存在名字为v的变量,下面代码将会报错
with tf.variable_scope("foo"):
v = tf.get_variable("v",[1])
将参数reuse设置为True,这样函数将直接获得已经声明的变量
with tf.variable_scope("foo",reuse=True):
v1 = tf.get_variable("v",[1])
print v==v1
参数reuse设置为True时,只能获取已经创建的变量。因为命名空间bar中还没创建v,所以会报错
with tf.variable_scope("bar",reuse=True):
v = tf.get_variable("v",[1])
管理变量名称
with tf.variable_scope("foo"):
v2 = tf.get_variable("v",[1])
print v2.name #输出foo/v:0