tqdm
is very versatile and can be used in a number of ways.
The three main ones are given below.
Wrap tqdm()
around any iterable:
text = ""
for char in tqdm(["a", "b", "c", "d"]):
text = text + char
trange(i)
is a special optimised instance of tqdm(range(i))
:
for i in trange(100):
pass
Instantiation outside of the loop allows for manual control over tqdm()
:
pbar = tqdm(["a", "b", "c", "d"])
for char in pbar:
pbar.set_description("Processing %s" % char)
Manual control on tqdm()
updates by using a with
statement:
with tqdm(total=100) as pbar:
for i in range(10):
pbar.update(10)
If the optional variable total
(or an iterable with len()
) is
provided, predictive stats are displayed.
with
is also optional (you can just assign tqdm()
to a variable,
but in this case don't forget to del
or close()
at the end:
pbar = tqdm(total=100)
for i in range(10):
pbar.update(10)
pbar.close()
num_steps = 10
loss_val = 0.1
# Use tqdm for progress bar
t = trange(num_steps)
for i in t:
time.sleep(0.1)
loss_val *= 0.1
# Log the loss in the tqdm progress bar
t.set_postfix(loss='{:05.3f}'.format(loss_val))
def my_generator0(n):
for i in range(1, 100):
time.sleep(0.1)
yield i
if i > n-1:
return
dataloader = my_generator0(10)
with tqdm(total=10) as t:
for labels_batch in dataloader:
loss_avg = labels_batch * 0.1
# Log the loss in the tqdm progress bar
t.set_postfix(loss='{:05.3f}'.format(loss_avg))
t.update()
100%|██████| 10/10 [00:01<00:00, 9.97it/s, loss=0.000]
100%|██████| 10/10 [00:01<00:00, 9.97it/s, loss=1.000]
set_description
vs.set_postfix