Python tensorflow初始化变量错误

Python tensorflow初始化变量错误,python,tensorflow,Python,Tensorflow,大家都知道,在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, matri

大家都知道,在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()
会退货?我认为这些语句是等价的。

问题是,
全局变量\初始值设定项需要与会话的同一个图形相关联。在
Graph1c
中发生这种情况是因为
global\u variables\u初始值设定项
在会话的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

太糟糕了,事实并非如此。我理解它看起来很混乱,但是g已经被定义为with。。as g:我也使用您的更改建议运行了代码,同样的情况也发生了。但是当会话初始化时,您使用标识g的方式超出了范围。正如我前面所说,我尝试了您的建议,但它没有更改输出。为了再次检查,我在函数中打印了图g1和g的运算。。都是一样的。你可能还有其他建议吗?你认为这是错误吗?