zwep
zwep

Reputation: 1340

tensorflow initialize variable error

As you all know there are various ways to initialize your variables in tensorflow. I tried some stuff in combination with a graph definition. See the code below.

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

Why is it so that Graph1a() and Graph1b() won't return product, while Graph1c() does? I thought these statements were equivalent.

Upvotes: 1

Views: 67

Answers (1)

Aaron
Aaron

Reputation: 2374

The problem is that the global_variables_initializer needs to be associated with the same graph as the session. In Graph1c this happens because the global_variables_initializer is inside the scope of the with statement of the session. To get Graph1a to work it needs to be rewritten like this

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

Upvotes: 1

Related Questions