栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

tf.variable

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

tf.variable

TensorFlow中的变量一般就是模型的参数。当模型复杂的时候共享变量会无比复杂。

例如,当创建两层conv过滤器时,每输入一批数据就会创建一次过滤器对应的变量,但是我们希望所有图片都共享同一过滤器变量,因此共有4个变量conv1_weights,conv1_biases,conv2_weights, conv2_biases。

通常的做法是将这些变量设置为全局变量 或 将模型封装成类。

不过TensorFlow提供了Variable Scope 这种独特的机制来共享变量。这个机制涉及两个主要函数:

tf.variable_scope('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()指定作用域进行区分,如                  with tf.variable_scope(“conv1”)这行代码指定了第一个卷积层作用域为conv1,在这个作用域下有两个变量weights和biases。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005407.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号