import tensorflow as tf
with tf.variable_scope('v_scope',reuse=True) as scope1:
Weights1 = tf.get_variable('Weights', shape=[2,3])
bias1 = tf.get_variable('bias', shape=[3])
# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
Weights2 = tf.get_variable('Weights')
# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
Weights3 = tf.get_variable('Weights')
print (Weights1.name)
print (Weights2.name)
print (Weights3.name)
v_scope/Weights:0
v_scope/Weights:0
v_scope/Weights:0
可以看到三个变量指向的是同一个变量.
注意1:
variable_scope必须是同一个名为‘v_scope’,否则起不到共享变量的作用,会报
ValueError: Variable v_scope1/Weights does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?
注意2:
get_variable()变量必须已经定义过了,而且必须是通过get_variable()定义的,才能设置 reuse=True,否则会报错
Variable v_scope/bias does not exist, or was not created with tf.get_variable()