Python tqdm的两种用法【教程】

Python tqdm的两种用法

本文记录一下在学习深度强化学习过程中遇到tqdm库显示进度条的用法,以供大家交流。

注意本文使用的tqdm均是使用的tqdm库中的同名tqdm方法,应该按照如下方式导入

python 复制代码
from tqdm import tqdm

Catologue

  • [Python tqdm的两种用法](#Python tqdm的两种用法)
    • [1. 基于可迭代的用法 (Iterable-based)](#1. 基于可迭代的用法 (Iterable-based))
    • [2. 手动方式的用法(Manual)](#2. 手动方式的用法(Manual))
    • Reference

1. 基于可迭代的用法 (Iterable-based)

该种用法比较简单,直接使用tqdm包裹可迭代对象即可,例如

python 复制代码
from tqdm import tqdm
import time

for _ in  tqdm(range(30)):
    time.sleep(0.1)

结果如下

bash 复制代码
100%|██████████| 30/30 [00:03<00:00,  9.20it/s]

循环外部的实例化允许手动​​控制 tqdm()

python 复制代码
from tqdm import tqdm
import time
pbar = tqdm(["a", "b", "c", "d"])

for char in pbar:
    time.sleep(0.25)
    pbar.set_description("Processing %s" % char)

结果如下

bash 复制代码
Processing d: 100%|██████████| 4/4 [00:01<00:00,  3.83it/s]

2. 手动方式的用法(Manual)

利用python中的上下文管理器with来手动使用tqdm,其中初始化参数如下

python 复制代码
def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
                 ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
                 ascii=None, disable=False, unit='it', unit_scale=False,
                 dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
                 position=None, postfix=None, unit_divisor=1000, write_bytes=False,
                 lock_args=None, nrows=None, colour=None, delay=0, gui=False,
                 **kwargs):
        """
        Parameters
        ----------
        iterable  : iterable, optional
            Iterable to decorate with a progressbar.
            Leave blank to manually manage the updates.
        desc  : str, optional
            Prefix for the progressbar. 设置进度条的描述
        total  : int or float, optional 进度条总长
            The number of expected iterations. If unspecified,
            len(iterable) is used if possible. If float("inf") or as a last
            resort, only basic progress statistics are displayed
            (no ETA, no progressbar).
            If `gui` is True and this parameter needs subsequent updating,
            specify an initial arbitrary large positive number,
            e.g. 9e9.
        leave  : bool, optional
            If [default: True], keeps all traces of the progressbar
            upon termination of iteration.
            If `None`, will leave only if `position` is `0`.

例如

python 复制代码
from tqdm import tqdm
import time

with tqdm(total=100) as pbar:	#进度条总长100%

    for i in range(10):
        time.sleep(0.1)
        pbar.update(10)	#每次更新进度条10%

结果如下

python 复制代码
100%|██████████| 100/100 [00:01<00:00, 91.47it/s]

再例如,同时保留多个进度条,其中在使用 tqdm 库时,set_postfix 方法用于在进度条中显示附加信息。它允许在进度条的右侧显示一些额外的信息,比如当前迭代的一些指标或状态。

set_postfix 方法可以接受一个字典作为参数,其中键值对表示要显示的附加信息。调用此方法后,进度条会更新并在右侧显示传入的信息。

python 复制代码
from tqdm import tqdm
import time
num_episodes = 100 #最大的迭代次数
num_tqdm = 10 #进度条的数量
for i in range(num_tqdm):
    with tqdm(total= num_episodes/num_tqdm, desc="Iteration %d" %i) as pbar:
        for i_episode in range(int(num_episodes/num_tqdm)):
            time.sleep(0.1)
            pbar.update(1)	# 更新一次tqdm
            if (i_episode+1) % 10 == 0:
            # tqdm控制输出
                pbar.set_postfix({
                    "episode": "%d"%(num_episodes / num_tqdm * i + i_episode + 1) 
                })

结果如下

bash 复制代码
Iteration 0: 100%|██████████| 10/10.0 [00:01<00:00,  9.15it/s, episode=10]
Iteration 1: 100%|██████████| 10/10.0 [00:01<00:00,  9.17it/s, episode=20]
Iteration 2: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=30]
Iteration 3: 100%|██████████| 10/10.0 [00:01<00:00,  9.18it/s, episode=40]
Iteration 4: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=50]
Iteration 5: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=60]
Iteration 6: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=70]
Iteration 7: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=80]
Iteration 8: 100%|██████████| 10/10.0 [00:01<00:00,  9.24it/s, episode=90]
Iteration 9: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=100]

Reference

tqdm官方github

相关推荐
夜雪一千2 小时前
Python 如何实现 SHA 加密?SHA1 / SHA256 / SHA512 实战教程
开发语言·python
码云骑士2 小时前
106-模型量化技术-GGUF-GPTQ-AWQ-bitsandbytes对比
python
御风之翼_唤星者2 小时前
LoadFramePackModel模块报错bad escape
python·ai
雪隐2 小时前
个人电脑玩AI-16让5060 Ti给你打工——5060Ti 16G 跑 MiniMax-Music-3:从下载到 60s 出歌的全流程
前端·人工智能·后端
民乐团扒谱机2 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
小白勇闯网安圈3 小时前
Django Ajax、批量操作与分页实践
python·django
Logintern093 小时前
Langgraph使用MemorySaver建立有记忆的图
开发语言·windows·python
counting money3 小时前
Spring AI Alibaba 从入门到实战:构建企业级 AI 应用
java·人工智能·spring
CAD老兵3 小时前
让 AI Coding Agent 直接访问 CAD 文档:GitMCP 实战指南
前端·人工智能·github
原野池予3 小时前
深入Java集合框架:数组与List互转底层原理剖析(JDK 8)
java·数据结构·list