24

我正在使用 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
4

2 回答 2

31

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)
于 2018-02-22T20:09:13.357 回答
5

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

from tqdm import tqdm

# ...
for imgs, targets in tqdm( train_dataloader, total=len(train_dataloader)):
   # ...
于 2021-04-20T08:53:05.327 回答