Python: プログレスバーを表示する (tqdm)

tqdmを使ってプログレスバーを表示する方法について紹介します。

Kerasなどのフレームワークは良い感じにビジュアライズしてくれるのですが、自前の前処理などで進捗表示したい場合に便利です。

$ pip install tqdm

github.com

基本的にはシーケンスやイテレータをtqdmで括るだけでOKです。

from tqdm import tqdm
import time

for i in tqdm(range(10)):
    time.sleep(1)

こんな感じで表示されます。

今現在の値も一緒に表示したい (例えばloss) 場合、set_descriptionとset_postfixを使うと良いです。trange(10)はtqdm(ragen(10))と等価です。

from tqdm import trange

EPOCHS = 10

with trange(EPOCHS) as t:
    for i in t:
        # 左に表示
        t.set_description(f"EPOCH {i}")
        
        # 右に表示
        t.set_postfix(loss=1.0/(i+1), acc=i/10)
        
        time.sleep(1)

f:id:ohke:20190907142759p:plain

pandasのDataFrameにも適用できます。applyは往々にして時間のかかる処理を行いますが、以下のようにprogress_applyとすることで、applyの進捗状況も表示できます。

from tqdm import tqdm
import pandas as pd

tqdm.pandas()

df = pd.DataFrame({
    "column1": ["a", "b", "c", "d", "e"]
})

df.progress_apply(lambda r: time.sleep(5), axis=1)