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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM