AttributeError: 'ResourceSummaryWriter' object has no attribute 'add_summary'

Viewed 1119

While trying to run the below part of the code, it is showing, AttributeError: ResourceSummaryWriter object has no attribute add_summary

def calc_running_avg_loss(loss, running_avg_loss, summary_writer, step, decay=0.99):
  if running_avg_loss == 0:  # on the first iteration just take the loss
    running_avg_loss = loss
  else:
    running_avg_loss = running_avg_loss * decay + (1 - decay) * loss
  running_avg_loss = min(running_avg_loss, 12)  # clip
  loss_sum = tf.compat.v1.Summary()
  tag_name = 'running_avg_loss/decay=%f' % (decay)
  loss_sum.value.add(tag=tag_name, simple_value=running_avg_loss)
  summary_writer.add_summary(loss_sum, step)
  return running_avg_loss

This is the code that calls the above function. And the self.summary_writer is initialized as self.summary_writer = tf.summary.create_file_writer(train_dir)

def trainIters(self, n_iters, model_file_path=None):
        iter, running_avg_loss = self.setup_train(model_file_path)
        start = time.time()
        while iter < n_iters:
            batch = self.batcher.next_batch()
            loss = self.train_one_batch(batch)

            running_avg_loss = calc_running_avg_loss(loss, running_avg_loss, self.summary_writer, iter)
            iter += 1

            if iter % 100 == 0:
                self.summary_writer.flush()
            print_interval = 2
            if iter % print_interval == 0:
                print('steps %d, seconds for %d batch: %.2f , loss: %f' % (iter, print_interval,
                                                                           time.time() - start, loss))
                start = time.time()
            if iter % 5000 == 0:
                self.save_model(running_avg_loss, iter)

Can someone please explain how to fix this error? PS: I don't have any prior experience with tensorflow and please correct if the question can be asked in a better way.

1 Answers

tf.compat.v1.summary.FileWriter has add_summary. This API is designed for Tensorflow v1. For more information visit add_summary

For Tensorflow v2, use tf.summary.create_file_writer .To know more about this API take a look here

Sample code

writer = tf.summary.create_file_writer("/tmp/mylogs/eager")

with writer.as_default():
  for step in range(100):
    # other model code would go here
    tf.summary.scalar("my_metric", 0.5, step=step)
    writer.flush()
Related