简体   繁体   English

为什么Tensorflow初始化一个类中失败的变量?

[英]Why tensorflow initialize the variables failed in a class?

The simplified code as bellow: 简化的代码如下:

class ExModel(object):
    def __init__(self, graph=None):

        if graph is None:
            self.graph = tf.get_default_graph()
        else:
            self.graph = graph

        self.sess = tf.Session(graph=self.graph)

        self.init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
        self.build_model()

        print(self.sess.run(tf.report_uninitialized_variables()))  # [b'global_step']
        print(self.sess.run(self._global_step))  # uninitialized error

    def build_model(self):
        with self.graph.as_default():
            self._global_step = tf.Variable(0, trainable=False, name='global_step')

        self.sess.run(self.init_op)

if __name__ == '__main__':
    model = ExModel()

It shows use uninitialized value error. 它显示use uninitialized value错误。

It seems no difference with the code bellow, but it can works well. 似乎下面的代码没有什么区别,但是它可以很好地工作。

if __name__ == '__main__':
    # model = ExModel()

    graph = tf.get_default_graph()

    sess = tf.Session(graph=graph)

    with graph.as_default():
        global_step = tf.Variable(0, trainable=False, name='global_step')

    sess.run(tf.global_variables_initializer())
    print(sess.run(global_step))

Please help me, the probelm have tormented me the whole day. 请帮助我,这整整一天都困扰着我。

I have read another question . 我读了另一个问题 I think my error is samiliar with it, but I don't know how to make the global_variables_initializer be associated with the same graph as the session, and I just use the default graph. 我认为我的错误很熟悉,但是我不知道如何使global_variables_initializer与会话与同一图相关联,而我只使用默认图。

I find when use self.sess.run(tf.global_variables_initializer()) to replace 我发现何时使用self.sess.run(tf.global_variables_initializer())进行替换

self.init_op = tf.global_variables_initializer()
self.sess.run(self.init_op)

can work well. 可以很好地工作。 But I still don't know the reason. 但是我仍然不知道原因。

The probelm is that init_op = tf.global_variables_initializer() should be define at the last of all the variables. 问题是init_op = tf.global_variables_initializer()应该在所有变量的最后定义。

It should be 它应该是

global_step = tf.Variable(0, trainable=False, name='global_step')
...
init_op = tf.global_variables_initializer()
sess.run(init_op)

but not 但不是

init_op = tf.global_variables_initializer()
global_step = tf.Variable(0, trainable=False, name='global_step')
...
sess.run(init_op)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM