preloader
Python

Python tqdm

Python tqdm

Python으로 이런 저런 코드를 작성하다 보면 Progress bar가 필요한 경우가 있습니다. 제 경우에는 ML/DL 학습 부분에서 얼마나 학습이 되었는지…. 보기 위해 필요하죠.. keras, TensorFlow 같은 경우에는 특정 API에선 progress bar가 보이긴합니다.

하지만 PyTorch에는 .. 없죠. 직접 만들어야합니다.
(PyTorch Lightning 이라면 말이 다릅니다.)

그래서 이번엔 tqdm 이라는 라이브러리 사용법을 알아보고자 합니다.

기본 사용법

for loop를 사용할때 tqdm(iterable) 과 같이 사용하면 다음과 같은 출력을 얻을 수 있습니다.

import time
from tqdm import tqdm
for i in tqdm(range(1000)):
	time.sleep(0.01)

# 100%|████████████████████████████████████████████████████| 1000/1000 [00:15<00:00, 63.18it/s]

응용

tqdm의 출력으로 나오는 Progress bar 전체의 앞, 뒤에 특정 값을 넣을 수도 있습니다.

마치 keras, TensorFlow의 예시와 같이 Epoch, loss, accuracy을 넣을 수 있어요!

예시는 다음과 같습니다.

import time
from tqdm import tqdm

num_epochs = 5
for epoch in range(num_epochs):
    num_steps = 100
    with tqdm(desc=f'{epoch+1}/{num_epochs}', total=num_steps) as t:
        for i in range(num_steps):
            time.sleep(0.01)
            t.set_postfix({
                            "Accuracy": f"{i/num_steps:.2f}",
                            "Loss": f"{i/num_steps:.2f}"})
            t.update()

# 1/5: 100%|█████████████████████████████| 100/100 [00:01<00:00, 62.57it/s, Accuracy=0.99, Loss=0.99] 
# 2/5: 100%|█████████████████████████████| 100/100 [00:01<00:00, 62.76it/s, Accuracy=0.99, Loss=0.99] 
# 3/5: 100%|█████████████████████████████| 100/100 [00:01<00:00, 62.68it/s, Accuracy=0.99, Loss=0.99] 
# 4/5: 100%|█████████████████████████████| 100/100 [00:01<00:00, 62.81it/s, Accuracy=0.99, Loss=0.99] 
# 5/5: 100%|█████████████████████████████| 100/100 [00:01<00:00, 62.82it/s, Accuracy=0.99, Loss=0.99] 

오늘도 편리한 파이썬 라이브러리에 대해 간단히 알아보았습니다!

그럼 포스팅 끝!

P.S

  • 졸려요..!
  • 또 무슨 라이브러리가 있더라..
support-btn
도움이 되셨다면 몰랑이에게 밀크티를...!
더 다양한 포스팅을 채우도록 노력할게요!
comments powered by Disqus