tf.name_scope和tf.variable_scope

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

tf.name_scope和tf.variable_scope

Bubbliiiing   2022-06-03 我要评论

学习前言

最近在学目标检测……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.get_variable()拥有一个变量检查机制,会检测已经存在的变量是否设置为共享变量,当同名变量存在共享机制时,不会报错,如果并未设置为共享变量,则报错。

如果使用tf.Variable() 的话每次都会新建变量。但是很多时候我们希望重用一些变量,所以我们使用到了get_variable(),它会去搜索变量名,有就直接用,没有再新建。
在进行变量共享的时候需要使用到标志reuse,当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

如果在下部再加上

with tf.variable_scope("scope2"):
    v1_share = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1))
    print(v1_share.name)

此时没有reuse,不能共享,程序报错。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们