Python中tf.name_scope与tf.variable_scope的区别详解
本文深入解析TensorFlow中tf.name_scope与tf.variable_scope的核心区别,重点阐述变量共享机制。通过对比tf.Variable()与tf.get_variable()的行为,详解reuse参数及AUTO_REUSE模式在变量复用中的作用,帮助开发者正确管理模型参数。
学习前言
近期在钻研目标检测算法,SSD源码结构复杂。对比多个版本的SSD实现后注意到,代码中频繁出现tf.variable_scope的使用。起初误以为它与tf.name_scope功能相同,深入研读后发现二者存在本质差异。
两者区别
tf.name_scope()与tf.variable_scope()均用于定义命名空间,通常分别配合tf.Variable()和tf.get_variable()函数使用。
引入两种不同作用域的主要动机在于支持变量共享功能。
变量共享机制主要围绕tf.Variable()与tf.get_variable()两个函数展开。
在tf.variable_scope作用域内,应使用tf.get_variable()函数。该函数具备变量检查机制:若检测到同名变量且已配置为共享状态,则直接复用而不报错;若未配置共享,则抛出错误。
相比之下,tf.Variable()每次调用都会创建新变量。为实现变量复用,需借助get_variable()搜索已有变量,存在则直接引用,不存在则新建。变量共享通过reuse标志控制:设为True时允许共享,设为False时禁止共享。
tf.variable_scope函数
tf.variable_scope(
name_or_scope,
default_name=None,
values=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None,
constraint=None,
auxiliary_name_scope=True
)
参数说明如下:
1、name_or_scope:指定作用域名称。
2、default_name:当name_or_scope为None时启用默认唯一名称;若提供name_or_scope,则忽略此参数,可为None。
3、values:传递给操作函数的Tensor参数列表。
4、initializer:该作用域内变量的默认初始化器。
5、regularizer:该作用域内变量的默认正则化器。
6、caching_device:该作用域内变量的默认缓存设备。
7、partitioner:该作用域内变量的默认分区程序。
8、custom_getter:该作用域内变量的默认自定义获取器。
9、reuse:可选值为True、None或tf.AUTO_REUSE。True表示开启变量共享;tf.AUTO_REUSE表示若变量不存在则创建,否则返回已有变量(适用于首轮创建);None表示继承父作用域的重用标志。
10、dtype:定义该作用域内创建变量的数据类型。
测试代码
1、使用reuse=True共享变量
import tensorflow as tf
# 初始化第一个v1
with tf.variable_scope("scope1"):
v1 = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1))
print(v1.name)
# 不同的作用域
with tf.variable_scope("scope2"):
v1 = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1))
print(v1.name)
# 开始共享
with tf.variable_scope("scope1",reuse = True):
v1_share = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1))
print(v1_share.name)
运行结果为:
scope1/v1:0 scope2/v1:0 scope1/v1:0
若在后续代码中不加reuse参数直接调用:
with tf.variable_scope("scope2"):
v1_share = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1))
print(v1_share.name)
此时因未启用共享,程序将报错。
2、使用AUTO_REUSE共享变量
import tensorflow as tf
# 使用AUTO_REUSE可以直接创建
# 如果reuse = True,初始化第一轮创建的时候会报错
def demo():
with tf.variable_scope("demo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v
v1 = demo()
v2 = demo()
print(v1.name)
运行结果为:
demo/v:0 demo/v:0
以上为Python神经网络中tf.name_scope与tf.variable_scope函数区别的详细解析,更多关于tf.name_scope和tf.variable_scope的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













