变量作用域

TensorFlow中的两个作用域:

variable_scope name_scope
variable_name或者op_name加前缀 op_name加前缀

variable_scope

variable_scope变量作用机制在TensorFlow中主要由两部分组成:

v = tf.get_variable(name,shape,dtype,initializer)  #通过所给名字创建或者返回一个变量
tf.variable_scope(<scope_name>)#为变量指定命名空间

当tf.getvariable_scope().reuse==False时,variable_scope作用域只能用来创建新变量。

with tf.variable_scope("foo"):
    v = tf.get_variable("v",[1])
    v2 = tf.get_variable("v",[1])
assert v.name == "foo/v:0"

上述程序会抛出ValueError错误,因为v这个变量已经被定义过了,但是tf.get_variable_scope().reuse默认为False,所以不能重用。
当tf.get_variable_scope().reuse==True 时,作用域可以共享变量:

with tf.get_variable_scope("foo") as scope:
    v = tf.get_variable(v,[1])
with tf.get_variable_scope("foo",reuse==True)
#也可以写成
#scope.reuse_variables()
v1=tf.get_variable("v",[1])
assert v1 == v
获取变量作用域

可以直接通过tf.variable_scope()来获取变量作用域:

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

注意,如果在开启的一个变量作用域里使用之前预先定义的一个作用域,则会跳过当前变量的作用域,保持预先存在的作用域不变。

变量作用域的初始化

变量作用域可以默认携带一个初始化器,在这个作用域中的子作用域或变量都可以继承或者重写父作用域初始化的值。

with tf.variable_scope("foo",initializer=tf.constant_initializer(0.4)):
    v = tf.get_variable("v",[1])
with tf.variable_scope("bar")
    with tf.variable_scope("baz") as other_scope:
        assert other_scope.name == "bar/baz"
        with tf.variable_scope(foo_scope) as foo_scope2:
            assert foo_scope2.name == "foo" #保持不变

同样的在variable_scope作用域下的op.name也会被加上加上前缀。
variable_scope主要用在循环神经网络(RNN)的操作中,其中需要大量的共享变量。

name_scope

TensorFlow中的节点用name_scope来为变量划分范围,在可视化中,这表示在计算图中的一个层级。
name_scope会影响op.name,不会影响用get_variable创建的变量,而会影响通过Variable()创建的变量。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、引言 最近在刷leetcode题的时候,遇到一个求最长回文子串的题目,于是,我写了如下的代码: 哎呀,写了两个...
    文哥的学习日记阅读 14,397评论 6 32
  • 1.1 基本类型和引用类型的值 ECMAScript变量可能包含两种不同数据类型的值:基本类型值和引用类型值。基本...
    Jackandjohn阅读 314评论 0 0
  •   按照 ECMA-262 的定义,JavaScript 的变量与其他语言的变量有很大区别。   JavaScri...
    霜天晓阅读 399评论 0 0
  • 撑一把荷叶伞 天水间 与清风共舞 采集一路花香 撑一把荷叶伞 花海里 与暗香同歌 品尝初夏的滋味 撑一把荷叶伞 静静守候
    阳光冬雨阅读 233评论 0 2
  • 二十年缘悭一面,相隔万里莫逆于心。 海莲·汉芙和弗兰克·德尔,互相写信二十年却从未谋面,书缘?情缘? 或许心中已住...
    伊晓阅读 762评论 1 3