举例说明
当我们创建两层卷积的过滤器时,每输入一次图片都要创建一次过滤器变量()但我们更希望所有图片都共享同一过滤器变量。通常的做法是:1.创建这些变量的全局变量,但是这样会打破封装性。2.将模型封装成类。
tensorflow提供了variable scope这种方式来共享变量,其主要涉及到两个函数
tf.get_variable(<name>, <shape>, <initializer>) //创建或返回给定名称的变量
tf.variable_scope(<scope_name>) //管理传给get_variable()的变量名称的作用域
例如下边的语句创建了一个的变量
wgight = tf.get_variable('weight',kernel_shape,
initializer=tf.random_normal_initializer())
但是我们需要两个卷积层,这时可以通过tf.variable_scope()指定作用域进行区分
with tf.variable_scope('conv1')
...
with tf.variable_scope('conv2')
最后在image_filters这个作用域重复使用第一张图片输入时创建的变量,调用函数reuse_variables(),代码如下:
with tf.variable_scope("image_filters") as scope:
...
scope.reuse_variables()
</