tf.get_variable 和tf.Variable不一樣的一點是,前者擁有一個變量檢查機制,會檢測已經存在的變量是否設置爲共享變量,若是已經存在的變量沒有設置爲共享變量,TensorFlow 運行到第二個擁有相同名字的變量的時候,就會報錯。後者會直接複製生成一個新變量。html
import tensorflow as tf with tf.variable_scope('a_1'): a = tf.Variable(1, name='a') b = tf.Variable(1, name='a') print(a.name) # a_1/a:0 print(b.name) # a_1/a_1:0 c = tf.get_variable('a', 1) print(c.name) # a_1/a_2:0 d = tf.get_variable('a', 1) print(d.name) # ValueError: Variable a_1/a already exists, disallowed. #Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
爲了解決上述問題,TensorFlow 又提出了 tf.variable_scope 函數:它的主要做用是,在一個做用域 scope 內共享一些變量,可使用reuse重用變量。函數
import tensorflow as tf with tf.variable_scope("a_1"): a = tf.get_variable("v", [1]) print(a.name) # a_1/v:0 with tf.variable_scope("a_1", reuse = True): #注意reuse的做用。 c = tf.get_variable("v", [1]) print(c.name) # a_1/v:0 print(a is c) # True, 兩個變量重用了,變量地址一致
對於tf.name_scope來講,tf.name_scope 只能管住tf.get_variable函數操做 Ops 的名字,而管不住變量 Variables 的名字,可是他能夠管住tf.Variable建立的變量,看下例:spa
import tensorflow as tf with tf.name_scope('a_1'): with tf.name_scope('a_2'): with tf.variable_scope('a_3'): d = tf.Variable(1, name='d') d_1 = tf.Variable(1, name='d') d_get = tf.get_variable('d', 1) x = 1.0 + d_get print(d.name) #輸出a_1/a_2/a_3/d:0 print(d_1.name) #輸出a_1/a_2/a_3/d_1:0 print(d_get.name) #輸出a_3/d:0 print(x.name) # 輸出a_1/a_2/a_3/add:0 with tf.variable_scope('a_3'): e = tf.Variable(1, name='d') print(e.name) #輸出a_1/a_2/a_3_1/d:0
參考:1.https://blog.csdn.net/legend_hua/article/details/78875625 .net