tqdmでプログレスバーの隣に標準出力する

いい感じのプログレスバーを作ってくれるPythonのライブラリであるtqdmで,プログレスバーの隣に標準出力を更新し続ける方法.

github.com

tqdm means "progress" in Arabic (taqadum, تقدّم) and is an abbreviation for "I love you so much" in Spanish (te quiero demasiado). Instantly make your loops show a smart progress meter - just wrap any iterable with tqdm(iterable), and you're done!

これは,tqdmで用意されているset_postfix関数を使うことで実現できる.

実装例

  • ループの外側をtqdmで包んで,そのなかでset_postfixを呼ぶ.
  • 引数はOrderedDict
for epoch in range(n_epochs):
    with tqdm(self.train_loader, ncols=100) as pbar:
        for idx, (inputs, targets) in enumerate(pbar):
            optimizer.zero_grad()

            outputs = network(inputs)

            loss = self.criterion(outputs, targets)
            loss.backward()
            self.optimizer.step()

            pbar.set_postfix(OrderedDict(
                epoch="{:>10}".format(epoch),
                loss="{:.4f}".format(loss.item())))

出力例

f:id:noconocolib:20190301021249g:plain

いい感じに出力できてる.