Search code examples
pythontensorflowtensorboard

Incorrect scalar summary being shown on tensorboard


I am trying to randomly generate 100 unique numbers and then write them as summary. However, every time the summary writer writes the default value of the variable.

import warnings
with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=FutureWarning)
    import tensorflow as tf

tf.compat.v1.reset_default_graph()
x = tf.compat.v1.Variable(name="X", shape=[], initial_value=0.0)
summary = tf.compat.v1.summary.scalar("X_summary", x)
summary_op = tf.compat.v1.summary.merge_all()

with tf.compat.v1.Session() as sess:
    sess.run(tf.compat.v1.global_variables_initializer())
    writer = tf.compat.v1.summary.FileWriter("train_dir", sess.graph)
    for step in range(100):
        x = tf.random.normal(stddev=0.01, shape=[1])
        x, summary_ = sess.run([x, summary_op])
        writer.add_summary(summary_, step)

The summary writer writes all the values as 0. Could someone help me point out my mistake?


Solution

  • Try this: I am giving an initializer to the variable declaration which would produce a random normal value, whereas before you were just giving the default value of zero.

    import tensorflow as tf
    tf.reset_default_graph()   
    x_scalar = tf.get_variable('x_scalar', shape=[], initializer=tf.truncated_normal_initializer(mean=0, stddev=1))
    first_summary = tf.summary.scalar(name='normal_x', tensor=x_scalar)
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        writer = tf.summary.FileWriter('./train_dir', sess.graph)
        for step in range(100):
            sess.run(init)
            summary = sess.run(first_summary)
            writer.add_summary(summary, step)