yolo-dataset-toolkit 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ydt/__init__.py +24 -0
- ydt/__main__.py +4 -0
- ydt/audit.py +485 -0
- ydt/cli.py +263 -0
- ydt/converters.py +425 -0
- ydt/dataset.py +286 -0
- ydt/demo.py +90 -0
- ydt/report.py +200 -0
- ydt/split.py +199 -0
- yolo_dataset_toolkit-0.3.0.dist-info/METADATA +267 -0
- yolo_dataset_toolkit-0.3.0.dist-info/RECORD +15 -0
- yolo_dataset_toolkit-0.3.0.dist-info/WHEEL +5 -0
- yolo_dataset_toolkit-0.3.0.dist-info/entry_points.txt +2 -0
- yolo_dataset_toolkit-0.3.0.dist-info/licenses/LICENSE +21 -0
- yolo_dataset_toolkit-0.3.0.dist-info/top_level.txt +1 -0
ydt/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""ydt —— YOLO 数据集工具链(体检 / 转换 / 切分)。
|
|
2
|
+
|
|
3
|
+
from ydt import audit, split
|
|
4
|
+
|
|
5
|
+
result = audit.audit("datasets/fruit")
|
|
6
|
+
print(result.verdict, result.instances)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.3.0"
|
|
10
|
+
|
|
11
|
+
from . import audit, converters, dataset, split # noqa: E402,F401
|
|
12
|
+
from .converters import coco_to_yolo, labelme_to_yolo, voc_to_yolo, yolo_seg_to_box # noqa: E402,F401
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"__version__",
|
|
16
|
+
"audit",
|
|
17
|
+
"converters",
|
|
18
|
+
"dataset",
|
|
19
|
+
"split",
|
|
20
|
+
"coco_to_yolo",
|
|
21
|
+
"voc_to_yolo",
|
|
22
|
+
"labelme_to_yolo",
|
|
23
|
+
"yolo_seg_to_box",
|
|
24
|
+
]
|
ydt/__main__.py
ADDED
ydt/audit.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"""数据集审计:把训练前的坑一次性查出来。
|
|
2
|
+
|
|
3
|
+
检查项:
|
|
4
|
+
无标注图片 / 空标签 / 孤立标签 / 坏行
|
|
5
|
+
框越界 / 超小框 / 极端长宽比 / 未知类别 / nc 与 names 数量
|
|
6
|
+
重复图片(感知哈希),并单独判定**同一张图跨 train/val 泄漏**
|
|
7
|
+
多边形标签按任务判定(task=detect 报错,task=seg 视为正常)
|
|
8
|
+
类别不平衡 / 图片尺寸分布
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections import Counter, defaultdict
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from PIL import Image
|
|
19
|
+
|
|
20
|
+
from . import dataset as ds
|
|
21
|
+
|
|
22
|
+
TINY_AREA = 0.001 # 相对面积小于 0.1% 视为超小框(640 输入下不足 20 像素)
|
|
23
|
+
EXTREME_RATIO = 8.0 # 宽高比超过 8:1 视为异常
|
|
24
|
+
IMBALANCE_RATIO = 5.0 # 最多类 / 最少类 超过 5 倍提示不平衡
|
|
25
|
+
BOUND_EPS = 1e-6
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Issue:
|
|
30
|
+
level: str # error / warn
|
|
31
|
+
kind: str
|
|
32
|
+
title: str
|
|
33
|
+
count: int
|
|
34
|
+
advice: str
|
|
35
|
+
examples: list[str] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class AuditResult:
|
|
40
|
+
root: Path
|
|
41
|
+
images: int = 0
|
|
42
|
+
label_files: int = 0
|
|
43
|
+
instances: int = 0
|
|
44
|
+
class_counts: dict[int, int] = field(default_factory=dict)
|
|
45
|
+
class_names: dict[int, str] = field(default_factory=dict)
|
|
46
|
+
missing_labels: int = 0
|
|
47
|
+
empty_labels: int = 0
|
|
48
|
+
orphan_labels: int = 0
|
|
49
|
+
bad_lines: int = 0
|
|
50
|
+
polygon_lines: int = 0
|
|
51
|
+
out_of_bounds: int = 0
|
|
52
|
+
tiny_boxes: int = 0
|
|
53
|
+
extreme_ratios: int = 0
|
|
54
|
+
unknown_classes: int = 0
|
|
55
|
+
duplicate_groups: int = 0
|
|
56
|
+
duplicate_images: int = 0
|
|
57
|
+
cross_split_leaks: int = 0
|
|
58
|
+
detect_rows: int = 0
|
|
59
|
+
nc_mismatch: int = 0
|
|
60
|
+
sizes: Counter = field(default_factory=Counter)
|
|
61
|
+
split_counts: dict[str, int] = field(default_factory=dict)
|
|
62
|
+
issues: list[Issue] = field(default_factory=list)
|
|
63
|
+
elapsed: float = 0.0
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def has_error(self) -> bool:
|
|
67
|
+
return any(issue.level == "error" and issue.count for issue in self.issues)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def has_warning(self) -> bool:
|
|
71
|
+
return any(issue.level == "warn" and issue.count for issue in self.issues)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def verdict(self) -> str:
|
|
75
|
+
if self.has_error:
|
|
76
|
+
return "FAIL"
|
|
77
|
+
if self.has_warning:
|
|
78
|
+
return "WARN"
|
|
79
|
+
return "PASS"
|
|
80
|
+
|
|
81
|
+
def to_dict(self) -> dict[str, Any]:
|
|
82
|
+
return {
|
|
83
|
+
"root": str(self.root),
|
|
84
|
+
"images": self.images,
|
|
85
|
+
"label_files": self.label_files,
|
|
86
|
+
"instances": self.instances,
|
|
87
|
+
"classes": len(self.class_counts),
|
|
88
|
+
"class_counts": {self.class_names.get(k, str(k)): v for k, v in self.class_counts.items()},
|
|
89
|
+
"missing_labels": self.missing_labels,
|
|
90
|
+
"empty_labels": self.empty_labels,
|
|
91
|
+
"orphan_labels": self.orphan_labels,
|
|
92
|
+
"bad_lines": self.bad_lines,
|
|
93
|
+
"polygon_lines": self.polygon_lines,
|
|
94
|
+
"out_of_bounds": self.out_of_bounds,
|
|
95
|
+
"tiny_boxes": self.tiny_boxes,
|
|
96
|
+
"extreme_ratios": self.extreme_ratios,
|
|
97
|
+
"unknown_classes": self.unknown_classes,
|
|
98
|
+
"duplicate_groups": self.duplicate_groups,
|
|
99
|
+
"duplicate_images": self.duplicate_images,
|
|
100
|
+
"cross_split_leaks": self.cross_split_leaks,
|
|
101
|
+
"detect_rows": self.detect_rows,
|
|
102
|
+
"nc_mismatch": self.nc_mismatch,
|
|
103
|
+
"sizes": {f"{w}x{h}": n for (w, h), n in self.sizes.most_common(10)},
|
|
104
|
+
"splits": self.split_counts,
|
|
105
|
+
"verdict": self.verdict,
|
|
106
|
+
"issues": [
|
|
107
|
+
{
|
|
108
|
+
"level": i.level,
|
|
109
|
+
"kind": i.kind,
|
|
110
|
+
"title": i.title,
|
|
111
|
+
"count": i.count,
|
|
112
|
+
"advice": i.advice,
|
|
113
|
+
"examples": i.examples,
|
|
114
|
+
}
|
|
115
|
+
for i in self.issues
|
|
116
|
+
],
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def audit(
|
|
121
|
+
root: str | Path,
|
|
122
|
+
*,
|
|
123
|
+
hash_images: bool = True,
|
|
124
|
+
max_examples: int = 5,
|
|
125
|
+
task: str = "detect",
|
|
126
|
+
tiny_area: float = TINY_AREA,
|
|
127
|
+
max_aspect: float = EXTREME_RATIO,
|
|
128
|
+
imbalance_ratio: float = IMBALANCE_RATIO,
|
|
129
|
+
) -> AuditResult:
|
|
130
|
+
"""体检一个 YOLO 数据集。
|
|
131
|
+
|
|
132
|
+
task="detect"(默认)时多边形标签视为错误;task="seg" 时多边形视为正常,
|
|
133
|
+
反而把纯检测行(5 列)提示出来,因为分割训练读不了它。
|
|
134
|
+
tiny_area / max_aspect / imbalance_ratio 可按数据集特性放宽。
|
|
135
|
+
"""
|
|
136
|
+
if task not in {"detect", "seg"}:
|
|
137
|
+
raise ValueError(f"task 只支持 detect / seg,收到:{task}")
|
|
138
|
+
if not 0 < tiny_area <= 1:
|
|
139
|
+
raise ValueError("tiny_area 必须落在 (0, 1] 之间")
|
|
140
|
+
if max_aspect < 1:
|
|
141
|
+
raise ValueError("max_aspect 必须 >= 1")
|
|
142
|
+
if imbalance_ratio < 1:
|
|
143
|
+
raise ValueError("imbalance_ratio 必须 >= 1")
|
|
144
|
+
|
|
145
|
+
data = ds.load(root)
|
|
146
|
+
result = AuditResult(root=data.root, class_names=dict(data.names))
|
|
147
|
+
result.images = len(data.images)
|
|
148
|
+
result.split_counts = {k: len(v) for k, v in data.splits.items()}
|
|
149
|
+
|
|
150
|
+
missing = empty = bad = oob = tiny = ratio = unknown = 0
|
|
151
|
+
polygon_total = polygon_error = detect_rows = 0
|
|
152
|
+
class_counts: Counter[int] = Counter()
|
|
153
|
+
sizes: Counter[tuple[int, int]] = Counter()
|
|
154
|
+
|
|
155
|
+
missing_examples: list[str] = []
|
|
156
|
+
empty_examples: list[str] = []
|
|
157
|
+
bad_examples: list[str] = []
|
|
158
|
+
oob_examples: list[str] = []
|
|
159
|
+
tiny_examples: list[str] = []
|
|
160
|
+
ratio_examples: list[str] = []
|
|
161
|
+
unknown_examples: list[str] = []
|
|
162
|
+
polygon_examples: list[str] = []
|
|
163
|
+
detect_examples: list[str] = []
|
|
164
|
+
|
|
165
|
+
for image in data.images:
|
|
166
|
+
label = data.label_path(image)
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
with Image.open(image) as im:
|
|
170
|
+
sizes[im.size] += 1
|
|
171
|
+
except Exception:
|
|
172
|
+
sizes[("unreadable", 0)] += 1 # 图片损坏,单独落进尺寸表里
|
|
173
|
+
continue
|
|
174
|
+
|
|
175
|
+
if not label.exists():
|
|
176
|
+
missing += 1
|
|
177
|
+
_add_example(missing_examples, _rel(image, data.root), max_examples)
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
boxes, malformed = ds.parse_label_file(label)
|
|
181
|
+
result.label_files += 1
|
|
182
|
+
|
|
183
|
+
if malformed:
|
|
184
|
+
bad += len(malformed)
|
|
185
|
+
_add_example(bad_examples, _rel(label, data.root), max_examples, note=f"{len(malformed)} 行")
|
|
186
|
+
|
|
187
|
+
if not boxes and not malformed:
|
|
188
|
+
empty += 1
|
|
189
|
+
_add_example(empty_examples, _rel(label, data.root), max_examples)
|
|
190
|
+
|
|
191
|
+
for box in boxes:
|
|
192
|
+
result.instances += 1
|
|
193
|
+
class_counts[box.cls] += 1
|
|
194
|
+
|
|
195
|
+
if box.points:
|
|
196
|
+
polygon_total += 1
|
|
197
|
+
if task == "detect":
|
|
198
|
+
polygon_error += 1
|
|
199
|
+
_add_example(polygon_examples, f"{_rel(label, data.root)}:{box.line_no}({box.points} 点)", max_examples)
|
|
200
|
+
elif task == "seg":
|
|
201
|
+
# 分割任务读不了 5 列检测行,训练时同样会丢,只是方向相反
|
|
202
|
+
detect_rows += 1
|
|
203
|
+
_add_example(detect_examples, f"{_rel(label, data.root)}:{box.line_no}", max_examples)
|
|
204
|
+
|
|
205
|
+
if data.names and box.cls not in data.names:
|
|
206
|
+
unknown += 1
|
|
207
|
+
_add_example(unknown_examples, f"{label.name}:{box.line_no} cls={box.cls}", max_examples)
|
|
208
|
+
|
|
209
|
+
half_w, half_h = box.w / 2, box.h / 2
|
|
210
|
+
if (
|
|
211
|
+
box.x - half_w < -BOUND_EPS
|
|
212
|
+
or box.x + half_w > 1 + BOUND_EPS
|
|
213
|
+
or box.y - half_h < -BOUND_EPS
|
|
214
|
+
or box.y + half_h > 1 + BOUND_EPS
|
|
215
|
+
or box.w <= 0
|
|
216
|
+
or box.h <= 0
|
|
217
|
+
):
|
|
218
|
+
oob += 1
|
|
219
|
+
_add_example(oob_examples, f"{label.name}:{box.line_no}", max_examples)
|
|
220
|
+
continue
|
|
221
|
+
|
|
222
|
+
if box.w * box.h < tiny_area:
|
|
223
|
+
tiny += 1
|
|
224
|
+
_add_example(tiny_examples, f"{label.name}:{box.line_no}", max_examples)
|
|
225
|
+
|
|
226
|
+
if box.h > 0 and (box.w / box.h > max_aspect or box.h / box.w > max_aspect):
|
|
227
|
+
ratio += 1
|
|
228
|
+
_add_example(ratio_examples, f"{label.name}:{box.line_no}", max_examples)
|
|
229
|
+
|
|
230
|
+
# 孤立标签:labels/ 目录里有 txt,但找不到对应图片
|
|
231
|
+
orphan, orphan_examples = _find_orphan_labels(data, max_examples)
|
|
232
|
+
|
|
233
|
+
split_of = _split_index(data)
|
|
234
|
+
duplicates, dup_groups, dup_examples, leaks, leak_examples = (
|
|
235
|
+
_find_duplicates(data.images, max_examples, split_of) if hash_images else (0, 0, [], 0, [])
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
# data.yaml 里 nc 和 names 数量对不上,训练会直接报错
|
|
239
|
+
nc_mismatch = 0
|
|
240
|
+
nc_examples: list[str] = []
|
|
241
|
+
if data.nc is not None and data.names and data.nc != len(data.names):
|
|
242
|
+
nc_mismatch = 1
|
|
243
|
+
nc_examples.append(f"nc={data.nc},names 实际 {len(data.names)} 个")
|
|
244
|
+
|
|
245
|
+
result.class_counts = dict(class_counts)
|
|
246
|
+
result.sizes = sizes
|
|
247
|
+
result.missing_labels = missing
|
|
248
|
+
result.empty_labels = empty
|
|
249
|
+
result.bad_lines = bad
|
|
250
|
+
result.polygon_lines = polygon_total
|
|
251
|
+
result.out_of_bounds = oob
|
|
252
|
+
result.tiny_boxes = tiny
|
|
253
|
+
result.extreme_ratios = ratio
|
|
254
|
+
result.unknown_classes = unknown
|
|
255
|
+
result.orphan_labels = orphan
|
|
256
|
+
result.duplicate_images = duplicates
|
|
257
|
+
result.duplicate_groups = dup_groups
|
|
258
|
+
result.cross_split_leaks = leaks
|
|
259
|
+
result.detect_rows = detect_rows
|
|
260
|
+
result.nc_mismatch = nc_mismatch
|
|
261
|
+
|
|
262
|
+
result.issues = _build_issues(result, {
|
|
263
|
+
"missing": (missing, missing_examples),
|
|
264
|
+
"empty": (empty, empty_examples),
|
|
265
|
+
"bad": (bad, bad_examples),
|
|
266
|
+
"polygon": (polygon_error, polygon_examples),
|
|
267
|
+
"orphan": (orphan, orphan_examples),
|
|
268
|
+
"oob": (oob, oob_examples),
|
|
269
|
+
"tiny": (tiny, tiny_examples),
|
|
270
|
+
"ratio": (ratio, ratio_examples),
|
|
271
|
+
"unknown": (unknown, unknown_examples),
|
|
272
|
+
"dup": (duplicates, dup_examples),
|
|
273
|
+
"leak": (leaks, leak_examples),
|
|
274
|
+
"detect_rows": (detect_rows, detect_examples),
|
|
275
|
+
"nc": (nc_mismatch, nc_examples),
|
|
276
|
+
}, task=task, tiny_area=tiny_area, max_aspect=max_aspect)
|
|
277
|
+
|
|
278
|
+
imbalance = _imbalance(result, ratio=imbalance_ratio)
|
|
279
|
+
if imbalance:
|
|
280
|
+
result.issues.append(imbalance)
|
|
281
|
+
|
|
282
|
+
return result
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _rel(path: Path, root: Path) -> str:
|
|
286
|
+
try:
|
|
287
|
+
return str(path.relative_to(root))
|
|
288
|
+
except ValueError:
|
|
289
|
+
return str(path)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _add_example(bucket: list[str], value: object, limit: int, *, note: str = "") -> None:
|
|
293
|
+
if len(bucket) >= limit:
|
|
294
|
+
return
|
|
295
|
+
text = str(value)
|
|
296
|
+
bucket.append(f"{text}({note})" if note else text)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _find_orphan_labels(data: ds.Dataset, limit: int) -> tuple[int, list[str]]:
|
|
300
|
+
labels_root = data.root / "labels"
|
|
301
|
+
if not labels_root.exists():
|
|
302
|
+
return 0, []
|
|
303
|
+
|
|
304
|
+
expected = {str(data.label_path(img)).casefold() for img in data.images}
|
|
305
|
+
orphans: list[str] = []
|
|
306
|
+
count = 0
|
|
307
|
+
for txt in labels_root.rglob("*.txt"):
|
|
308
|
+
if str(txt).casefold() in expected:
|
|
309
|
+
continue
|
|
310
|
+
count += 1
|
|
311
|
+
if len(orphans) < limit:
|
|
312
|
+
orphans.append(str(txt.relative_to(data.root)))
|
|
313
|
+
return count, orphans
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _ahash(path: Path, size: int = 8) -> str | None:
|
|
317
|
+
try:
|
|
318
|
+
with Image.open(path) as im:
|
|
319
|
+
gray = im.convert("L").resize((size, size), Image.Resampling.LANCZOS)
|
|
320
|
+
pixels = gray.tobytes() # 8x8 灰度图,每像素一字节
|
|
321
|
+
except Exception:
|
|
322
|
+
return None
|
|
323
|
+
|
|
324
|
+
avg = sum(pixels) / len(pixels)
|
|
325
|
+
return "".join("1" if p > avg else "0" for p in pixels)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _find_duplicates(
|
|
329
|
+
images: list[Path],
|
|
330
|
+
limit: int,
|
|
331
|
+
split_of: dict[str, set[str]] | None = None,
|
|
332
|
+
) -> tuple[int, int, list[str], int, list[str]]:
|
|
333
|
+
"""返回 (重复图数, 重复组数, 重复样例, 跨 split 泄漏图数, 泄漏样例)。"""
|
|
334
|
+
buckets: dict[str, list[Path]] = defaultdict(list)
|
|
335
|
+
for image in images:
|
|
336
|
+
digest = _ahash(image)
|
|
337
|
+
if digest:
|
|
338
|
+
buckets[digest].append(image)
|
|
339
|
+
|
|
340
|
+
duplicate_images = 0
|
|
341
|
+
groups = 0
|
|
342
|
+
examples: list[str] = []
|
|
343
|
+
leaks = 0
|
|
344
|
+
leak_examples: list[str] = []
|
|
345
|
+
|
|
346
|
+
for paths in buckets.values():
|
|
347
|
+
if len(paths) < 2:
|
|
348
|
+
continue
|
|
349
|
+
groups += 1
|
|
350
|
+
duplicate_images += len(paths) - 1
|
|
351
|
+
if len(examples) < limit:
|
|
352
|
+
name = paths[0].name
|
|
353
|
+
examples.append(f"{name} 等 {len(paths)} 张")
|
|
354
|
+
|
|
355
|
+
if not split_of:
|
|
356
|
+
continue
|
|
357
|
+
spans = set()
|
|
358
|
+
for path in paths:
|
|
359
|
+
spans |= split_of.get(_key(path), set())
|
|
360
|
+
if len(spans) > 1:
|
|
361
|
+
leaks += len(paths)
|
|
362
|
+
if len(leak_examples) < limit:
|
|
363
|
+
leak_examples.append(
|
|
364
|
+
f"{paths[0].name} 等 {len(paths)} 张:" + " + ".join(sorted(spans))
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
return duplicate_images, groups, examples, leaks, leak_examples
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _key(path: Path) -> str:
|
|
371
|
+
try:
|
|
372
|
+
return str(path.resolve()).casefold()
|
|
373
|
+
except OSError:
|
|
374
|
+
return str(path).casefold()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _split_index(data: ds.Dataset) -> dict[str, set[str]]:
|
|
378
|
+
"""图片路径 → 它出现在哪些 split;用来识别跨 split 的同一张图。"""
|
|
379
|
+
index: dict[str, set[str]] = defaultdict(set)
|
|
380
|
+
for name, paths in data.splits.items():
|
|
381
|
+
for path in paths:
|
|
382
|
+
index[_key(path)].add(name)
|
|
383
|
+
return dict(index)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _imbalance(result: AuditResult, *, ratio: float = IMBALANCE_RATIO) -> Issue | None:
|
|
387
|
+
if not result.class_counts:
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
counts = list(result.class_counts.values())
|
|
391
|
+
missing_classes = [i for i in result.class_names if i not in result.class_counts]
|
|
392
|
+
top = max(counts)
|
|
393
|
+
low = min(counts)
|
|
394
|
+
|
|
395
|
+
if missing_classes:
|
|
396
|
+
names = ", ".join(result.class_names[i] for i in missing_classes[:5])
|
|
397
|
+
return Issue(
|
|
398
|
+
level="warn",
|
|
399
|
+
kind="empty_class",
|
|
400
|
+
title="有类别在数据集中一个实例都没有",
|
|
401
|
+
count=len(missing_classes),
|
|
402
|
+
advice=f"检查是否漏标注:{names}。训练时这些类别的 mAP 会直接为 0。",
|
|
403
|
+
examples=names.split(", "),
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
if low == 0:
|
|
407
|
+
return None
|
|
408
|
+
|
|
409
|
+
if top / low >= ratio:
|
|
410
|
+
worst = max(result.class_counts, key=result.class_counts.get)
|
|
411
|
+
rarest = min(result.class_counts, key=result.class_counts.get)
|
|
412
|
+
return Issue(
|
|
413
|
+
level="warn",
|
|
414
|
+
kind="imbalance",
|
|
415
|
+
title="类别分布不平衡",
|
|
416
|
+
count=top - low,
|
|
417
|
+
advice=(
|
|
418
|
+
f"最多的是「{result.class_names.get(worst, worst)}」{top} 个,"
|
|
419
|
+
f"最少的是「{result.class_names.get(rarest, rarest)}」{low} 个,"
|
|
420
|
+
f"相差 {top / low:.1f} 倍。建议补样本或开类别权重。"
|
|
421
|
+
),
|
|
422
|
+
examples=[f"{result.class_names.get(worst, worst)}: {top}", f"{result.class_names.get(rarest, rarest)}: {low}"],
|
|
423
|
+
)
|
|
424
|
+
return None
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _build_issues(
|
|
428
|
+
result: AuditResult,
|
|
429
|
+
stats: dict[str, tuple[int, list[str]]],
|
|
430
|
+
*,
|
|
431
|
+
task: str = "detect",
|
|
432
|
+
tiny_area: float = TINY_AREA,
|
|
433
|
+
max_aspect: float = EXTREME_RATIO,
|
|
434
|
+
) -> list[Issue]:
|
|
435
|
+
def issue(level: str, kind: str, title: str, count: int, advice: str, examples: list[str]) -> Issue | None:
|
|
436
|
+
return Issue(level=level, kind=kind, title=title, count=count, advice=advice, examples=examples) if count else None
|
|
437
|
+
|
|
438
|
+
candidates = [
|
|
439
|
+
issue("error", "leakage", "同一张图同时出现在不同 split(数据泄漏)", stats["leak"][0],
|
|
440
|
+
"感知哈希判定是同一张图,却分布在 train / val(或 test)两侧。这是 val mAP 虚高最常见的原因:"
|
|
441
|
+
"同一张图在 train 里见过,val 上自然全中。用 `ydt split` 按组重新切分,同一组图只会落在同一侧。",
|
|
442
|
+
stats["leak"][1]),
|
|
443
|
+
issue("error", "nc_mismatch", "data.yaml 的 nc 与 names 数量不一致", stats["nc"][0],
|
|
444
|
+
"ultralytics 会按 names 的长度建类别表,nc 写错会让类别 id 整体错位或直接报错。"
|
|
445
|
+
"把 nc 改成 `len(names)`,或补齐 names。", stats["nc"][1]),
|
|
446
|
+
issue("error", "polygon", "标签是多边形(分割格式),不是检测框", stats["polygon"][0],
|
|
447
|
+
"每行有 2n+1 个数字,是 YOLO-seg 的多边形导出。检测任务读这种标签会解析错位;"
|
|
448
|
+
"跑 `ydt seg2box` 转成外接框,或改用分割任务训练(`ydt audit --task seg`)。", stats["polygon"][1]),
|
|
449
|
+
issue("error", "bad_line", "标签文件里有无法解析的行", stats["bad"][0],
|
|
450
|
+
"这些行不是 `类别 x y w h` 五列格式,训练时会被静默丢弃,务必修正。", stats["bad"][1]),
|
|
451
|
+
issue("error", "out_of_bounds", "标注框超出图像边界", stats["oob"][0],
|
|
452
|
+
"框的坐标应当归一化到 [0,1]。越界通常是标注工具导出错误,或做了裁剪没同步改标签。", stats["oob"][1]),
|
|
453
|
+
issue("error", "orphan_label", "存在没有对应图片的标签", stats["orphan"][0],
|
|
454
|
+
"`labels/` 下有 txt 却找不到同名图片,通常是删图没删标签,或 images/labels 目录结构不对。", stats["orphan"][1]),
|
|
455
|
+
issue("error", "unknown_class", "标注里的类别 id 不在 names 里", stats["unknown"][0],
|
|
456
|
+
"类别 id 超出 data.yaml 的 names 范围,训练会直接报错或错位。", stats["unknown"][1]),
|
|
457
|
+
issue("warn", "detect_row", "分割任务里出现纯检测框标签", stats["detect_rows"][0],
|
|
458
|
+
f"当前按 --task seg 体检。这 {stats['detect_rows'][0]} 行只有 5 列,是检测格式,"
|
|
459
|
+
"分割训练读不了,会被丢弃。要么用 `ydt seg2box` 的方向相反操作补多边形,要么改回检测任务。",
|
|
460
|
+
stats["detect_rows"][1]),
|
|
461
|
+
issue("warn", "missing_label", "图片没有对应标签文件", stats["missing"][0],
|
|
462
|
+
"这些图会被当作纯背景训练(负样本)。如果不是故意的,会造成漏标。", stats["missing"][1]),
|
|
463
|
+
issue("warn", "empty_label", "标签文件存在但没有任何有效框", stats["empty"][0],
|
|
464
|
+
"空标签等价于负样本;确认这些图里真的没有目标。", stats["empty"][1]),
|
|
465
|
+
issue("warn", "duplicate", "存在重复图片", stats["dup"][0],
|
|
466
|
+
"感知哈希判定为同一张图。若它们还在同一个 split 内,属于冗余样本;跨 split 的情况会单独报 error。", stats["dup"][1]),
|
|
467
|
+
issue("warn", "tiny_box", "存在超小标注框", stats["tiny"][0],
|
|
468
|
+
f"框面积小于整图的 {tiny_area:.1%},训练时几乎学不到;确认不是误标或分辨率过低。"
|
|
469
|
+
"小目标数据集可用 `--min-box-area` 放宽。", stats["tiny"][1]),
|
|
470
|
+
issue("warn", "extreme_ratio", "存在极端长宽比的框", stats["ratio"][0],
|
|
471
|
+
f"宽高比超过 {max_aspect:.0f}:1,可能是把长条物体框成了一整行,或坐标写反。"
|
|
472
|
+
"可用 `--max-aspect` 调整阈值。", stats["ratio"][1]),
|
|
473
|
+
]
|
|
474
|
+
|
|
475
|
+
issues = [i for i in candidates if i is not None]
|
|
476
|
+
|
|
477
|
+
unreadable = result.sizes.get(("unreadable", 0), 0)
|
|
478
|
+
if unreadable:
|
|
479
|
+
issues.append(Issue(
|
|
480
|
+
level="error", kind="unreadable", title="有图片无法读取",
|
|
481
|
+
count=unreadable, advice="文件可能损坏或扩展名与实际格式不符,训练时会报错。",
|
|
482
|
+
examples=[],
|
|
483
|
+
))
|
|
484
|
+
|
|
485
|
+
return issues
|