1. 程式人生 > >TensorFlow中get_variable共享變數呼叫

TensorFlow中get_variable共享變數呼叫

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