一、由来
深度学习中需要使用大量的变量集,以往写代码我们只需要做全局限量就可以了,但在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()完全相同,区别在于它还会搜索是否有同名变量;
import tensorflow as tf with tf.variable_scope('const'):
a = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.))
再说第二个API
这个方法最重要的参数时reuse,有三个取值:None、True、tf.AUTO_REUSE
reuse = None:继承父类的reuse标志
reuse = True:只能复用,不能创建
import tensorflow as tf with tf.variable_scope('const'):
a = tf.get_variable('a', [1]) with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
b = tf.get_variable('a', [1]) print(a==b) # True
reuse = tf.AUTO_REUSE:没有就创建,有了就复用,这是最安全的用法
import tensorflow as tf def test():
with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
a = tf.get_variable('a', [1]) return a x = test() # 没有就创建
y = test() # 有了就复用
print(x==y) # True