最近在看TensorFlow的变量管理,发现很多代码中tf.variable_scope()参数的数量及意义还不太清楚,特此记录:

def __init__(self,
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):
"""Initialize the context manager.
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
default_name: The default name to use if the `name_or_scope` argument is
`None`, this name will be uniquified. If name_or_scope is provided it
won't be used and therefore it is not required and can be None.
values: The list of `Tensor` arguments that are passed to the op function.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
reuse: `True`, None, or tf.AUTO_REUSE; if `True`, we go into reuse mode
for this scope as well as all sub-scopes; if tf.AUTO_REUSE, we create
variables if they do not exist, and return them otherwise; if None, we
inherit the parent scope's reuse flag. When eager execution is enabled,
this argument is always forced to be tf.AUTO_REUSE.
dtype: type of variables created in this scope (defaults to the type
in the passed scope, or inherited from parent scope).
use_resource: If False, all variables will be regular Variables. If True,
experimental ResourceVariables with well-defined semantics will be used
instead. Defaults to False (will later change to True). When eager
execution is enabled this argument is always forced to be True.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
auxiliary_name_scope: If `True`, we create an auxiliary name scope with
the scope. If `False`, we don't touch name scope.
Returns:
A scope that can be captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope.
TypeError: when the types of some arguments are not appropriate.
"""
上面的代码是tf.variable函数的定义,其中
name_or_scope: `string` or `VariableScope`: the scope to open. 是变量空间的名称
default_name: 当name_or_scope 使用时它就可以忽略,基本没什么用
values: 传入该scope的tensor参数
initializer=None: 默认的参数初始化函数
regularizer: d默认的正则化函数
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
reuse: `True`, None, or tf.AUTO_REUSE; if `True`, we go into reuse mode
for this scope as well as all sub-scopes; if tf.AUTO_REUSE, we create
variables if they do not exist, and return them otherwise; if None, we
inherit the parent scope's reuse flag. When eager execution is enabled,
this argument is always forced to be tf.AUTO_REUSE
reuse有三种取值,默认取值是None:

True: 参数空间使用reuse 模式,即该空间下的所有tf.get_variable()函数将直接获取已经创建的变量,如果参数不存在tf.get_variable()函数将会报错。

AUTO_REUSE:若参数空间的参数不存在就创建他们,如果已经存在就直接获取它们。

None 或者False 这里创建函数tf.get_variable()函数只能创建新的变量,当同名变量已经存在时,函数就报错

下面是几个例子:

with tf.variable_scope("foo"):
v = tf.get_variable("v", [1], initializer=tf.constant_initializer(1.0))

#with tf.variable_scope("foo"):
# v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
print(v == v1)

#with tf.variable_scope("bar", reuse=True):
# v = tf.get_variable("v", [1])
输出是True

with tf.variable_scope("root"): # reuse 在默认情况下为false 或者和 上一层保持一致
print(tf.get_variable_scope().reuse)

with tf.variable_scope("foo", reuse=True):
print(tf.get_variable_scope().reuse)

with tf.variable_scope("bar"):
print(tf.get_variable_scope().reuse)

print(tf.get_variable_scope().reuse)

tf.name_scope和tf.variable_scope的关系

tf.name_scope和tf.variable_scope是两个作用域,主要与创建/调用变量函数tf.Variable() 和tf.get_variable()搭配使用。首先说tf.Variable() 和tf.get_variable()的区别:

tf.Variable() 每次调用都会产生一个新的变量,他会自动检测命名冲突并自行处理,变量名称是一个可选参数,例如:

a1 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')

print(a1.name)

print(a2.name)

print(a1==a2)

运行结果:

f1/a1:0
f1/a1_1:0

False    # a2实际变成了a1_1并且和a1 不是同一个变量

而tf.get_variable()则不同,遇到重命名的变量创建且变量名没有设置成共享变量(所谓的共享是指在同一参数空间下的共享,参数空间名称不一样就不能共享了)时,就会报错 ;相对应的,变量名称这个参数是必填参数,tf.get_variable()会根据这个参数去创建或者获取变量。

tf.name_scope()主要用于管理图中各种op,而tf.variable_scope()主要用于管理图中变量的名字,在 tf.name_scope下时,tf.get_variable()创建的变量名不受 name_scope 的影响(不受它的约束)

import tensorflow as tf

with tf.variable_scope('f2'):
#a1 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))
a1 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a1')
a5 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))

with tf.variable_scope('f2', reuse=True):
a3 = tf.get_variable(name='a1', shape=[1], initializer=tf.constant_initializer(1))

a4 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a2')

print(a1.name)
print(a2.name)
print(a1==a2)
print(a5.name)
print(a3.name)
print(a4.name)
运行结果:

f2/a1:0
f2/a1_1:0
False
f2/a1_2:0
f2/a1_2:0
f2_1/a2:0

---------------------
作者:hyxing520
来源:CSDN
原文:https://blog.csdn.net/hyxing520/article/details/80889496
版权声明:本文为博主原创文章,转载请附上博文链接!

tf.variable_scope 参数的更多相关文章

  1. 深度学习原理与框架-Alexnet(迁移学习代码) 1.sys.argv[1:](控制台输入的参数获取第二个参数开始) 2.tf.split(对数据进行切分操作) 3.tf.concat(对数据进行合并操作) 4.tf.variable_scope(指定w的使用范围) 5.tf.get_variable(构造和获得参数) 6.np.load(加载.npy文件)

    1. sys.argv[1:]  # 在控制台进行参数的输入时,只使用第二个参数以后的数据 参数说明:控制台的输入:python test.py what, 使用sys.argv[1:],那么将获得w ...

  2. tf.variable和tf.get_Variable以及tf.name_scope和tf.variable_scope的区别

    在训练深度网络时,为了减少需要训练参数的个数(比如具有simase结构的LSTM模型).或是多机多卡并行化训练大数据大模型(比如数据并行化)等情况时,往往需要共享变量.另外一方面是当一个深度学习模型变 ...

  3. TF.VARIABLE、TF.GET_VARIABLE、TF.VARIABLE_SCOPE以及TF.NAME_SCOPE关系

    1. tf.Variable与tf.get_variable tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要 ...

  4. 理解 tf.Variable、tf.get_variable以及范围命名方法tf.variable_scope、tf.name_scope

    tensorflow提供了通过变量名称来创建或者获取一个变量的机制.通过这个机制,在不同的函数中可以直接通过变量的名字来使用变量,而不需要将变量通过参数的形式到处传递. 1. tf.Variable( ...

  5. tf.name_scope()和tf.variable_scope() (转)

    网络层中变量存在两个问题: 随着层数的增多,导致变量名的增多: 在调用函数的时候,会重复生成变量,但他们存储的都是一样的变量.   tf.variable不能解决这个问题. 变量作用域使用tf.var ...

  6. 彻底弄懂tf.Variable、tf.get_variable、tf.variable_scope以及tf.name_scope异同

    https://blog.csdn.net/qq_22522663/article/details/78729029 1. tf.Variable与tf.get_variabletensorflow提 ...

  7. Tensorflow函数——tf.variable_scope()

    Tensorflow函数——tf.variable_scope()详解 https://blog.csdn.net/yuan0061/article/details/80576703 2018年06月 ...

  8. TensorFlow基础笔记(13) tf.name_scope tf.variable_scope学习

    转载http://blog.csdn.net/jerr__y/article/details/60877873 1. 首先看看比较简单的 tf.name_scope(‘scope_name’). tf ...

  9. tensorflow中共享变量 tf.get_variable 和命名空间 tf.variable_scope

    tensorflow中有很多需要变量共享的场合,比如在多个GPU上训练网络时网络参数和训练数据就需要共享. tf通过 tf.get_variable() 可以建立或者获取一个共享的变量. tf.get ...

随机推荐

  1. 2-4 Numpy+Matplotlib可视化(二)

    自定义绘图 # -*-coding:utf-8-*- # !/usr/bin/env python # Author:@vilicute import numpy as np import matpl ...

  2. SCAN listener and Node listener – How does it work

    http://www.mydbspace.com/? p=324 Single Client Access Name (SCAN) is new feature of oracle 11gR2 gri ...

  3. [Vue CLI 3] 配置解析之 indexPath

    在 vue.config.js 配置中有一个 indexPath 的配置,我们先看看它有什么用? 用来指定 index.html 最终生成的路径(相对于 outputDir) 先看看它的默认值:在文件 ...

  4. iOS开发——你真的会用SDWebImage?

    http://www.cocoachina.com/ios/20160503/16064.html 本文授权转载,作者:hosea_zhou(简书) SDWebImage作为目前最受欢迎的图片下载第三 ...

  5. VisualTreeHelper使用——使用BFS实现高效率的视觉对象搜索

    BFS,即广度优先搜索,是一种典型的图论算法.BFS算法与DFS(深度优先搜索)算法相对应,都是寻找图论中寻路的常用算法,两者的实现各有优点. 其中DFS算法常用递归实现,也就是常见的一条路找到黑再找 ...

  6. Python re.sub函数

  7. COOKIE与SESSION的详解

    cookie与session的小例子: 包含cookie记住登录名,session防止用户非法登录2个例子: 问我拿吧,这个下载连接挂了 描述 cookie过程描述 网站为了辨别用户身份.进行 ses ...

  8. Sum Root to Leaf Numbers深度优先计算路径和

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...

  9. 【JZOJ4964】【GDKOI2017模拟1.21】Rhyme

    hafy 由于多次交换邮票没有满足所有人的需求,小Z被赶出了集邮部.无处可去的小Z决定加入音乐部,为了让音乐部的人注意到自己的才华,小Z想写一首曲子.为了让自己的曲子更好听,小Z找到了一些好听曲子作为 ...

  10. oracle-12333错误

    Errors in file /oracle/OraHome1/admin/hndw/udump/hndw_ora_17941.trc: ORA-00600: internal error code, ...