Show progress bar for each epoch during batchwise training in Keras

Question:

When I load the whole dataset in memory and train the network in Keras using following code:

model.fit(X, y, nb_epoch=40, batch_size=32, validation_split=0.2, verbose=1)

This generates a progress bar per epoch with metrics like ETA, accuracy, loss, etc

When I train the network in batches, I’m using the following code

for e in range(40):
        for X, y in data.next_batch():
            model.fit(X, y, nb_epoch=1, batch_size=data.batch_size, verbose=1)

This will generate a progress bar for each batch instead of each epoch. Is it possible to generate a progress bar for each epoch during batchwise training?

Asked By: Anish Shah

||

Answers:

model.fit(X, y, nb_epoch=40, batch_size=32, validation_split=0.2, verbose=1)

In the above change to verbose=2, as it is mentioned in the documentation:

verbose: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch

It’ll show your output as:

Epoch 1/100
0s - loss: 0.2506 - acc: 0.5750 - val_loss: 0.2501 - val_acc: 0.3750
Epoch 2/100
0s - loss: 0.2487 - acc: 0.6250 - val_loss: 0.2498 - val_acc: 0.6250
Epoch 3/100
0s - loss: 0.2495 - acc: 0.5750 - val_loss: 0.2496 - val_acc: 0.6250
.....
.....

If you want to show a progress bar for completion of epochs, keep verbose=0 (which shuts out logging to stdout) and implement in the following manner:

from time import sleep
import sys

epochs = 10

for e in range(epochs):
    sys.stdout.write('r')

    for X, y in data.next_batch():
        model.fit(X, y, nb_epoch=1, batch_size=data.batch_size, verbose=0)

    # print loss and accuracy

    # the exact output you're looking for:
    sys.stdout.write("[%-60s] %d%%" % ('='*(60*(e+1)/10), (100*(e+1)/10)))
    sys.stdout.flush()
    sys.stdout.write(", epoch %d"% (e+1))
    sys.stdout.flush()

The output will be as follows:

[============================================================] 100%, epoch 10

If you want to show loss after every n batches, you can use:

out_batch = NBatchLogger(display=1000)
model.fit([X_train_aux,X_train_main],Y_train,batch_size=128,callbacks=[out_batch])

Though, I haven’t ever tried it before. The above example was taken from this keras github issue: Show Loss Every N Batches #2850

You can also follow a demo of NBatchLogger here:

class NBatchLogger(Callback):
    def __init__(self, display):
        self.seen = 0
        self.display = display

    def on_batch_end(self, batch, logs={}):
        self.seen += logs.get('size', 0)
        if self.seen % self.display == 0:
            metrics_log = ''
            for k in self.params['metrics']:
                if k in logs:
                    val = logs[k]
                    if abs(val) > 1e-3:
                        metrics_log += ' - %s: %.4f' % (k, val)
                    else:
                        metrics_log += ' - %s: %.4e' % (k, val)
            print('{}/{} ... {}'.format(self.seen,
                                        self.params['samples'],
                                        metrics_log))

You can also use progbar for progress, but it’ll print progress batchwise

from keras.utils import generic_utils

progbar = generic_utils.Progbar(X_train.shape[0])

for X_batch, Y_batch in datagen.flow(X_train, Y_train):
    loss, acc = model_test.train([X_batch]*2, Y_batch, accuracy=True)
    progbar.add(X_batch.shape[0], values=[("train loss", loss), ("acc", acc)])
Answered By: Abhijay Ghildyal

you can set verbose=0 and set callbacks that will update progress at the end of each fitting,

clf.fit(X, y, nb_epoch=1, batch_size=data.batch_size, verbose=0, callbacks=[some_callback])

https://keras.io/callbacks/#example-model-checkpoints

or set callback https://keras.io/callbacks/#remotemonitor

Answered By: quester

tqdm (version >= 4.41.0) has also just added built-in support for keras so you could do:

from tqdm.keras import TqdmCallback
...
model.fit(..., verbose=0, callbacks=[TqdmCallback(verbose=2)])

This turns off keras‘ progress (verbose=0), and uses tqdm instead. For the callback, verbose=2 means separate progressbars for epochs and batches. 1 means clear batch bars when done. 0 means only show epochs (never show batch bars).

Answered By: casper.dcl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.