尝试使用未初始化的变量 - tensorboard

Attempting to use uninitialized variable - tensorboard

我刚开始使用 Tensorboard,想创建一个简单的示例,其中我有一个调用函数的循环。在该函数中,我有一个张量变量,该变量会递增 1,然后将其添加到摘要中。

我收到一个 FailedPreconditionError: Attempting to use uninitialized value x_scalar

但我认为我是在第 10 行和第 14 行初始化 x_scalar。正确的初始化方法是什么?

import tensorflow as tf
tf.reset_default_graph()   # To clear the defined variables and operations of the previous cell

# create the scalar variable
x_scalar = tf.get_variable('x_scalar', shape=[], initializer=tf.truncated_normal_initializer(mean=0, stddev=1))

# ____step 1:____ create the scalar summary
first_summary = tf.summary.scalar(name='My_first_scalar_summary', tensor=x_scalar)
step = 1
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('./graphs', sess.graph)
    sess.run(x_scalar.assign(1))
    print(sess.run(x_scalar))
    print("---------------------------")
def main():
    global init
    global first_summary
    global step

    # launch the graph in a session
    # with tf.Session() as sess:
        # # ____step 2:____ creating the writer inside the session
        # writer = tf.summary.FileWriter('./graphs', sess.graph)
    for s in range(100):
        func()

def func():
    global init
    global first_summary
    global step
    global x_scalar

    with tf.Session() as sess:
        # ____step 2:____ creating the writer inside the session

        # loop over several initializations of the variable
        sess.run(x_scalar.assign(x_scalar + 1))
        # ____step 3:____ evaluate the scalar summary
        summary = sess.run(first_summary)
        # ____step 4:____ add the summary to the writer (i.e. to the event file)
        writer.add_summary(summary, step)
        step = step + 1
        print('Done with writing the scalar summary') 
if __name__ == '__main__':
    main()

您在另一个 tf.Session() 中初始化了您的变量。当使用 tf.Session() 作为上下文管理器时,会话会在代码块完成后自动关闭。

您可以使用检查点和元图来保存图和权重,然后将它们加载到新创建的会话中。

或者您可以尝试传递会话

sess = tf.Session()
sess.run([CODE])
sess.run([CODE])
sess.run([CODE])
sess.run([CODE])
sess.close()

已编辑:进行了更正