有人可以向我解释name_scopeTensorFlow中的工作原理吗?
假设我有以下代码:
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default() as g:
with g.name_scope( "g1" ) as scope:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
tf.reset_default_graph()
g2 = tf.Graph()
with g2.as_default() as g:
with g.name_scope( "g2" ) as scope:
matrix1 = tf.constant([[4., 4.]])
matrix2 = tf.constant([[5.],[5.]])
product = tf.matmul(matrix1, matrix2)
tf.reset_default_graph()
with tf.Session( graph = g1 ) as sess:
result = sess.run( product )
print( result )
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我收到以下错误消息:
Tensor Tensor("g2/MatMul:0", shape=(1, 1), dtype=float32) is not an element of this graph.
Run Code Online (Sandbox Code Playgroud)
我同意"g2/MatMul"不是图形的元素g1,但为什么在会话图设置为g1?时选择"g2/MatMul" ?为什么不选择"g1/MatMul"?
以下代码似乎有效:
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default() as g:
with g.name_scope( "g1" ) as g1_scope:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
tf.reset_default_graph()
g2 = tf.Graph()
with g2.as_default() as g:
with g.name_scope( "g2" ) as g2_scope:
matrix1 = tf.constant([[4., 4.]])
matrix2 = tf.constant([[5.],[5.]])
product = tf.matmul( matrix1, matrix2, name = "product" )
tf.reset_default_graph()
use_g1 = False
if ( use_g1 ):
g = g1
scope = g1_scope
else:
g = g2
scope = g2_scope
with tf.Session( graph = g ) as sess:
tf.initialize_all_variables()
result = sess.run( sess.graph.get_tensor_by_name( scope + "product:0" ) )
print( result )
Run Code Online (Sandbox Code Playgroud)
通过翻转开关use_g1,图形g1或g2将在会话中运行.这是名称范围界定的方式吗?
Yar*_*tov 16
您product是一个全局变量,并将其设置为指向"g2/MatMul".
特别是
尝试
print product
Run Code Online (Sandbox Code Playgroud)
你会看到的
Tensor("g2/MatMul:0", shape=(1, 1), dtype=float32)
Run Code Online (Sandbox Code Playgroud)
所以系统"g2/MatMul:0"因为那是Tensor的名字,并试图在图中找到它,g1因为那是你为会话设置的图形.顺便提一下,您可以看到图中的所有节点print [n.name for n in g1.as_graph_def().node]
通常,使用多个图表很少有用.您无法合并它们,也无法在它们之间传递张量.我建议你这样做
tf.reset_default_graph()
a = tf.Constant(2)
sess = tf.InteractiveSession()
....
Run Code Online (Sandbox Code Playgroud)
这样,您将拥有一个默认图和一个默认会话,并且在大多数情况下您可以省略指定图或会话.如果您需要明确地引用它们,您可以从tf.get_default_graph()或获取它们tf.get_default_session()
小智 6
这确实是坏事,但它仍然是与此相关的问题的最佳搜索结果,我认为这样做可能有助于做出非常明确的内容,以便先前的回答(正确)通过:
Q的变量product是python变量。这样,它指向一个对象:定义后,它指向在name_scope'g1'中定义的matmul 的tf.Tensor输出tf.Operation。稍后将其重新定义为指向另一个对象,即tf.Tensor“ g2” 的输出。这个python变量从未听说过tf.name_scopes,不在乎。
这就是为什么您需要通过tensorflow对象的名称属性进行查找的原因...使用name_scopes的那些属性是唯一且可访问的。或生成不同的python变量(这些变量是唯一的,并且可以根据python作用域规则进行访问),以指向tf.Tensor要引用的每个对象。
邓诺(Dunno)如果这对其他人有帮助,但是如果我忘记了,我将为此感谢自己。
| 归档时间: |
|
| 查看次数: |
33942 次 |
| 最近记录: |