TensorFlow之tf.Variable_scope、tf.Variable以及tf.get_Variable

博客介绍了TensorFlow中变量创建和命名空间管理机制。TensorFlow可通过变量名创建或获取变量,主要由tf.get_variable和tf.variable_scope实现,也可用tf.Variable创建。tf.get_variable和tf.Variable有区别,前者必须指定变量名。同时说明了tf.variable_scope中reuse的使用规则及对变量命名空间的管理。

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

https://www.cnblogs.com/MY0213/p/9270864.html
https://blog.youkuaiyun.com/brucewong0516/article/details/78788772

1、tf.variable与tf.get_variable

tensorflow提供了通过变量名称来创建或者获取一个变量的机制,通过变量名获取变量的机制主要是通过tf.get_variable和tf.variable_scope实现的。当然,变量也可以通过tf.Varivale来创建。当tf.get_variable用于变量创建时,和tf.Variable的功能基本等价

#以下两个定义是等价的
v = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer(1.0))
v = tf.Variable(tf.constant(1.0, shape=[1], name='v')

tf.get_varialbe和tf.Variable最大的区别在于:tf.Variable的变量名是一个可选项,通过name=’v’的形式给出。但是tf.get_variable必须指定变量名。

2、tf.get_variable与tf.variable_scope

TensorFlow中通过变量名获取变量的机制主要是通过tf.get_variable和tf.variable_scope实现的。关键是reuse问题,这里只要记住:当reuse为False或者None时(这也是默认值),同一个tf.variable_scope下面的变量名不能相同;当reuse为True时,tf.variable_scope只能获取已经创建过的变量。
示例代码:

#reuse=False时会报错的情况:
with tf.variable_scope('foo'):
    v = tf.get_variable('v',[1],initializer=tf.constant_initializer(1.0))
 
with tf.variable_scope('foo'):
    v1 = tf.get_variable('v',[1])

在这种情况下会报错:Variable foo/v already exists, disallowed.Did you mean to set reuse=True in Varscope?
其原因就是在命名空间foo中创建了相同的变量。如果要在foo下创建一个变量v1,其name=‘v’,只需要将reuse设置为Ture就ok了。将上面第二部分代码修改为:

with tf.variable_scope('foo', reuse=True):
    v1 = tf.get_variable('v',[1])
    print(v1.name)      #结果为foo/v

tf.variable_scope函数生成的上下文管理器也会创建一个TensorFlow中的命名空间,在这个命名空间内创建的变量名称都会带上这个空间名作为前缀,因此tf.variable_scope函数可以管理变量命名空间。
示例代码:

import tensorflow as tf
with tf.variable_scope("bar"):
    v0= tf.get_variable('v',[1],initializer = tf.constant_initializer(1.0))  
with tf.variable_scope("bar",reuse =True):
    v2= tf.get_variable('v',[1])    
    print(v2.name) #输出带有空间名:bar\v:0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值