add full review and auto upload notebooks/colab_gas_valve_auto_label_train.py
Browse files
notebooks/colab_gas_valve_auto_label_train.py
CHANGED
|
@@ -57,7 +57,7 @@
|
|
| 57 |
|
| 58 |
get_ipython().system(
|
| 59 |
"pip install -q ultralytics huggingface_hub opencv-python-headless "
|
| 60 |
-
"tqdm pyyaml matplotlib pandas"
|
| 61 |
)
|
| 62 |
|
| 63 |
import os
|
|
@@ -66,6 +66,7 @@ import time
|
|
| 66 |
import shutil
|
| 67 |
import random
|
| 68 |
import subprocess
|
|
|
|
| 69 |
from pathlib import Path
|
| 70 |
|
| 71 |
import cv2
|
|
@@ -132,6 +133,7 @@ DATASET_LOCAL = "/content/hf_11111"
|
|
| 132 |
RAW_VALVE_PREFIX = "raw/valve"
|
| 133 |
RAW_GAS_EXTRA_PREFIX = "raw/gas_extra"
|
| 134 |
REVIEWED_VALVE_LABEL_PREFIX = "reviewed_labels/valve"
|
|
|
|
| 135 |
PROCESS_SCRIPT_REPO_PATH = "scripts/process_valve_to_polygon.py"
|
| 136 |
FORCE_REDOWNLOAD = True
|
| 137 |
|
|
@@ -145,6 +147,7 @@ allow_patterns = [
|
|
| 145 |
f"{RAW_VALVE_PREFIX}/**",
|
| 146 |
f"{RAW_GAS_EXTRA_PREFIX}/**",
|
| 147 |
f"{REVIEWED_VALVE_LABEL_PREFIX}/**",
|
|
|
|
| 148 |
PROCESS_SCRIPT_REPO_PATH,
|
| 149 |
"dataset.yaml",
|
| 150 |
]
|
|
@@ -162,6 +165,7 @@ snapshot_download(
|
|
| 162 |
RAW_VALVE_DIR = base / RAW_VALVE_PREFIX
|
| 163 |
RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX
|
| 164 |
REVIEWED_VALVE_LABEL_DIR = base / REVIEWED_VALVE_LABEL_PREFIX
|
|
|
|
| 165 |
PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH
|
| 166 |
|
| 167 |
print("下载结果统计")
|
|
@@ -171,6 +175,7 @@ for p in [
|
|
| 171 |
RAW_VALVE_DIR,
|
| 172 |
RAW_GAS_EXTRA_DIR,
|
| 173 |
REVIEWED_VALVE_LABEL_DIR,
|
|
|
|
| 174 |
]:
|
| 175 |
n = len(list(p.glob("*"))) if p.exists() else 0
|
| 176 |
print(f" {p}: {n} entries")
|
|
@@ -575,7 +580,21 @@ def parse_exclude_keys(text: str) -> set[str]:
|
|
| 575 |
return keys
|
| 576 |
|
| 577 |
|
| 578 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
print(f"Excluded sample keys: {len(EXCLUDED_SAMPLE_KEYS)}")
|
| 580 |
for key in sorted(EXCLUDED_SAMPLE_KEYS):
|
| 581 |
print(f" {key}")
|
|
@@ -761,7 +780,10 @@ if DELETE_EXCLUDED_FROM_HF:
|
|
| 761 |
# %%
|
| 762 |
# @title Step 10 - 构建两类训练集
|
| 763 |
|
|
|
|
|
|
|
| 764 |
COMBINED_DATASET = Path("/content/gas_valve_dataset")
|
|
|
|
| 765 |
VAL_RATIO = 0.20 # 20% 做验证集,80% 做训练集。
|
| 766 |
RANDOM_SEED = 42 # 固定随机种子,方便复现实验。
|
| 767 |
INCLUDE_OLD_GAS_DATA = True # 保留原来的气瓶数据一起训练。
|
|
@@ -833,6 +855,8 @@ for img_path in list_images(RAW_VALVE_DIR):
|
|
| 833 |
})
|
| 834 |
|
| 835 |
excluded_keys = globals().get("EXCLUDED_SAMPLE_KEYS", set())
|
|
|
|
|
|
|
| 836 |
if excluded_keys:
|
| 837 |
before_filter = len(samples)
|
| 838 |
samples = [
|
|
@@ -863,6 +887,8 @@ for group in sorted({s["group"] for s in samples}):
|
|
| 863 |
rng.shuffle(train_samples)
|
| 864 |
rng.shuffle(val_samples)
|
| 865 |
|
|
|
|
|
|
|
| 866 |
|
| 867 |
def materialize(split: str, split_samples: list[dict]) -> None:
|
| 868 |
for idx, sample in enumerate(split_samples, 1):
|
|
@@ -872,10 +898,27 @@ def materialize(split: str, split_samples: list[dict]) -> None:
|
|
| 872 |
dst_lbl = COMBINED_DATASET / f"labels/{split}/{stem}.txt"
|
| 873 |
shutil.copy2(sample["image"], dst_img)
|
| 874 |
write_lines(dst_lbl, sample["lines"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 875 |
|
| 876 |
|
| 877 |
materialize("train", train_samples)
|
| 878 |
materialize("val", val_samples)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
|
| 880 |
YAML_PATH = COMBINED_DATASET / "dataset.yaml"
|
| 881 |
yaml_content = {
|
|
@@ -902,23 +945,29 @@ print(f" val images: {len(list_images(COMBINED_DATASET / 'images/val'))}")
|
|
| 902 |
print(f" val labels: {len(val_label_files)}")
|
| 903 |
print(f" train class counts: {class_counts(train_label_files)}")
|
| 904 |
print(f" val class counts: {class_counts(val_label_files)}")
|
|
|
|
| 905 |
print(YAML_PATH.read_text(encoding="utf-8"))
|
| 906 |
|
| 907 |
|
| 908 |
# %% [markdown]
|
| 909 |
# ---
|
| 910 |
-
# ## Step 11 -
|
| 911 |
|
| 912 |
|
| 913 |
# %%
|
| 914 |
-
# @title Step 11 -
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
|
| 916 |
-
|
|
|
|
| 917 |
img = read_image(img_path)
|
| 918 |
if img is None:
|
| 919 |
raise ValueError(f"Cannot read {img_path}")
|
| 920 |
h, w = img.shape[:2]
|
| 921 |
-
scale =
|
| 922 |
disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
|
| 923 |
dh, dw = disp.shape[:2]
|
| 924 |
colors = {
|
|
@@ -942,23 +991,184 @@ def draw_label_overlay(img_path: Path, label_path: Path) -> np.ndarray:
|
|
| 942 |
return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)
|
| 943 |
|
| 944 |
|
| 945 |
-
|
| 946 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 947 |
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 962 |
|
| 963 |
|
| 964 |
# %% [markdown]
|
|
@@ -978,6 +1188,7 @@ IMG_SIZE = 640 # YOLO 分割常用图片尺寸。
|
|
| 978 |
BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。
|
| 979 |
PATIENCE = 35 # 验证集 35 轮不提升就早停。
|
| 980 |
RUN_NAME = f"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}"
|
|
|
|
| 981 |
|
| 982 |
print("训练参数")
|
| 983 |
print(f" model: {TRAIN_MODEL}")
|
|
@@ -987,6 +1198,65 @@ print(f" imgsz: {IMG_SIZE}")
|
|
| 987 |
print(f" batch: {BATCH}")
|
| 988 |
print(f" run: {RUN_NAME}")
|
| 989 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 990 |
model = YOLO(TRAIN_MODEL)
|
| 991 |
t_start = time.time()
|
| 992 |
train_results = model.train(
|
|
@@ -1022,6 +1292,14 @@ print(f"训练完成,用时 {elapsed / 60:.1f} 分钟")
|
|
| 1022 |
print(f"Run dir: {RUN_DIR}")
|
| 1023 |
print(f"Best weights: {RUN_DIR / 'weights/best.pt'}")
|
| 1024 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1025 |
|
| 1026 |
# %% [markdown]
|
| 1027 |
# ---
|
|
@@ -1061,59 +1339,12 @@ for name in ["results.png", "confusion_matrix_normalized.png", "confusion_matrix
|
|
| 1061 |
|
| 1062 |
# %%
|
| 1063 |
# @title Step 14 - 上传训练结果
|
|
|
|
| 1064 |
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
UPLOAD_REPO_TYPE = "dataset"
|
| 1068 |
-
|
| 1069 |
-
if UPLOAD_TRAINING_RESULTS:
|
| 1070 |
-
upload_items = [
|
| 1071 |
-
"weights/best.pt",
|
| 1072 |
-
"weights/last.pt",
|
| 1073 |
-
"results.png",
|
| 1074 |
-
"results.csv",
|
| 1075 |
-
"args.yaml",
|
| 1076 |
-
"confusion_matrix_normalized.png",
|
| 1077 |
-
"confusion_matrix.png",
|
| 1078 |
-
"BoxP_curve.png",
|
| 1079 |
-
"BoxR_curve.png",
|
| 1080 |
-
"BoxF1_curve.png",
|
| 1081 |
-
"BoxPR_curve.png",
|
| 1082 |
-
"MaskP_curve.png",
|
| 1083 |
-
"MaskR_curve.png",
|
| 1084 |
-
"MaskF1_curve.png",
|
| 1085 |
-
"MaskPR_curve.png",
|
| 1086 |
-
]
|
| 1087 |
-
|
| 1088 |
-
operations = []
|
| 1089 |
-
for rel in upload_items:
|
| 1090 |
-
local_file = RUN_DIR / rel
|
| 1091 |
-
if not local_file.exists():
|
| 1092 |
-
continue
|
| 1093 |
-
operations.append(CommitOperationAdd(
|
| 1094 |
-
path_in_repo=f"runs/{RUN_NAME}/{rel}",
|
| 1095 |
-
path_or_fileobj=local_file.read_bytes(),
|
| 1096 |
-
))
|
| 1097 |
-
print(f"Prepared {rel}")
|
| 1098 |
|
| 1099 |
-
|
| 1100 |
-
path_in_repo=f"runs/{RUN_NAME}/dataset.yaml",
|
| 1101 |
-
path_or_fileobj=YAML_PATH.read_bytes(),
|
| 1102 |
-
))
|
| 1103 |
-
|
| 1104 |
-
if operations:
|
| 1105 |
-
api.create_commit(
|
| 1106 |
-
repo_id=UPLOAD_REPO,
|
| 1107 |
-
repo_type=UPLOAD_REPO_TYPE,
|
| 1108 |
-
token=HF_TOKEN,
|
| 1109 |
-
operations=operations,
|
| 1110 |
-
commit_message=f"Training_results_{RUN_NAME}",
|
| 1111 |
-
)
|
| 1112 |
-
print(f"Uploaded results to https://huggingface.co/datasets/{UPLOAD_REPO}/tree/main/runs/{RUN_NAME}")
|
| 1113 |
-
else:
|
| 1114 |
-
print("No result files found to upload")
|
| 1115 |
-
else:
|
| 1116 |
-
print("Skipping result upload")
|
| 1117 |
|
| 1118 |
|
| 1119 |
# %% [markdown]
|
|
|
|
| 57 |
|
| 58 |
get_ipython().system(
|
| 59 |
"pip install -q ultralytics huggingface_hub opencv-python-headless "
|
| 60 |
+
"tqdm pyyaml matplotlib pandas ipywidgets"
|
| 61 |
)
|
| 62 |
|
| 63 |
import os
|
|
|
|
| 66 |
import shutil
|
| 67 |
import random
|
| 68 |
import subprocess
|
| 69 |
+
import base64
|
| 70 |
from pathlib import Path
|
| 71 |
|
| 72 |
import cv2
|
|
|
|
| 133 |
RAW_VALVE_PREFIX = "raw/valve"
|
| 134 |
RAW_GAS_EXTRA_PREFIX = "raw/gas_extra"
|
| 135 |
REVIEWED_VALVE_LABEL_PREFIX = "reviewed_labels/valve"
|
| 136 |
+
CLEANING_PREFIX = "cleaning"
|
| 137 |
PROCESS_SCRIPT_REPO_PATH = "scripts/process_valve_to_polygon.py"
|
| 138 |
FORCE_REDOWNLOAD = True
|
| 139 |
|
|
|
|
| 147 |
f"{RAW_VALVE_PREFIX}/**",
|
| 148 |
f"{RAW_GAS_EXTRA_PREFIX}/**",
|
| 149 |
f"{REVIEWED_VALVE_LABEL_PREFIX}/**",
|
| 150 |
+
f"{CLEANING_PREFIX}/**",
|
| 151 |
PROCESS_SCRIPT_REPO_PATH,
|
| 152 |
"dataset.yaml",
|
| 153 |
]
|
|
|
|
| 165 |
RAW_VALVE_DIR = base / RAW_VALVE_PREFIX
|
| 166 |
RAW_GAS_EXTRA_DIR = base / RAW_GAS_EXTRA_PREFIX
|
| 167 |
REVIEWED_VALVE_LABEL_DIR = base / REVIEWED_VALVE_LABEL_PREFIX
|
| 168 |
+
CLEANING_DIR = base / CLEANING_PREFIX
|
| 169 |
PROCESS_SCRIPT_LOCAL = base / PROCESS_SCRIPT_REPO_PATH
|
| 170 |
|
| 171 |
print("下载结果统计")
|
|
|
|
| 175 |
RAW_VALVE_DIR,
|
| 176 |
RAW_GAS_EXTRA_DIR,
|
| 177 |
REVIEWED_VALVE_LABEL_DIR,
|
| 178 |
+
CLEANING_DIR,
|
| 179 |
]:
|
| 180 |
n = len(list(p.glob("*"))) if p.exists() else 0
|
| 181 |
print(f" {p}: {n} entries")
|
|
|
|
| 580 |
return keys
|
| 581 |
|
| 582 |
|
| 583 |
+
def read_exclude_keys_file(path: Path) -> set[str]:
|
| 584 |
+
if not path.exists():
|
| 585 |
+
return set()
|
| 586 |
+
return parse_exclude_keys(path.read_text(encoding="utf-8", errors="ignore"))
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
PERSISTED_EXCLUDE_PATH = CLEANING_DIR / "excluded_sample_keys.txt"
|
| 590 |
+
PERSISTED_EXCLUDED_SAMPLE_KEYS = read_exclude_keys_file(PERSISTED_EXCLUDE_PATH)
|
| 591 |
+
MANUAL_EXCLUDED_SAMPLE_KEYS = parse_exclude_keys(EXCLUDE_SAMPLE_KEYS)
|
| 592 |
+
EXCLUDED_SAMPLE_KEYS = PERSISTED_EXCLUDED_SAMPLE_KEYS | MANUAL_EXCLUDED_SAMPLE_KEYS
|
| 593 |
+
|
| 594 |
+
if PERSISTED_EXCLUDED_SAMPLE_KEYS:
|
| 595 |
+
print(f"HuggingFace 已保存排除样本: {len(PERSISTED_EXCLUDED_SAMPLE_KEYS)}")
|
| 596 |
+
if MANUAL_EXCLUDED_SAMPLE_KEYS:
|
| 597 |
+
print(f"本次手动填写排除样本: {len(MANUAL_EXCLUDED_SAMPLE_KEYS)}")
|
| 598 |
print(f"Excluded sample keys: {len(EXCLUDED_SAMPLE_KEYS)}")
|
| 599 |
for key in sorted(EXCLUDED_SAMPLE_KEYS):
|
| 600 |
print(f" {key}")
|
|
|
|
| 780 |
# %%
|
| 781 |
# @title Step 10 - 构建两类训练集
|
| 782 |
|
| 783 |
+
import pandas as pd
|
| 784 |
+
|
| 785 |
COMBINED_DATASET = Path("/content/gas_valve_dataset")
|
| 786 |
+
COMBINED_MANIFEST_PATH = COMBINED_DATASET / "training_manifest.csv"
|
| 787 |
VAL_RATIO = 0.20 # 20% 做验证集,80% 做训练集。
|
| 788 |
RANDOM_SEED = 42 # 固定随机种子,方便复现实验。
|
| 789 |
INCLUDE_OLD_GAS_DATA = True # 保留原来的气瓶数据一起训练。
|
|
|
|
| 855 |
})
|
| 856 |
|
| 857 |
excluded_keys = globals().get("EXCLUDED_SAMPLE_KEYS", set())
|
| 858 |
+
if "read_exclude_keys_file" in globals():
|
| 859 |
+
excluded_keys = set(excluded_keys) | read_exclude_keys_file(CLEANING_DIR / "excluded_sample_keys.txt")
|
| 860 |
if excluded_keys:
|
| 861 |
before_filter = len(samples)
|
| 862 |
samples = [
|
|
|
|
| 887 |
rng.shuffle(train_samples)
|
| 888 |
rng.shuffle(val_samples)
|
| 889 |
|
| 890 |
+
training_manifest_rows: list[dict] = []
|
| 891 |
+
|
| 892 |
|
| 893 |
def materialize(split: str, split_samples: list[dict]) -> None:
|
| 894 |
for idx, sample in enumerate(split_samples, 1):
|
|
|
|
| 898 |
dst_lbl = COMBINED_DATASET / f"labels/{split}/{stem}.txt"
|
| 899 |
shutil.copy2(sample["image"], dst_img)
|
| 900 |
write_lines(dst_lbl, sample["lines"])
|
| 901 |
+
training_manifest_rows.append({
|
| 902 |
+
"split": split,
|
| 903 |
+
"dataset_stem": stem,
|
| 904 |
+
"image_path": str(dst_img),
|
| 905 |
+
"label_path": str(dst_lbl),
|
| 906 |
+
"source_key": sample["source_key"],
|
| 907 |
+
"source": sample["source"],
|
| 908 |
+
"source_stem": sample["source_stem"],
|
| 909 |
+
"group": sample["group"],
|
| 910 |
+
"classes": ",".join(sorted({line.split()[0] for line in sample["lines"]})),
|
| 911 |
+
"objects": len(sample["lines"]),
|
| 912 |
+
})
|
| 913 |
|
| 914 |
|
| 915 |
materialize("train", train_samples)
|
| 916 |
materialize("val", val_samples)
|
| 917 |
+
pd.DataFrame(training_manifest_rows).to_csv(
|
| 918 |
+
COMBINED_MANIFEST_PATH,
|
| 919 |
+
index=False,
|
| 920 |
+
encoding="utf-8-sig",
|
| 921 |
+
)
|
| 922 |
|
| 923 |
YAML_PATH = COMBINED_DATASET / "dataset.yaml"
|
| 924 |
yaml_content = {
|
|
|
|
| 945 |
print(f" val labels: {len(val_label_files)}")
|
| 946 |
print(f" train class counts: {class_counts(train_label_files)}")
|
| 947 |
print(f" val class counts: {class_counts(val_label_files)}")
|
| 948 |
+
print(f" manifest: {COMBINED_MANIFEST_PATH}")
|
| 949 |
print(YAML_PATH.read_text(encoding="utf-8"))
|
| 950 |
|
| 951 |
|
| 952 |
# %% [markdown]
|
| 953 |
# ---
|
| 954 |
+
# ## Step 11 - 全量审核训练集并删除坏样本
|
| 955 |
|
| 956 |
|
| 957 |
# %%
|
| 958 |
+
# @title Step 11 - 全量审核训练集并删除坏样本
|
| 959 |
+
# @markdown 这一步会显示 train/val 全部样本。勾选错误样本后点击红色按钮,会从当前 Colab 训练集删除,并把排除清单保存到 HuggingFace。
|
| 960 |
+
|
| 961 |
+
from IPython.display import display
|
| 962 |
+
import ipywidgets as widgets
|
| 963 |
|
| 964 |
+
|
| 965 |
+
def draw_label_overlay(img_path: Path, label_path: Path, max_side: int = 720) -> np.ndarray:
|
| 966 |
img = read_image(img_path)
|
| 967 |
if img is None:
|
| 968 |
raise ValueError(f"Cannot read {img_path}")
|
| 969 |
h, w = img.shape[:2]
|
| 970 |
+
scale = max_side / max(w, h)
|
| 971 |
disp = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
|
| 972 |
dh, dw = disp.shape[:2]
|
| 973 |
colors = {
|
|
|
|
| 991 |
return cv2.cvtColor(disp, cv2.COLOR_BGR2RGB)
|
| 992 |
|
| 993 |
|
| 994 |
+
def overlay_data_url(img_path: Path, label_path: Path, max_side: int = 320) -> str:
|
| 995 |
+
rgb = draw_label_overlay(img_path, label_path, max_side=max_side)
|
| 996 |
+
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
|
| 997 |
+
ok, buf = cv2.imencode(".jpg", bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 82])
|
| 998 |
+
if not ok:
|
| 999 |
+
raise ValueError(f"Cannot encode overlay for {img_path}")
|
| 1000 |
+
encoded = base64.b64encode(buf.tobytes()).decode("ascii")
|
| 1001 |
+
return f"data:image/jpeg;base64,{encoded}"
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def write_persisted_exclusions(keys: set[str], selected_df: pd.DataFrame) -> tuple[Path, Path]:
|
| 1005 |
+
CLEANING_DIR.mkdir(parents=True, exist_ok=True)
|
| 1006 |
+
txt_path = CLEANING_DIR / "excluded_sample_keys.txt"
|
| 1007 |
+
csv_path = CLEANING_DIR / "excluded_sample_keys_latest.csv"
|
| 1008 |
+
|
| 1009 |
+
txt_path.write_text(
|
| 1010 |
+
"\n".join(sorted(keys)) + ("\n" if keys else ""),
|
| 1011 |
+
encoding="utf-8",
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
selected_out = selected_df[
|
| 1015 |
+
["source_key", "source", "source_stem", "group", "split", "dataset_stem"]
|
| 1016 |
+
].copy()
|
| 1017 |
+
selected_out["deleted_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 1018 |
+
selected_out.to_csv(csv_path, index=False, encoding="utf-8-sig")
|
| 1019 |
+
return txt_path, csv_path
|
| 1020 |
|
| 1021 |
+
|
| 1022 |
+
def upload_persisted_exclusions(txt_path: Path, csv_path: Path) -> None:
|
| 1023 |
+
api.upload_file(
|
| 1024 |
+
repo_id=DATASET_REPO,
|
| 1025 |
+
repo_type="dataset",
|
| 1026 |
+
token=HF_TOKEN,
|
| 1027 |
+
path_or_fileobj=str(txt_path),
|
| 1028 |
+
path_in_repo=f"{CLEANING_PREFIX}/excluded_sample_keys.txt",
|
| 1029 |
+
commit_message="update excluded training sample keys",
|
| 1030 |
+
)
|
| 1031 |
+
api.upload_file(
|
| 1032 |
+
repo_id=DATASET_REPO,
|
| 1033 |
+
repo_type="dataset",
|
| 1034 |
+
token=HF_TOKEN,
|
| 1035 |
+
path_or_fileobj=str(csv_path),
|
| 1036 |
+
path_in_repo=f"{CLEANING_PREFIX}/excluded_sample_keys_latest.csv",
|
| 1037 |
+
commit_message="update latest excluded training sample table",
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
if not COMBINED_MANIFEST_PATH.exists():
|
| 1042 |
+
raise FileNotFoundError(
|
| 1043 |
+
f"Missing {COMBINED_MANIFEST_PATH}. Please run Step 10 before Step 11."
|
| 1044 |
+
)
|
| 1045 |
+
|
| 1046 |
+
training_review_df = pd.read_csv(COMBINED_MANIFEST_PATH)
|
| 1047 |
+
training_review_df = training_review_df.sort_values(
|
| 1048 |
+
["split", "source", "source_key"]
|
| 1049 |
+
).reset_index(drop=True)
|
| 1050 |
+
|
| 1051 |
+
print(f"全量训练集样本数: {len(training_review_df)}")
|
| 1052 |
+
print(training_review_df.groupby(["split", "source"]).size().to_string())
|
| 1053 |
+
print("")
|
| 1054 |
+
print("绿色是 class 0 气瓶,橙蓝色是 class 1 阀门。确认有问题的样本后,勾选图片下方复选框。")
|
| 1055 |
+
|
| 1056 |
+
checkboxes: dict[int, widgets.Checkbox] = {}
|
| 1057 |
+
cards: list[widgets.Widget] = []
|
| 1058 |
+
|
| 1059 |
+
for idx, row in training_review_df.iterrows():
|
| 1060 |
+
img_path = Path(row["image_path"])
|
| 1061 |
+
lbl_path = Path(row["label_path"])
|
| 1062 |
+
if img_path.exists() and lbl_path.exists():
|
| 1063 |
+
img_html = (
|
| 1064 |
+
f"<img src='{overlay_data_url(img_path, lbl_path)}' "
|
| 1065 |
+
"style='width:260px; height:auto; display:block;'>"
|
| 1066 |
+
)
|
| 1067 |
+
else:
|
| 1068 |
+
img_html = "<div style='width:260px;height:160px;background:#eee;'>missing file</div>"
|
| 1069 |
+
|
| 1070 |
+
title = (
|
| 1071 |
+
"<div style='font-size:12px;line-height:1.35;"
|
| 1072 |
+
"font-family:Arial, sans-serif;word-break:break-all;'>"
|
| 1073 |
+
f"<b>{row['split']}</b> | {row['source_key']}<br>"
|
| 1074 |
+
f"{row['dataset_stem']} | class {row['classes']} | objects {row['objects']}"
|
| 1075 |
+
"</div>"
|
| 1076 |
+
)
|
| 1077 |
+
checkbox = widgets.Checkbox(
|
| 1078 |
+
value=False,
|
| 1079 |
+
description="删除这个样本",
|
| 1080 |
+
indent=False,
|
| 1081 |
+
layout=widgets.Layout(width="260px"),
|
| 1082 |
+
)
|
| 1083 |
+
checkboxes[idx] = checkbox
|
| 1084 |
+
cards.append(widgets.VBox(
|
| 1085 |
+
[
|
| 1086 |
+
widgets.HTML(title + img_html),
|
| 1087 |
+
checkbox,
|
| 1088 |
+
],
|
| 1089 |
+
layout=widgets.Layout(
|
| 1090 |
+
width="280px",
|
| 1091 |
+
border="1px solid #ddd",
|
| 1092 |
+
padding="6px",
|
| 1093 |
+
margin="4px",
|
| 1094 |
+
),
|
| 1095 |
+
))
|
| 1096 |
+
|
| 1097 |
+
delete_button = widgets.Button(
|
| 1098 |
+
description="删除勾选样本并保存到 HuggingFace",
|
| 1099 |
+
button_style="danger",
|
| 1100 |
+
layout=widgets.Layout(width="280px"),
|
| 1101 |
+
)
|
| 1102 |
+
summary_label = widgets.HTML(
|
| 1103 |
+
value="<b>操作提示:</b>删除后不用重新跑 Step 10,直接运行 Step 12 训练即可。"
|
| 1104 |
+
)
|
| 1105 |
+
delete_output = widgets.Output()
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
def on_delete_clicked(_button):
|
| 1109 |
+
selected_indices = [idx for idx, cb in checkboxes.items() if cb.value]
|
| 1110 |
+
with delete_output:
|
| 1111 |
+
delete_output.clear_output()
|
| 1112 |
+
if not selected_indices:
|
| 1113 |
+
print("没有勾选任何样本。")
|
| 1114 |
+
return
|
| 1115 |
+
|
| 1116 |
+
selected_df = training_review_df.loc[selected_indices].copy()
|
| 1117 |
+
selected_keys = set(selected_df["source_key"].astype(str))
|
| 1118 |
+
|
| 1119 |
+
existing_keys = set(globals().get("EXCLUDED_SAMPLE_KEYS", set()))
|
| 1120 |
+
if "read_exclude_keys_file" in globals():
|
| 1121 |
+
existing_keys |= read_exclude_keys_file(CLEANING_DIR / "excluded_sample_keys.txt")
|
| 1122 |
+
merged_keys = existing_keys | selected_keys
|
| 1123 |
+
|
| 1124 |
+
deleted_files = 0
|
| 1125 |
+
for _, selected_row in selected_df.iterrows():
|
| 1126 |
+
for col in ["image_path", "label_path"]:
|
| 1127 |
+
p = Path(selected_row[col])
|
| 1128 |
+
if p.exists():
|
| 1129 |
+
p.unlink()
|
| 1130 |
+
deleted_files += 1
|
| 1131 |
+
|
| 1132 |
+
remaining_df = training_review_df.drop(index=selected_indices).reset_index(drop=True)
|
| 1133 |
+
remaining_df.to_csv(COMBINED_MANIFEST_PATH, index=False, encoding="utf-8-sig")
|
| 1134 |
+
|
| 1135 |
+
txt_path, csv_path = write_persisted_exclusions(merged_keys, selected_df)
|
| 1136 |
+
globals()["EXCLUDED_SAMPLE_KEYS"] = merged_keys
|
| 1137 |
+
|
| 1138 |
+
print(f"当前 Colab 训练集已删除样本: {len(selected_df)}")
|
| 1139 |
+
print(f"删除 image/label 文件数: {deleted_files}")
|
| 1140 |
+
print(f"累计排除 source_key 数: {len(merged_keys)}")
|
| 1141 |
+
print(f"本地清单: {txt_path}")
|
| 1142 |
+
train_labels_now = list((COMBINED_DATASET / "labels/train").glob("*.txt"))
|
| 1143 |
+
val_labels_now = list((COMBINED_DATASET / "labels/val").glob("*.txt"))
|
| 1144 |
+
print(f"剩余 train 图片: {len(list_images(COMBINED_DATASET / 'images/train'))}")
|
| 1145 |
+
print(f"剩余 val 图片: {len(list_images(COMBINED_DATASET / 'images/val'))}")
|
| 1146 |
+
print(f"剩余 train 类别计数: {class_counts(train_labels_now)}")
|
| 1147 |
+
print(f"剩余 val 类别计数: {class_counts(val_labels_now)}")
|
| 1148 |
+
|
| 1149 |
+
try:
|
| 1150 |
+
upload_persisted_exclusions(txt_path, csv_path)
|
| 1151 |
+
print("HuggingFace 排除清单已保存。以后重新跑 Step 3-10 会自动排除这些样本。")
|
| 1152 |
+
except Exception as exc:
|
| 1153 |
+
print("HuggingFace 上传排除清单失败,但当前 Colab 训练集已经删除。")
|
| 1154 |
+
print(repr(exc))
|
| 1155 |
+
|
| 1156 |
+
for idx in selected_indices:
|
| 1157 |
+
checkboxes[idx].disabled = True
|
| 1158 |
+
|
| 1159 |
+
|
| 1160 |
+
delete_button.on_click(on_delete_clicked)
|
| 1161 |
+
|
| 1162 |
+
grid = widgets.GridBox(
|
| 1163 |
+
cards,
|
| 1164 |
+
layout=widgets.Layout(
|
| 1165 |
+
grid_template_columns="repeat(3, 300px)",
|
| 1166 |
+
grid_gap="8px",
|
| 1167 |
+
align_items="flex-start",
|
| 1168 |
+
),
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
display(widgets.VBox([summary_label, delete_button, delete_output, grid]))
|
| 1172 |
|
| 1173 |
|
| 1174 |
# %% [markdown]
|
|
|
|
| 1188 |
BATCH = -1 # 让 Ultralytics 自动选择显存能承受的 batch。
|
| 1189 |
PATIENCE = 35 # 验证集 35 轮不提升就早停。
|
| 1190 |
RUN_NAME = f"gas_valve_seg_reviewed_{time.strftime('%Y%m%d_%H%M')}"
|
| 1191 |
+
AUTO_UPLOAD_TRAINING_RESULTS = True
|
| 1192 |
|
| 1193 |
print("训练参数")
|
| 1194 |
print(f" model: {TRAIN_MODEL}")
|
|
|
|
| 1198 |
print(f" batch: {BATCH}")
|
| 1199 |
print(f" run: {RUN_NAME}")
|
| 1200 |
|
| 1201 |
+
|
| 1202 |
+
TRAINING_UPLOAD_ITEMS = [
|
| 1203 |
+
"weights/best.pt",
|
| 1204 |
+
"weights/last.pt",
|
| 1205 |
+
"results.png",
|
| 1206 |
+
"results.csv",
|
| 1207 |
+
"args.yaml",
|
| 1208 |
+
"confusion_matrix_normalized.png",
|
| 1209 |
+
"confusion_matrix.png",
|
| 1210 |
+
"BoxP_curve.png",
|
| 1211 |
+
"BoxR_curve.png",
|
| 1212 |
+
"BoxF1_curve.png",
|
| 1213 |
+
"BoxPR_curve.png",
|
| 1214 |
+
"MaskP_curve.png",
|
| 1215 |
+
"MaskR_curve.png",
|
| 1216 |
+
"MaskF1_curve.png",
|
| 1217 |
+
"MaskPR_curve.png",
|
| 1218 |
+
]
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
def upload_training_outputs(run_dir: Path, run_name: str) -> None:
|
| 1222 |
+
operations = []
|
| 1223 |
+
for rel in TRAINING_UPLOAD_ITEMS:
|
| 1224 |
+
local_file = run_dir / rel
|
| 1225 |
+
if not local_file.exists():
|
| 1226 |
+
continue
|
| 1227 |
+
operations.append(CommitOperationAdd(
|
| 1228 |
+
path_in_repo=f"runs/{run_name}/{rel}",
|
| 1229 |
+
path_or_fileobj=str(local_file),
|
| 1230 |
+
))
|
| 1231 |
+
print(f"准备上传: {rel}")
|
| 1232 |
+
|
| 1233 |
+
extra_files = [
|
| 1234 |
+
(YAML_PATH, "dataset.yaml"),
|
| 1235 |
+
(COMBINED_MANIFEST_PATH, "training_manifest.csv"),
|
| 1236 |
+
(CLEANING_DIR / "excluded_sample_keys.txt", "excluded_sample_keys.txt"),
|
| 1237 |
+
]
|
| 1238 |
+
for local_file, rel in extra_files:
|
| 1239 |
+
if local_file.exists():
|
| 1240 |
+
operations.append(CommitOperationAdd(
|
| 1241 |
+
path_in_repo=f"runs/{run_name}/{rel}",
|
| 1242 |
+
path_or_fileobj=str(local_file),
|
| 1243 |
+
))
|
| 1244 |
+
print(f"准备上传: {rel}")
|
| 1245 |
+
|
| 1246 |
+
if not operations:
|
| 1247 |
+
print("没有找到可上传的训练结果文件。")
|
| 1248 |
+
return
|
| 1249 |
+
|
| 1250 |
+
api.create_commit(
|
| 1251 |
+
repo_id=DATASET_REPO,
|
| 1252 |
+
repo_type="dataset",
|
| 1253 |
+
token=HF_TOKEN,
|
| 1254 |
+
operations=operations,
|
| 1255 |
+
commit_message=f"Training_results_{run_name}",
|
| 1256 |
+
)
|
| 1257 |
+
print(f"训练结果已上传: https://huggingface.co/datasets/{DATASET_REPO}/tree/main/runs/{run_name}")
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
model = YOLO(TRAIN_MODEL)
|
| 1261 |
t_start = time.time()
|
| 1262 |
train_results = model.train(
|
|
|
|
| 1292 |
print(f"Run dir: {RUN_DIR}")
|
| 1293 |
print(f"Best weights: {RUN_DIR / 'weights/best.pt'}")
|
| 1294 |
|
| 1295 |
+
if AUTO_UPLOAD_TRAINING_RESULTS:
|
| 1296 |
+
print("开始自动上传训练结果到 HuggingFace...")
|
| 1297 |
+
try:
|
| 1298 |
+
upload_training_outputs(RUN_DIR, RUN_NAME)
|
| 1299 |
+
except Exception as exc:
|
| 1300 |
+
print("自动上传失败。训练结果仍保存在当前 Colab 的 RUN_DIR,可以运行 Step 14 手动重传。")
|
| 1301 |
+
print(repr(exc))
|
| 1302 |
+
|
| 1303 |
|
| 1304 |
# %% [markdown]
|
| 1305 |
# ---
|
|
|
|
| 1339 |
|
| 1340 |
# %%
|
| 1341 |
# @title Step 14 - 上传训练结果
|
| 1342 |
+
# @markdown Step 12 训练完成后已经会自动上传。本步骤只用于自动上传失败后的手动重传。
|
| 1343 |
|
| 1344 |
+
if "RUN_DIR" not in globals() or "RUN_NAME" not in globals():
|
| 1345 |
+
raise RuntimeError("还没有训练结果。请先运行 Step 12。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1346 |
|
| 1347 |
+
upload_training_outputs(RUN_DIR, RUN_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1348 |
|
| 1349 |
|
| 1350 |
# %% [markdown]
|