tensorflow初始化变量错误

时间:2017-10-10 16:58:03

标签: 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, 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()呢?我认为这些陈述是等同的。

1 个答案:

答案 0 :(得分:1)

问题是<a href="whatsapp://send?text=my message&phone=+XXXXXXXXXXX&abid=+XXXXXXXXXXX">Whatsapp me please</a> 需要与会话相同的图形关联。在global_variables_initializer中会发生这种情况,因为Graph1c位于会话的with语句的范围内。要让global_variables_initializer工作,需要像这样重写

Graph1a