众所周知,有多种方法可以在tensorflow中初始化变量。我尝试了一些与图形定义结合的东西。请参见下面的代码。
def Graph1a():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
sess = tf.Session( graph = g )
sess.run(tf.global_variables_initializer())
return product
def Graph1b():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
sess = tf.Session( graph = g )
sess.run(tf.initialize_all_variables())
return product
def Graph1c():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
with tf.Session( graph = g ) as sess:
tf.global_variables_initializer().run()
return product
为什么
Graph1a()
和Graph1b()
不会返回产品,而Graph1c()
会返回产品呢?我认为这些陈述是等效的。 最佳答案
问题是global_variables_initializer
需要与与会话相同的图相关联。在Graph1c
中,这是因为global_variables_initializer
在会话的with语句的范围内。要使Graph1a
工作,需要像这样重写
def Graph1a():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
init_op = tf.global_variables_initializer()
sess = tf.Session( graph = g )
sess.run(init_op)
return product