张量流初始化变量错误

张量流初始化变量错误

本文介绍了张量流初始化变量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,有多种方法可以在 tensorflow 中初始化变量.我尝试了一些结合图形定义的东西.请参阅下面的代码.

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

为什么 Graph1a()Graph1b() 不会返回产品,而 Graph1c() 会返回?我认为这些陈述是等效的.

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

推荐答案

问题在于 global_variables_initializer 需要与会话关联到同一个图.在 Graph1c 中,发生这种情况是因为 global_variables_initializer 在会话的 with 语句的范围内.要让 Graph1a 工作,需要像这样重写

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

这篇关于张量流初始化变量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:30