TensorFlow中的变量就是模型的参数,当模型复杂的时候变量也会很复杂。
例如,当创建两层conv时,每输入一批batchsize数据就会创建一次conv层的变量。我们希望所有数据都共享相同的模型变量,因此共有4个模型变量conv1_weights,conv1_biases,conv2_weights, conv2_biases。
通常的做法是将这些变量设置为全局变量 或 将模型封装成类。
TensorFlow提供了tf.variable_scope( )函数和tf.get_variable()来共享变量:
tf.variable_scope('scopename')#定义了一个图,所有变量都在图scopename内
tf.get_variable('variblename',dtype,shape,initializer)#返回变量
常规是将模型封装成类:
def conv_relu(input, kernel_shape, bias_shape):
weights = tf.get_variable("weights", kernel_shape,
initializer=tf.random_normal_initializer())
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)
当我们要用两个卷积层,这时可以通过tf.variable_scope()指定两层变量。‘conv1’内为第一层变量,其输出relu1被第二层‘conv2’共享。
def my_image_filter(input_images):
with tf.variable_scope("conv1"):
relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
with tf.variable_scope("conv2"):
return conv_relu(relu1, [5, 5, 32, 32], [32])