想要清楚variable_scope和name_scope的區別。你只需要:
搞清楚 tf.Variable() 和 tf.get_variable()
tf.Variable() 其實本質是 tf.Variable.__init__() , 永遠都是用于創建variable的
而 tf.get_variable() 是查看指定name的variable存在與否,存在則復用,不存在則創建。
兩者的另一個區別在于,get_variable不受name_scope 的影響。
但是兩者都受 variable_scope的影響。
get_variable的用于有倆
1 復用一個Variable
tf.get_variable_scope().reuse == True
2 防止重名Variable
tf.get_variable_scope().reuse == False
import tensorflow as tf
v = tf.Variable( [2,2,3,32],name='weights')
with tf.variable_scope('variable_scope'):
v1 = tf.get_variable('weights', [2,2,3,32])
with tf.name_scope('name_scope'):
v2 = tf.get_variable('weights',[2,2,3,32])
print v.name
print v1.name
print v2.name
輸出結果如下:
weights:0
variable_scope/weights:0
weights_1:0
注意,如果用的是Variable() 是允許同名的,他會自動給你加上下劃線并且編號,但是weights和weights_1并不是相同的變量
但是如果改成get_variable 則需要設置 reuse,設置完了以后才能確定是允不允許復用,一旦允許復用,同名的就是同變量。
PS.在調用variable_scope()的時候,會自動調用name_scope().
所以一句話,總結就是get_variable 可以不受 name_scope()的約束
其他情況都會在Variable的name之前都會加上scope的name。