众所周知,有多种方法可以在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

10-04 18:23