Gabriele
Gabriele

Reputation: 949

How to customize the printed text in TensorFlow Keras progress bar?

Is it possible to customize the text appearning in TensorFlow's Keras progress bar? My current implementation and usage is the following (I use TensorFlow 2.8):

bar = tf.keras.utils.Progbar(target=n_train_samples)
step = 0
for x in dataset:
  train_step(x)
  step += 1
  bar.update(step * batch_size)

And the current behavior is:

 48/316 [===>..........................] - ETA: 1:19

However, I would like to print something like:

 TRAIN: 48/316 [===>..........................] - ETA: 1:19

Edit: I have also tried to print text before the progress bar, but then it gets overwritten. E.g. the code below:

import time
import tensorflow as tf

bar = tf.keras.utils.Progbar(target=10)
step = 0
for x in range(10):
    time.sleep(0.2)
    step += 1
    print("TRAIN: ", end="")
    bar.update(step)

returns the following output:

10/10 [==============================] - 5s 501ms/step

What I don't want to happen: I don't want to have prints on multiple lines. The progress bar should still update itself on the same line, just pre-appending "TRAIN" to it. So, at time step #3, I don't want:

 TRAIN: 
 1/10 [==>...........................] - ETA: 4s
 TRAIN: 
 2/10 [=====>........................] - ETA: 4s
 TRAIN: 
 3/10 [========>.....................] - ETA: 3s

but I want:

 TRAIN: 3/10 [========>.....................] - ETA: 3s

Upvotes: 1

Views: 572

Answers (2)

Antti Rytsölä
Antti Rytsölä

Reputation: 1545

Just print something with a few spaces in front and no LF in end. It'll save until overwritten, which is probably never.

now = datetime.datetime.now()
saveTime = now.strftime("%H:%M:%S")  # userfriendly now
print("        saved at ", saveTime, end='', flush=True)


Epoch: 3
21/98 [=====>........................] - ETA: 16:04 - total_loss: 83.5692 - rec_loss: 0.0669 - perc_loss: 0.7274 - smooth_loss: 0.2739 - warping_loss: 0.6828 - psnr: 19.1418 - ssim: 0.5147        saved at  12:22:03

Also, take note of your screen width.

Upvotes: 0

user11530462
user11530462

Reputation:

Resolved Code:

import time import tensorflow as tf

bar = tf.keras.utils.Progbar(target=10) step = 0

for x in range(10):
    print("\n TRAIN: ")
    time.sleep(0.5)
    step += 1
    bar.update(step)

Output:

TRAIN: 
 1/10 [==>...........................] - ETA: 4s
 TRAIN: 
 2/10 [=====>........................] - ETA: 4s
 TRAIN: 
 3/10 [========>.....................] - ETA: 3s
 TRAIN: 
 4/10 [===========>..................] - ETA: 3s
 TRAIN: 
 5/10 [==============>...............] - ETA: 2s
 TRAIN: 
 6/10 [=================>............] - ETA: 2s
 TRAIN: 
 7/10 [====================>.........] - ETA: 1s
 TRAIN: 
 8/10 [=======================>......] - ETA: 1s
 TRAIN: 
 9/10 [==========================>...] - ETA: 0s
 TRAIN: 
10/10 [==============================] - 5s 503ms/step

Upvotes: 1

Related Questions