tqdm 不显示栏

tqdm not showing bar

我使用的是 tqdm 库,它没有给我进度条,而是给我如下所示的输出,它只是告诉我迭代:

251it [01:44, 2.39it/s]

知道为什么代码会这样做吗?我想这可能是因为我给它传递了一个发电机,但我又一次使用了过去有效的发电机。我以前从来没有真正搞砸过 tdqm 格式。以下是部分源代码:

train_iter = zip(train_x, train_y) #train_x and train_y are just lists of elements
....
def train(train_iter, model, criterion, optimizer):
    model.train()
    total_loss = 0
    for x, y in tqdm(train_iter):
        x = x.transpose(0, 1)
        y = y.transpose(0, 1)
        optimizer.zero_grad()
        bloss = model.forward(x, y, criterion)   
        bloss.backward()
        torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)
        optimizer.step()        
        total_loss += bloss.data[0]
    return total_loss

tqdm 需要知道要执行多少升(总量)才能显示进度条。

你可以试试这个:

from tqdm import tqdm

train_x = range(100)
train_y = range(200)

train_iter = zip(train_x, train_y)

# Notice `train_iter` can only be iter over once, so i get `total` in this way.
total = min(len(train_x), len(train_y))

with tqdm(total=total) as pbar:
    for item in train_iter:
        # do something ...
        pbar.update(1)

用长度填充“总计”参数对我有用。现在进度条出现了。

from tqdm import tqdm

# ...
for imgs, targets in tqdm( train_dataloader, total=len(train_dataloader)):
   # ...