1

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.

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Too bad, this is not the case. I understand that it looks confusing, but g is already being defined by the with.. as g: I also ran the code with your suggestion of change, and the same situation happened.
but the way that you have the identiation g becomes out of scope when the session is initialized
Okay, as I said before, I have tried your suggestion but it did not change the output. And to check again, I printed the operations of both graph g1 and g in the function.. which are identical. Do you perhaps have any other suggestions? Would you consider this a bug?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.