python進度條元件
阿新 • • 發佈:2020-12-19
python 進度條元件
作者:elfin 資料來源:原創
1、在迴圈體中加入進度條
def save_txt(d, save_json="Data/train/"): my_bar1 = tqdm(d["annotations"]) for ann in my_bar1: my_bar1.set_description("annotations handle: ") image_id = ann.get("image_id") # 若不存在image_id就放棄此條資料 if type(image_id) != int: continue # 將annotations的資料整合成:{"img_id": [ann, ……]}的形式 if res.get(f"{image_id}"): res[f"{image_id}"].append(ann) else: res[f"{image_id}"] = [] res[f"{image_id}"].append(ann) # 撰寫最後的標註資料,形成{"filename": [ann, ……]}, 中間通過image_id進行對應 my_bar2 = tqdm(d["images"]) for img in my_bar2: my_bar2.set_description("Images_id filename >>> ") # 若當前image本身就包含了標註資料,則將這些 if img.get("annotations"): label_name = img.get("file_name").split(".")[0] result[f"{label_name}"] = { "annotations": img.get("annotations"), "width": img.get("width"), "height": img.get("height") } else: img_id = img.get("id") if res.get(str(img_id)): label_name = img.get("file_name").split(".")[0] result[f"{label_name}"] = { "annotations": res.get(str(img_id)), "width": img.get("width"), "height": img.get("height") } # 判斷儲存路徑是否存在 if not os.path.exists(PROJECT_DIR + save_json): os.makedirs(PROJECT_DIR + save_json) with open(PROJECT_DIR + save_json + "train_modify.json", "w+") as f2: json.dump(res, f2, indent=4, sort_keys=True, ensure_ascii=False) f2.close()
pycharm顯示的進度條:
annotations handle: : 100%|██████████| 3263046/3263046 [02:19<00:00, 23418.42it/s]
Images_id filename >>> : 100%|██████████| 335703/335703 [00:14<00:00, 23051.71it/s]
這裡我們設定了進度條的樣式,在實際應用中可以加入自己想展示的關鍵資訊。如模型訓練中加入損失:
import time from tqdm import tqdm batches = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] my_bar = tqdm(batches) batch_num = 0 for i in my_bar: loss = 2 * (1 / (1 + batch_num)**2) my_bar.set_description(f"epoch:{batch_num+1}/{len(batches)}\ttotal_loss: {loss}\t") batch_num += 1 time.sleep(1)
pycharm顯示的進度條:
epoch:4/4 total_loss: 0.125 : 100%|██████████| 4/4 [00:04<00:00, 1.00s/it]