两种scope:variable与name

两种scope:variable与name

tf.variable_scope()是对变量进行命名管理,而tf.name_scope()是对算子(op)进行命名管理,二者相互不影响。见下例:


    import tensorflow as tf

    for i in range(10):

    with tf.name_scope('test'):

    a = tf.constant([1])

    b = tf.constant([1])

    c = a + b

    with tf.variable_scope("foo",reuse=True): # 设定为重用模式,

    v = tf.get_variable("v", [1])

    v1 = tf.get_variable("v", [1])

    print(v)

    print(v1)

    assert v is v1

    print(c)

 结果中算子c的名称会随着循环的增加而改变:"test_1_2_..._9/add:0"。而v和v1两个变量始终都是'foo/v:0'。

二、variable_scope的reuse方法

如果需要同一个参数参与不同的运算,可以使用reuse构建不同的指针指向相同的variable。例如在tf中想在多GPU上进行并行计算,需要使用reuse完成模型的复制。

import tensorflow as tf

with tf.variable_scope("foo",reuse=False): # 只有在false下才能新增变量

v = tf.get_variable("v", [1]) # 创建新变量

tf.get_variable_scope().reuse_variables() # 开启reuse模式,不能够再新建变量

v1 = tf.get_variable("v", [1]) # 自动reuse变量v

print(v)

print(v1)

assert v is v1

for i in range(10):

with tf.variable_scope("foo",reuse=True): # 开启reuse模式

v = tf.get_variable("v", [1]) # 自动reuse变量v

print(v)

最终结果:全为'foo/v:0'

官方示例:

import tensorflow as tf

with tf.variable_scope("foo"):

v = tf.get_variable("v", [1])

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

v1 = tf.get_variable("v", [1])

注:可以在后续对scope的reuse模式进行改变,从而新增变量。reuse的本质是为创建好的variable添加指针。

 

TensorFlow的reuse参数、一次性对variable_scope进行reuse的两种简便方法

tensorflow中通过共享 变量作用域(variable_scope)来实现共享变量 ,节约变量存储空间 。
TensorFlow用于变量管理的函数主要有两个:

  • tf. get_variable() 用于创建或获取变量的值
  • tf.variable_scope() 用于生成上下文管理器,创建命名空间,命名空间可以嵌套。

函数**tf.get_variable()**既可以创建变量,也可以获取变量。用函数tf.variable.scope()中的参数reuse来控制,分两种情况进行说明:

  1. 设置reuse=False时,函数get_variable()表示创建变量
with tf.variable_scope("foo",reuse=False):
    v=tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))
  • 1
  • 2

在tf.variable_scope()函数中,设置reuse=False时,在其命名空间"foo"中执行函数get_variable()时,表示创建变量"v",若在该命名空间中已经有了变量"v",则在创建时会报错。

import tensorflow as tf 
with tf.variable_scope("foo"): 
	v=tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0)) 
	v1=tf.get_variable("v",[1])
# ValueError: Variable foo/v already exists, disallowed. 
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 设置reuse=True时,函数get_variable()表示获取变量
    设置 reuse=True 可以再次调用 该共享变量作用域
import tensorflow as tf
with tf.variable_scope("foo"):
    v=tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))
    
with tf.variable_scope("foo",reuse=True):
    v1=tf.get_variable("v",[1])
print(v1==v)    #结果为:True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在tf.variable_scope()函数中,设置reuse=True时,在其命名空间"foo"中执行函数get_variable()时,表示获取变量"v"。若在该命名空间中还没有该变量,则在获取时会报错,如下面的例子

import tensorflow as tf 
with tf.variable_scope("foo",reuse=True):
    v1=tf.get_variable("v",[1])
    # ValueError: Variable foo/v does not exist, or was not created with tf.get_variable()
  • 1
  • 2
  • 3
  • 4

TensorFlow通过tf. get_variable()和tf.variable_scope()两个函数,可以创建多个并列的或嵌套的命名空间,用于存储神经网络中的各层的权重、偏置、学习率、滑动平均衰减率、正则化系数等参数值,神经网络不同层的参数可放置在不同的命名空间中。同时,变量重用检错和读取不存在变量检错两种机制保证了数据存放的安全性。

一次性对variable_scope进行reuse的两种简便方法

  • 使用 tf.Variable_scope(..., reuse=tf.AUTO_REUSE)
  • 通过 from tensorflow.python.ops import variable_scope as vs 来导入操作。
# -*- coding: utf-8 -*- 
import tensorflow as tf 
def func(...):
	 with tf.variable_scope(name_or_scope='', reuse=tf.AUTO_REUSE): ### 改动部分 ### 
  • 1
  • 2
  • 3
  • 4

方法2中,main函数要设置reuse=(_!=0)

# -*- coding: utf-8 -*-

import tensorflow as tf

from tensorflow.python.ops import variable_scope as vs    ### 改动部分 ###

def func(..., reuse=False):    ### 改动部分 ###

    if reuse:                                        ### 改动部分 ###
        vs.get_variable_scope().reuse_variables()    ### 改动部分 ###

    return output


def main():
    with tf.Graph().as_default():
        pass
        for _ in xrange(5):
            output = func(..., reuse=(_!=0))    ### 改动部分 ###
            with tf.Session() as sess:
                sess.run(tf.global_variables_initializer())
                pass
                _output = sess.run(output, feed_dict=...)
                pass

if __name__ == "__main__":
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值