Tensorflow学习(二) name_scope和variable_scope

本文详细介绍了TensorFlow中的tf.name_scope()和tf.variable_scope()的使用方法及区别。tf.name_scope()用于节点命名,方便Tensorboard记录;tf.variable_scope()用于变量管理,支持变量共享,适用于RNN等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tf.name_scope()创建名称作用域,可以影响tf.Variable和tf.Operation,主要用于对节点名称命名,方便Tensorboard记录和分类节点创建名称作用域,可以影响tf.Variable和tf.Operation

with tf.name_scope('foo') as foo_scope:
    a = tf.Variable(1, name='a')
    assert a.name == 'foo/a:0'
    with tf.name_scope('bar') as bar_scope:
        b = tf.Variable(2, name='b')
        c = a * b
        assert b.name == 'foo/bar/b:0'
        assert c.op.name == 'foo/bar/mul'

注:a.name是Tensor的name属性,name中‘:’后是Tensor的value_index属性,value_index表示该Tensor被产生它的操作的第几个输出,如

#value是一个[5, 30]的矩阵
split0, split1, split2 = tf.split(value, [4, 15, 11], 1)

则split0,split1,split2的value_index分别为0、1、2。

tf.variable_scope()用于创建变量作用域,可以通过tf.fet_variable()创建变量,tf.variable_scope()只影响由tf.get_variable()创建的变量,而不会影响tf.Variable()创建的变量,tf.get_variable()也可从内存中取出已有变量,tf.variable_scope()主要应用于需要大规模共享变量的场景,如RNN。tf.variable_scope().reuse默认为False,此时不可重复使用此变量域中的变量

with tf.variable_scope('var_scope', reuse=tf.AUTO_REUSE) as var_scope
    v1 = tf.get_variable('v', [1])
    v2 = tf.get_variable('v', [1])
    assert v1.name =='var_scope/v:0')
    assert v1 == v2
    #id(var)查询变量在内存中的位置,发现v1、v2一样,是因为v1、v2同时调用内存中同一变量
    print(id(v1), id(v2))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值