43

I often want to log python variables --as opposed to tf tensors.

In the docs it says that "you can pass a tf.Summary protocol buffer that you populate with your own data" but there is no docs for tf.Summary and i could not figure out how to use it.

Anyone knows how to create a Scalar summary this way?

1

3 Answers 3

63

You can create a tf.Summary object in your Python program and write it to the same tf.summary.FileWriter object that takes your TensorFlow-produced summaries using the SummaryWriter.add_summary() method.

The tf.Summary class is a Python protocol buffer wrapper for the Summary protocol buffer. Each Summary contains a list of tf.Summary.Value protocol buffers, which each have a tag and a either a "simple" (floating-point scalar) value, an image, a histogram, or an audio snippet. For example, you can generate a scalar summary from a Python object as follows:

writer = tf.train.SummaryWriter(...)
value = 37.0
summary = tf.Summary(value=[
    tf.Summary.Value(tag="summary_tag", simple_value=value), 
])
writer.add_summary(summary)
7
  • 1
    How to create an Image Summary instead? Jun 28, 2016 at 9:00
  • 4
    I created a gist showing how to create image summaries: gist.github.com/gyglim/… Jan 4, 2017 at 10:04
  • 3
    tf.train.SummaryWriter is deprecated, instead use tf.summary.FileWriter Jul 3, 2017 at 16:07
  • 1
    How can you pass the current epoch to the summery as well? Jul 3, 2017 at 16:47
  • 1
    If you want to store the global step as well, use writer.add_summary(summary, global_step). Nov 20, 2017 at 13:20
6

If you want to log a python value you have to create a placeholder that have to be fed when running the tf.Summary op.

Here's a code snipped

value_ = tf.placeholder(tf.float32, [])
summary_op = tf.scalar_summary("value_log", value_)
my_python_variable = 10
# define everything else you need...
# ...
with tf.Session() as sess:
    for i in range(0, 10):
        sess.run(summary_op, feed_dict={value_: my_python_variable*i})
1
  • 2
    Thanks but I was explicitly asking for a way to directly create a Summary protobuf so that i could avoid this cumbersome method. Jun 19, 2016 at 16:07
4

I needed to do many updates to the custom summary variable during training so I implemented mine like so:

Before the loop:

writer = tf.summary.FileWriter(log_folder)
accuracy = None
accuracy_summary = tf.Summary()
accuracy_summary.value.add(tag='accuracy', simple_value=accuracy)

Inside the loop:

if i%20000 == 0:
    accuracy = get_accuracy()
    accuracy_summary.value[0].simple_value = accuracy
    writer.add_summary(accuracy_summary, i)

I'm assuming the indexes to value are in the order in which the variables were added to the summary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.