2022-03-05
翻译自:
问题:以下功能有什么区别?
tf.(, 名称, , =None)
一个为一个。这就是从同一个图给出的,那个图就是图,一个名字范围和一个范围。
tf.(, name, =None) a 用于使用操作。这表示给定相同的图,表示该图是该图,并且是一个名称范围。
tf.(姓名)
对于 Graph.() 使用图形。有关更多信息,请参见 Graph.()。
tf.(,reuse=None, =None)
a for 范围。to new 和 to share one to not or share by 。对于,请参阅 Scope How To,这里我们只介绍几个基本的 .
答案1:
首先简单介绍一下变量共享( )。这是允许从代码中的不同位置访问共享变量的机制之一(不传递变量引用)。tf。方法可以将变量的名称作为参数来创建具有该名称的新变量或检索该变量(如果该变量已存在)。这与 tf. 每次调用 tf. 创建一个新变量(如果已存在同名变量,则可能在变量名中添加后缀)。对于共享变量机制,引入了作用域(scope)。
结果,我们有两种不同的类型:
这两个对所有操作()和使用 tf.
然而,tf. 忽略名称范围,我们可以看下面的例子:
with tf.name_scope("my_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_scope/var2:0 print(a.name) # my_scope/Add:0
使用 tf. 的唯一方法。在范围内使变量可访问是使用范围,例如:
with tf.variable_scope("my_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_scope/var1:0print(v2.name) # my_scope/var2:0 print(a.name) # my_scope/Add:0
这使我们可以轻松地在程序的不同部分之间共享变量,即使在不同的名称范围内:
with tf.name_scope("foo"): with tf.variable_scope("var_scope"): v = tf.get_variable("var", [1]) with tf.name_scope("bar"): with tf.variable_scope("var_scope", reuse=True): v1 = tf.get_variable("var", [1]) assert v1 == v print(v.name) # var_scope/var:0 print(v1.name) # var_scope/var:0
更新:
在版本 r0.11 之后,and 被弃用,并被 and 取代。
答案 2:
举个例子并形象化。
import tensorflow as tf def scoping(fn, scope1, scope2, vals): with fn(scope1): a = tf.Variable(vals[0], name='a') b = tf.get_variable('b', initializer=vals[1]) c = tf.constant(vals[2], name='c') with fn(scope2): d = tf.add(a * b, c, name='res') print 'n '.join([scope1, a.name, b.name, c.name, d.name]), 'n' return dd1 = scoping(tf.variable_scope, 'scope_vars', 'res', [1, 2, 3]) d2 = scoping(tf.name_scope, 'scope_name', 'res', [1, 2, 3]) with tf.Session() as sess: writer = tf.summary.FileWriter('logs', sess.graph) sess.run(tf.global_variables_initializer()) print sess.run([d1, d2]) writer.close()
输出如下:
scope_vars scope_vars/a:0 scope_vars/b:0 scope_vars/c:0 scope_vars/res/res:0 scope_name scope_name/a:0 b:0 scope_name/c:0 scope_name/res/res:0
如下图所示:
从上面可以看出,tf.() 给所有变量添加了前缀(不管你如何创建),操作(ops),常量(),而 tf.() 忽略了用 tf.() 创建的变量,因为它假设您知道您使用的变量在哪个范围内。
文档告诉你:
tf.variable_scope(): Manages namespaces for names passed to tf.get_variable().
有关详细信息,请查看官方文档。
分类:
技术要点:
相关文章:
暂无评论内容