tensoflow笔记:tf.name_scope和tf.variable_scope

本文详细介绍了Tensorflow中tf.name_scope和tf.variable_scope的使用区别。tf.name_scope只影响tf.Variable的命名,而不影响tf.get_variable创建的变量。而tf.variable_scope则对tf.get_variable和tf.Variable都产生作用,使得在同一作用域内创建的变量能实现共享。理解这两个作用域的不同对于Tensorflow代码的组织和变量管理至关重要。

这两种作用域,对于使用tf.Variable()方式创建的变量,具有相同的效果,都会在变量名称前面,加上域名称。
对于通过tf.get_variable()方式创建的变量,只有variable_scope名称会加到变量名称前面,而name_scope不会作为前缀。例如 print(v1.name) # var1:0

with tf.name_scope("my_name_scope"):
    v1 = tf.get_variable("var1", [1], dtype=tf.float32)
    v2 = tf.Variable(1, name="var2", dtype=tf.float32)
 
a = tf.add(v1, v2)
print(v1.name) # var1:0
print(v2.name) # my_name_scope/var2:0
print(a.name) # my_name_scope/Add:0

小结:name_scope不会作为tf.get_variable变量的前缀,但是会作为tf.Variable的前缀。

with tf.variable_scope("my_variable_scope"):
    v1 = tf.get_variable("var1", [1], dtype=tf.float32)
    v2 = tf.Variable(1, name="var2", dtype=tf.float32)
 
a = tf.add(v1, v2)
print(v1.name) # my_variable_scope/var1:0
print(v2.name) # my_variable_scope/var2:0
print(a.name) # my_variable_scope/Add:0

小结:在variable_scope的作用域下,tf.get_variable()和tf.Variable()都加了scope_name前缀。因此,在tf.variable_scope的作用域下,通过get_variable()可以使用已经创建的变量,实现了变量的共享。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值