Tensorflow学习笔记——变量作用域(variable scope)

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

官网给出过一个case,当创建两层卷积的过滤器时,每输入一个图片就会创建一次过滤器对应的变量,但是我们希望所有图片都共享同一过滤器变量,一共有4个变量:conv1_weights,conv1_biases,conv2_weights, and conv2_biases。
通常做法是将这些变量设置为全局变量。但是存在的问题是打破封装性,这些变量必须文档化被其它代码文件引用,一旦代码变化,调用方也可能需要变化。
还有一种保证封装性的方式是将模型封装成类。

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

tf.get_variable(<name>, <shape>, <initializer>) # 创建或返回给定名称的变量
tf.variable_scope(<scope_name>) # 管理传给get_variable()的变量名称的作用域

在下面的代码中,通过tf.get_variable()创建了名称分别为weights和biases的两个变量。

def conv_relu(input, kernel_shape, bias_shape):

	# creat variable named "weights"
	weights = tf.get_variable("weights", kernel_shape, initializer=tf.random_normal_initializer())
	
	# create variable named "bias"
	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和bias。

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

Reference:
https://www.cnblogs.com/MY0213/p/9208503.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值