DaveS
DaveS

Reputation: 105

Attempting to use uninitialized variable - tensorboard

I am just starting to play around with Tensorboard, and want to create a simple example where I have a loop that calls a function. Inside that function I have a tensor variable that gets incremented by one and then I add it to a summary.

I am getting a FailedPreconditionError: Attempting to use uninitalized value x_scalar

But I thought I was initializing the x_scalar with lines 10 and 14. What is the proper way to initialize?

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()

Upvotes: 1

Views: 92

Answers (1)

vr9494
vr9494

Reputation: 76

You initialized your variable in a different tf.Session(). When using your tf.Session() as a context manager the session automatically closes after the block of code has completed.

You could use a checkpoint and metagraph to save your graph+weights and then loading them into your newly created session.

Or you can try passing around a session

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

edited: made a correction

Upvotes: 1

Related Questions