SoFunction
Updated on 2024-11-19

The use of tqdm in python, for two different cases under for and while problem

python tqdm use, for two different cases under for and while

Using tqdm in while,for

About "while:"

使用while

About "for:"

使用for

reach a verdict

Progress bars appear in different forms

Three ways to draw a progress bar with tqdm

Introduction to tqdm

tqdm is a python progress bar library that adds a progress message to long Python loops.

3 ways to use

(range)-Automatic update

import time
from tqdm import range
# Automatic updates
for i in tqdm(range(10)): # A total of 10 progress bar updates are possible
    time. Sleep(0.5) # Interval between each update0.5s

range(10) means that the progress bar here can be updated 10 times, and since this is an automatic update here, one loop will update the progress bar by 1, with an interval of 0.5s between each update.

()-Automatic update

import time
from tqdm import trange
for i in trange(10):
    (0.5)

This one has the same effect as method 1.

3. Manual control of updates

from tqdm import tqdm
# With a with statement, the progress bar closes automatically when it's finished
with tqdm(total=10) as pbar:
    for i in range(10):
        time. Sleep(0.5)
        (1)
# Variables are created externally and manually closed at the end of the progress
phar = tqdm(total=100)
for i in range(100):
    (0.1)
    (1)
()

Here.total=10means that the progress bar here can be updated ten times, and since this is a manual update, you need to use the update() method.update(1) means update progress 1 at a time., with an interval of 0.5s between each update.

Application Examples

As an example of the use of method 3 in the code in question, the code could be written like this:

# Start training
for epoch in range(num_epochs):
    train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time. Time()
    with tqdm(total=468, desc="Epoch: %d" % epoch) as pbar:
        for idx, (X, y) in enumerate(train_iter, 0):
            X = (device)
            y = (device)
            y_hat = net(X)
            l = loss(y_hat, y).sum()
            optimizer.zero_grad()
            ()
            optimizer. Step()
            train_l_sum += ()
            train_acc_sum += (y_hat.argmax(dim=1) == y).float().sum().item()
            n += [0]
            (1) # One update of progress 1
        test_acc = evaluate_accuracy(test_iter, net)
        # Display relevant information on the progress bar
        pbar.set_postfix({
            'loss': '%.4f' % (train_l_sum / n),
            'train acc': '%.3f' % (train_acc_sum / n),
            'test acc': '%.3f' % test_acc ,
            'time': '%.1f time. () - start)
        })

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.