TensorFlow作用域:name_scope和variable_scope

在TensorFlow中有两个作用域,一个是name_scope,另一个是variable_scope。variable_scope主要是给variable_name加前缀的,也给op_name加前缀;name_scope是给op_name加前缀。

1、variable_scope示例

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

v = tf.get_variable()#通过所给的名字创建或是返回一个变量
tf.variable_scope()#为变量指定命名空间

当reuse=False时,

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

抛出错误,因为v这个变量已经被定义过了。

作用域可以共享变量:

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

输出:True

1.获取变量作用域

#可以直接通过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") as foo_scope:
    print(foo_scope.name)
with tf.variable_scope("bar") :
    with tf.variable_scope("barz") as other_scope:
        print(other_scope.name)
        #如果在开启的一个变量作用域里使用之前预先定义的一个作用域,则会跳过当前变量的作用域,保持预先存在的作用域不变
        with tf.variable_scope(foo_scope) as foo_scope2:
            print(foo_scope2.name)#保持不变

输出:

foo
bar/barz
foo

2、name_scope示例

TesnsorFlow中常常会有数以千计的节点,在可视化的过程中很难一下子展示出来,因此用name_scope为变量划分范围,在可视化中,这表示在计算图中的一个层级。

with tf.name_scope('conv1') as scope:
    w1 = tf.Variable([1], name='weights')
    b1 = tf.Variable([0.3], name='bias')

with tf.name_scope('conv2') as scope:
    w2 = tf.Variable([1], name='weights')
    b2 = tf.Variable([0.3], name='bias')

print (w1.name)
print (w2.name)
print (b1.name)
print (b2.name)

输出:

conv1/weights:0
conv2/weights:0
conv1/bias:0
conv2/bias:0

name_scope会影响op_name,不会影响用get_variable()创建的变量,而会影响通过Variable()创建的变量。

import tensorflow as tf

with tf.variable_scope("foo") :
    with tf.name_scope("bar"):
        v = tf.get_variable("v",[1])
        b = tf.Variable(tf.zeros([1]),name='b')
        x = 1.0 + v

print(v.name)
print(b.name)
print(x.op.name)

输出:

foo/v:0
foo/bar/b:0
foo/bar/add

可以看出,name_scope对用get_variable创建的变量的名字不会有任何影响,而Variable创建的操作会被加上前缀,并且会给操作加上名字前缀。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值