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()