tensorflow tf.Variable、tf.get_variable机制

本文探讨了TensorFlow中变量的生命周期、命名机制、作用域以及权重共享。在不同的scope内可以使用相同变量名,变量在初始化后直至session关闭一直存在。通过tf.get_variable实现权重共享,name_scope不支持重名,而variable_scope会添加到变量全局名称中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里涉及到了两个概念,一个是tf.variable_scope一个是tensorflow中变量的名字。

tensorflow中变量是有名字的,就像是我们用tensorboard绘制graph的时候,每个节点都有名字一样。即使没有手动赋予的变量也会有默认的名字。这个名字可以用变量的name方法来获得,或者是直接打印这个结点,就会显示其名字。

>>> a = tf.constant(1)
>>> a.name
'Const:0'

>>> a = tf.get_variable('v',[1],initializer=tf.constant_initializer(1.0))
>>> a
<tf.Variable 'v:0' shape=(1,) dtype=float32_ref>

>>> a = tf.Variable(tf.constant(1.0,shape=[1]))
>>> a
<tf.Variable 'Variable_1:0' shape=(1,) dtype=float32_ref>

不同scope可以使用相同的名字

tf.variable_scopetf.name_scope,就是给出互不影响的名字的范围。比如说在两个tf.variable_scope中,我们可以有两个相同名字的变量。在下面例子中,两个变量都叫Variable:0。当然,能够区分它们的原因也很简单,因为他们名字前加上了variable_scope的名称。

>>> with tf.variable_scope('V1'):
...     a = tf.Variable(tf.constant(1.0,shape=[1]))
...
>>> a
<tf.Variable 'V1_1/Variable:0' shape=(1,) dtype=float32_ref>
>>> with tf.variable_scope('V2'):
...     b = tf.Variable(tf.constant(1.0,shape=[1]))
..
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值