Tensorflow中scope命名方法

本文详细介绍了Tensorflow中的tf.name_scope()和tf.variable_scope()的区别及使用。tf.name_scope()主要影响变量显示名称,而不影响变量创建;tf.variable_scope()配合tf.get_variable()用于变量重用,避免在相同作用域内创建重复变量。在RNN应用中,通过variable_scope实现训练和测试阶段权重共享。

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

两篇文章掌握Tensorflow中scope用法:

【1】Tensorflow中scope命名方法(本文)

【2】Tensorflow中tf.name_scope() 和 tf.variable_scope() 的区别

微信公众号

1. tf.name_scope()

在 Tensorflow 当中有两种途径生成变量 variable,一种是 tf.get_variable()另一种是tf.variable() 如果在tf.name_scope()的框架下使用这两种方式,结果会如下。

import tensorflow as tf

with tf.name_scope("a_name_scope"):
    initializer = tf.constant_initializer(value=1)
    var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
    var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
    var21 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
    var22 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var1.name)        # var1:0
    print(sess.run(var1))   # [ 1.]
    print(var2.name)        # a_name_scope/var2:0
    print(sess.run(var2))   # [ 2.]
    print(var21.name)       # a_name_scope/var2_1:0
    print(sess.run(var21))  # [ 2.1]
    print(var22.name)       # a_name_scope/var2_2:0
    print(sess.run(var22))  # [ 2.2]

结果:

分析:

在tf.name_scope()中使用tf.variable()定义变量的时候,虽然name都一样,但是为了不重复变量名,Tensorflow输出的变量名并不是一样的。所以,本质上var2、var21、var22并不是一样的变量。而另一方面,使用tf.get_variable()定义的变量不会被tf.name_scope()当中的名字所影响,相当于tf.name_scope()对tf.get_variable()是无效的。

2. tf.variable_scope()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值