https://blog.csdn.net/baimafujinji/article/details/50485557
http://jermmy.xyz/2017/08/25/2017-8-25-learn-tensorflow-shared-variables/
https://www.tensorflow.org/programmers_guide/variables?hl=zh-cn
文章来源于对以上三个链接的学习总结。
可能会有认识有误的地方,请多多指教。
本文主要解决以下三个问题?
1. 什么是变量共享?
2. 什么情况下需要变量共享?
变量共享包括两个阶段:
(1)在定义函数或者方法的时候,将前面已经定义的变量(或者函数)在下文中重复使用。例如,在cnn的定义中卷积层需要使用多次,那么卷积层的weights和biases将重复使用多次。此时,共用多次变量的行为称作变量共享。
(2)在定义好模型之后,需要调用多次。此时需要再次共享变量。
3. 如何使用变量共享机制(两个tensorflow中的API:tf.get_variable()和tf.variable_scope())?
首先,先看一段代码。
def conv_relu(input, kernel_shape, bias_shape):
# Create variable named "weights".
weights = tf.get_variable("weights", kernel_shape, initializer=tf.random_normal_initializer())
# Create variable named "biases"
biases = tf.get_variable("biases", bias_shape, initializer=tf.constant_initializer(0.0))
conv = tf.nn.conv2d(input, weights, strides=[1,1,1,1], padding='SAME')
return tf.nn.relu(conv + biases)
在现实模型中,我们需要很多此类卷积层,如果每一层都重新定义weights和biases(不可以重名),将会使得代码冗余。
并且,重复调用此函数将不起作用(报错)。
input1 = tf.random_normal([1,10,10,32])
input2 = tf.random_normao([1,20,20,32])
x = conv_relu(input1, kernel_shape=[5,5,32,32], bias_shape=[32])
x = conv_relu(x, kernel_shape=[5,5,32,32], bias_shape=[32]) # This fail
由于tensorflow不知道下面是创建新变量还是使用原来的变量 ,所有会报错。不过,在不同的作用域中调用conv_relu()
可表明我们想要创建新的变量。
def my_image_filter(input_images):
with tf.variable_scope("conv1"):
# Variables created here will be named "conv1/weights","conv1/biases".
relu1 = conv_relu(input_images, [5,5,32,32], [32])
with tf.variable_scope("conv2"):
# Variables created here will be named "conv2/weights", "conv2/biases"
return conv_relu (relu1, [5,5,32,32], [32])
如果,你想要共享变量的话,有两种方法可供选择。首先,你可以使用reuse=True创建具有相同名称的作用域:
with tf.variable_scope("model"):
output1 = my_image_filter(input1)
with tf.variable_scope("model", reuse=True):
output2 = my_image_filter(input2)
你也可以调用scope.reuse_variables()以触发 重用:
with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
scope.reuse_variables()
output2 = my_image_filter(input2)
由于,依赖作用域的确切字符串名称可能比较危险,因此也可以根据另一作用域初始化某个变量作用域:
with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
with tf.variable_scope(scope, reuse=True):
output2 = my_image_filter(input2)