tf.variable_scope

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])

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值