tensorflow入门:tf.name_scope,tf.variable_scope、变量共享

本文介绍了TensorFlow中tf.name_scope和tf.variable_scope的使用,探讨了它们如何与变量名前缀及变量共享相关联。在tf.name_scope中,传入字符串或name_scope对象影响变量名的前缀。而在tf.variable_scope中,配合get_variable,通过reuse参数实现变量的复用或创建。理解这些概念对于优化TensorFlow模型的组织和管理至关重要。

1. tf.name_scope('scope_name')或tf.name_scope(named_scope)

主要与tf.Variable搭配使用;

当传入字符串时,用以给变量名添加前缀,类似于目录,如case1所示;

当传入已存在的name_scope对象时,则其范围内变量的前缀只与当前传入的对象有关,与更上层的name_scope无关,如case2所示。

import tensorflow as tf

# case 1:
with tf.name_scope('l1'):
	with tf.name_scope('l2'):
		wgt1 = tf.Variable([1,2,3], name='wgts')
		bias1 = tf.Variable([0.1], name='biases')

print wgt1.name, bias1.name
# >>> l1/l2/wgts:0 l1/l2/biases:0

# case 2:
with tf.name_scope('l1') as l1_scp:
	with tf.name_scope('l2'):
		wgt0 = tf.Variable([1,2,3], name='wgts')
		bias0 = tf.Variable([0.1], name='biases')
		with tf.name_scope(l1_scp):
			wgt1 = tf.Variable([1,2,3], name='wgts')
			bias1 = tf.Variable([0.1], name='biases')

print wgt0.name, bias0.name, wgt1.name, bias1.name
# >>> l1_1/l2/wgts:0 l1_1/l2/biases:0 l1_1/wgts:0 l1_1/biases:0

2. tf.vari

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值