为什么我们使用 tf.name_scope() [英] Why do we use tf.name_scope()
问题描述
我一直在阅读他们编写的关于 TensorFlow 的教程
I've been reading the tutorials on TensorFlow where they have written
with tf.name_scope('read_inputs') as scope:
# something
例子
a = tf.constant(5)
和
with tf.name_scope('s1') as scope:
a = tf.constant(5)
似乎有同样的效果.那么,我们为什么要使用 name_scope
?
seem to have the same effect. So, why do we use name_scope
?
推荐答案
我没有看到重用常量的用例,但这里有一些关于作用域和变量共享的相关信息.
I don't see the use case for reusing constants but here is some relevant information on scopes and variable sharing.
范围
name_scope
将范围作为前缀添加到所有操作
name_scope
will add scope as a prefix to all operations
variable_scope
将范围作为前缀添加到所有变量和操作
variable_scope
will add scope as a prefix to all variables and operations
实例化变量
tf.Variable()
构造器使用当前的name_scope
和variable_scope
tf.Variable()
constructer prefixes variable name with currentname_scope
andvariable_scope
tf.get_variable()
构造函数忽略 name_scope
并且只用当前的 variable_scope
tf.get_variable()
constructor ignores name_scope
and only prefixes name with the current variable_scope
例如:
with tf.variable_scope("variable_scope"):
with tf.name_scope("name_scope"):
var1 = tf.get_variable("var1", [1])
with tf.variable_scope("variable_scope"):
with tf.name_scope("name_scope"):
var2 = tf.Variable([1], name="var2")
生产
var1 = <tf.Variable 'variable_scope/var1:0' shape=(1,) dtype=float32_ref>
var2 = <tf.Variable 'variable_scope/name_scope/var2:0' shape=(1,) dtype=string_ref>
重用变量
总是使用
tf.variable_scope
来定义共享变量的范围
重用变量的最简单方法是使用reuse_variables()
,如下所示
The easiest way to do reuse variables is to use the reuse_variables()
as shown below
with tf.variable_scope("scope"):
var1 = tf.get_variable("variable1",[1])
tf.get_variable_scope().reuse_variables()
var2=tf.get_variable("variable1",[1])
assert var1 == var2
tf.Variable()
总是创建一个新变量,当一个变量用一个已经用过的名字构造时,它只是附加_1
,_2
> 等等 - 这可能会导致冲突:(tf.Variable()
always creates a new variable, when a variable is constructed with an already used name it just appends_1
,_2
etc. to it - which can cause conflicts :(
这篇关于为什么我们使用 tf.name_scope()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!