Article directory
提示:以下是本篇文章正文内容,下面案例可供参考
1. Basic knowledge of tqdm
"tqdm" is a Python library for creating progress bars in the command line interface.
The basic usage is as follows:
from tqdm import tqdm
import time
items = range(10)
for item in tqdm(items, desc="Test", total=len(items)):
time.sleep(1)
The documentation is as follows:
Only the three parameters passed in are introduced: iterable, desc, total
iterable: is an iterable object
desc: descriptive information before the progress bar
total: the length of the iterable object.
The results are as follows:
you can see that there is descriptive Information, progress bar, how much time has been running, how much time is left, and speed. You can also add a suffix description later, see below.
2. Use tqdm in pytorch
Generally, tqdm is used in the train function. Dataloader is passed into tqdm as an iterable object.
loop = tqdm((dataloader_train), desc=f"Epoch: [{
epoch}/20]", total=len(dataloader_train))
for img, label in loop:
img = img.to(device)
label = label.to(device)
output = model(img)
optimizer.zero_grad()
loss = criterion(output,label)
loss.backward()
optimizer.step()
train_loss += loss.item()
correct += (torch.argmax(output,dim=1) == label).sum().item()
loop.set_postfix(loss=loss.item() / label.shape[0])
print("epoch: {i} Train Loss: {loss}".format(i=epoch, loss=train_loss))
print("epoch: {i} Train Accuracy: {acc}".format(i=epoch, acc=correct / len(dataset_train)))