一、由來
深度學習中需要使用大量的變量集,以往寫代碼我們只需要做全局限量就可以了,但在tensorflow中,這樣做既不方便管理變量集,有不便於封裝,因此tensorflow提供了一種變量管理方法:變量作用域機制
二、兩個重要API
tf.get_variable(name, shape=None) # 根據給定的名字創建或返回一個變量
tf.variable_scope(name_or_scope, reuse=None) # 將name_or_scope下的所有變量組成一個命名空間
三、解讀
先說第一個API
tf.get_variable(name, shape=None)這個方法在建立變量時與tf.Variable()完全相同,區別在於它還會搜索是否有同名變量;
1 import tensorflow as tf 2 3 4 with tf.variable_scope('const'): 5 a = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.))
再說第二個API
這個方法最重要的參數時reuse,有三個取值:None、True、tf.AUTO_REUSE
reuse = None:繼承父類的reuse標志
reuse = True:只能復用,不能創建
1 import tensorflow as tf 2 3 4 with tf.variable_scope('const'): 5 a = tf.get_variable('a', [1]) 6 7 with tf.variable_scope('const', reuse=tf.AUTO_REUSE): 8 b = tf.get_variable('a', [1]) 9 10 print(a==b) # True
reuse = tf.AUTO_REUSE:沒有就創建,有了就復用,這是最安全的用法
1 import tensorflow as tf 2 3 4 def test(): 5 with tf.variable_scope('const', reuse=tf.AUTO_REUSE): 6 a = tf.get_variable('a', [1]) 7 8 return a 9 10 x = test() # 沒有就創建 11 y = test() # 有了就復用 12 print(x==y) # True