27 分鐘閱讀 · 機器視覺

假設一家工廠打算訓練 AI 檢測金屬工件上的刮痕,團隊蒐集了整整 300 張不良品圖片。可是在真實產線上一試,系統卻把好幾件表面紋理正常的工件誤報成刮痕。另一種情況是測試分數非常高,一上產線結果卻下滑。這兩種問題往往不出在模型,而出在資料:蒐集來的圖片與實際工況不符,標註之間自相矛盾,或者同一張圖片同時出現在訓練集和測試集裡。
本文不教訓練模型,而是教你在訓練前檢查資料集(label 指由人來標明這張圖是良品還是不良品,或不良在哪裡),用的是可以真正執行的 Python 程式碼,只用 numpy。所有影像都由記憶體中的 seed 產生,沒有影像檔案。經理讀說明和表格就能看懂,工程師可以直接跟著執行程式碼。
真實問題:看似齊全卻教錯了 AI 的資料集
缺陷影像集通常會犯三種錯誤。第一種是缺少良品和臨界樣本,模型從沒見過正常紋理長什麼樣。第二種是兩位標註員的標準不一致。第三種是近似重複的影像(例如對同一工件連拍的三張影格)被隨機分到了不同的集合。下面是三個假設情境,並非 BT San 任何客戶的專案。
- 假設的金屬零件工廠:只蒐集了不良品托盤裡的刮痕影像,沒有不同照明批次的良品影像。結果模型學到「表面變亮就是不良」。
- 假設的產線組裝場景:兩位標註員對淡淡的痕跡算不算不良意見不同,各憑感覺判斷,又沒有 unsure 類別,因此在臨界點上得到的標註是隨機的。
- 假設的重複拍攝工件的工廠:同一工件重新拍攝後登記成新的工件編號,依工件編號劃分資料集時無法得知它們其實是同一張圖,一張進了 train,另一張進了 test,測試分數因此虛高。
這三個問題都能在浪費訓練時間之前用一小段程式碼查出來。下面的範例把整個流程做全了:把標註指南寫成資料、衡量一致性、產生需要複核的影像清單、查看各批次的比例和涵蓋情況、找出近似重複的影像,以及無洩漏地劃分資料集。
文件怎麼說,以及本範例不主張什麼
| 主題 | 文件的說法 | 對我們範例的影響 |
|---|---|---|
| 標註指南 | Ultralytics 建議制定清晰且統一的標註標準,附上說明和範例圖片,並定期複查和改進 | spec.py 把指南存成資料,validate 依指南檢查每一筆標註 |
| 一致性 | Ultralytics 指出,較高的 inter-annotator agreement 表示指南清晰、標註員的用法一致,但沒有給出門檻數字 | 我們回報 kappa 值,但不規定多少算夠,需要自行與 QC 約定 |
| kappa 公式 | scikit-learn 定義 kappa = (p_o - p_e) / (1 - p_e),取值在 -1.0 到 1.0 之間,0.0 表示一致程度不超過隨機預期,文件中的範例給出 0.6875 | agreement.py 自行實作該公式,並以 0.6875 的範例作為測試 |
| IoU | Label Studio 把 IoU 解釋為兩個框重疊的面積除以合併後的總面積,取值 0.0 到 1.0。CVAT consensus 用 Min overlap 作為配對門檻,對框而言相當於 IoU | match_boxes 把 IoU 達到 0.5 以上的框配成一對,0.5 是我們自己選的值 |
| 重複影像 | Google ML Crash Course 要求刪除 validation 和 test 集中與 training 集重複的樣本,因為公平的測試需要新的樣本,而不是重複的樣本 | dedupe.py 找出近似重複的影像,然後 split.py 讓同一組影像留在同一個集合 |
| 依群組劃分 | scikit-learn GroupKFold 指出,每個群組在所有 fold 中只會在測試集出現一次 | 概念相同,但我們自己寫了簡單的 train/val/test 劃分器,沒有呼叫 scikit-learn |
| 資料不平衡 | Google ML Crash Course 把常見的類別稱為 majority,罕見的類別稱為 minority,並建議使用 downsampling 和 upweighting | balance.py 只回報比例和缺口,不調整權重 |
本範例使用合成影像、兩位假設的標註員和自行產生的數字,因此其中的 kappa 和 IoU 不能拿去與真實工廠資料比較。可以學到的是衡量方法和讀結果的方法。
範例概覽
全部程式碼位於 examples/defect-dataset-labeling-guide/ 資料夾,使用 Python 3 和 numpy,無須另外安裝任何東西,不使用網路。
| 檔案 | 作用 |
|---|---|
| spec.py | 把標註指南存成資料:類別、最小尺寸、良品的定義 |
| synth.py | 由 seed 產生灰階影像(表面紋理、刮痕、凹痕、淡痕、各批次不同的照明) |
| make_data.py 和 data/ | 產生 A 和 B 兩位標註員的影像清單和標註,並刻意混入有問題的資料 |
| agreement.py | 檢查標註、kappa、IoU 以及需要複核的影像清單 |
| balance.py | 類別比例和各批次的涵蓋情況 |
| dedupe.py | average hash 以及近似重複影像的分組 |
| split.py | 依群組劃分 train/val/test,並檢查洩漏 |
| demo.py / test_dataset.py | 輸出全部步驟的報告,以及 unittest 測試集 |
第 1 步:把標註指南寫成資料,並包含 unsure 類別
Word 文件形式的指南無法自動檢查,而資料形式的指南可以讓程式碼檢查每一筆標註。需要寫清楚的有三點。第一點是計入的 defect 的最小尺寸(範例中是長邊至少 8 像素)。第二點是良品指什麼,包括說明各批次亮度不同不算 defect。第三點是 unsure 類別,它是一個真實的類別,供標註員表示「看到了些什麼,但無法判斷」。這類影像會交給裁定人,而不是被悄悄猜成良品或不良品。
"""Labelling spec as data: class list, minimum defect size, what counts as good."""
IMG_SIZE = 64 # synthetic images are 64x64 grayscale
CLASSES = ["good", "scratch", "dent", "unsure"]
DEFECT_CLASSES = ["scratch", "dent"] # these must carry a box
# A defect box whose longer side is under this many pixels is too small to call.
# The annotator must use "unsure" (or no box) instead of "scratch"/"dent".
MIN_DEFECT_PX = 8
# What counts as good (written down so both annotators use the same rule):
# - no visible mark at all, or only marks below MIN_DEFECT_PX that you cannot name
# - lighting changes and lot-to-lot brightness differences are NOT defects
# What counts as unsure: you can see something but cannot decide scratch / dent / texture.
# "unsure" is a first-class label: it goes to a reviewer, it is never silently
# turned into good or defect.
GUIDE = {
"good": "no visible mark; brightness differences between lots do not count",
"scratch": "thin bright line, longer side >= MIN_DEFECT_PX, box around the whole line",
"dent": "dark soft blob, longer side >= MIN_DEFECT_PX, box around the dark area",
"unsure": "something is visible but you cannot decide; box optional",
}
IOU_MATCH = 0.5 # boxes with IoU >= this count as the same defect
HASH_MAX_DIST = 6 # Hamming distance (of 64 bits) at or below this = near-duplicate這個檔案中的 MIN_DEFECT_PX 和 IOU_MATCH 是範例的假設值,真實的數值必須來自產品標準或與 QC 的約定,最終的裁定人應是對實際產品品質負責的人。
第 2 步:產生帶有「陷阱」的合成資料,使其像真實資料
synth.py 依據 seed 繪製影像。每個工件的表面來自 part_seed,影格的雜訊來自 frame_seed,gain 是各批次的亮度,這樣同一工件重新拍攝會得到相似但並非逐像素相同的影像。短而淡的痕跡就是 unsure 的情形。
"""Synthetic grayscale images drawn from seeds. Nothing is stored as an image file."""
import numpy as np
from spec import IMG_SIZE
def render(entry):
"""entry: dict with part_seed, frame_seed, gain, kind, box (box = [x0,y0,x1,y1] or None)."""
prng = np.random.default_rng(entry["part_seed"])
# base texture belongs to the part: 8x8 coarse blocks, so every part looks different
img = np.kron(prng.uniform(80, 170, (8, 8)), np.ones((8, 8)))
if entry["box"] is not None:
x0, y0, x1, y1 = entry["box"]
if entry["kind"] in ("scratch", "unsure"):
lift = 60 if entry["kind"] == "scratch" else 25 # unsure = faint mark
yy = (y0 + y1) // 2
img[yy:yy + 2, x0:x1] += lift
elif entry["kind"] == "dent":
ys, xs = np.mgrid[y0:y1, x0:x1]
cy, cx = (y0 + y1 - 1) / 2, (x0 + x1 - 1) / 2
r = ((ys - cy) / ((y1 - y0) / 2)) ** 2 + ((xs - cx) / ((x1 - x0) / 2)) ** 2
img[y0:y1, x0:x1] -= 45 * np.clip(1 - r, 0, 1)
frng = np.random.default_rng(entry["frame_seed"]) # per-frame sensor noise
img = img * entry["gain"] + frng.normal(0, 2.0, img.shape) # gain = lighting / lot shift
assert img.shape == (IMG_SIZE, IMG_SIZE)
return np.clip(img, 0, 255)make_data.py 一共產生 40 個工件的 49 張影像,有三個照明不同的批次。批次 L3 刻意只放很少的良品,好讓涵蓋情況報告能抓到,同時還加入了真實資料中常見的陷阱。
- 近似重複的影像:有些工件有多張影格,照明略有差異
- 同一工件重新拍攝但登記了新編號(p041 就是 p005,p042 就是 p021)
- 有問題的標註:指南中沒有的類別、良品上的 3x3 框、超出影像範圍的框,以及 B 沒有標註的影像
- B 對淡痕的判斷標準與 A 不同,因此有真實的分歧可供衡量
def annotate(who):
out = {}
for im in images:
cls = im["kind"]
if who == "B": # annotator B has a different threshold for faint marks
r = rng.random()
if cls == "unsure" and r < 0.45:
cls = "good" if rng.random() < 0.5 else "scratch"
elif cls == "scratch" and r < 0.15:
cls = "unsure"
elif cls == "good" and r < 0.06:
cls = "unsure"
boxes = []
if im["box"] is not None and cls != "good":
boxes = [dict(cls=cls, xyxy=jitter(im["box"], 1 if who == "A" else 2))]
out[im["id"]] = dict(cls=cls, boxes=boxes)
return out
A, B = annotate("A"), annotate("B")
# deliberately bad entries (a real export has these):
B["p001_f0"] = dict(cls="crack", boxes=[]) # class not in the spec
B["p002_f0"] = dict(cls="scratch", boxes=[dict(cls="scratch", xyxy=[10, 10, 13, 13])]) # 3x3 box on a good part
A["p000_f0"] = dict(cls="dent", boxes=[dict(cls="dent", xyxy=[50, 50, 70, 66])]) # box leaves the image
del B["p010_f0"] # B never labelled this image第 3 步:依指南檢查標註,再衡量一致性
衡量一致性之前,先把格式有誤的標註過濾掉,因為不符合指南的標註不應算作意見。validate 檢查四件事:類別不在指南中、不良類別卻沒有框、良品卻有框,以及框超出影像或小於指南規定。
def validate(label):
"""Problems in ONE annotator's label for ONE image, judged against spec.py."""
probs = []
if label["cls"] not in CLASSES:
probs.append(f"unknown class '{label['cls']}'")
if label["cls"] in DEFECT_CLASSES and not label["boxes"]:
probs.append("defect class without a box")
if label["cls"] == "good" and label["boxes"]:
probs.append("good image carries boxes")
for b in label["boxes"]:
x0, y0, x1, y1 = b["xyxy"]
if not (0 <= x0 < x1 <= IMG_SIZE and 0 <= y0 < y1 <= IMG_SIZE):
probs.append(f"box {b['xyxy']} leaves the {IMG_SIZE}px image")
elif b["cls"] in DEFECT_CLASSES and max(x1 - x0, y1 - y0) < MIN_DEFECT_PX:
probs.append(f"{b['cls']} box {b['xyxy']} under {MIN_DEFECT_PX}px: use unsure")
return probs接著衡量影像層級類別的 Cohen's kappa。概念是先看兩人回答一致的比例(p_o),再扣除預計會因巧合而一致的部分(p_e),公式見 scikit-learn 文件。當類別不平衡時,這個扣除很重要,因為如果良品占 90%,任何人對所有影像都回答「良品」,也能有 90% 的一致,卻什麼都沒檢查。
def cohen_kappa(a, b):
"""kappa = (po - pe) / (1 - pe); same formula as sklearn.metrics.cohen_kappa_score."""
n = len(a)
po = sum(x == y for x, y in zip(a, b)) / n
ca, cb = Counter(a), Counter(b)
pe = sum(ca[c] * cb[c] for c in set(ca) | set(cb)) / (n * n)
# simplified: if both annotators use a single identical class pe == 1; return 1.0.
return 1.0 if pe == 1 else (po - pe) / (1 - pe)框則用 IoU 衡量,即重疊面積除以合併面積,然後一對一地配對,依 IoU 由高到低排序。IoU 低於門檻的框視為不同的 defect,這與 CVAT consensus 用 overlap 門檻配對框的方式一致。
def iou(p, q):
"""Intersection over union of two [x0,y0,x1,y1] boxes (x1,y1 exclusive)."""
iw = min(p[2], q[2]) - max(p[0], q[0])
ih = min(p[3], q[3]) - max(p[1], q[1])
inter = max(0, iw) * max(0, ih)
union = (p[2] - p[0]) * (p[3] - p[1]) + (q[2] - q[0]) * (q[3] - q[1]) - inter
return inter / union if union else 0.0def match_boxes(ba, bb, thr=IOU_MATCH):
"""Greedy one-to-one matching by descending IoU. Returns (pairs, only_a, only_b)."""
# simplified: greedy, not Hungarian; fine with 0-2 boxes per image, use scipy for crowds.
cand = sorted(((iou(x["xyxy"], y["xyxy"]), i, j) for i, x in enumerate(ba)
for j, y in enumerate(bb)), reverse=True)
pairs, ua, ub = [], set(), set()
for v, i, j in cand:
if v >= thr and i not in ua and j not in ub:
pairs.append((i, j, v)); ua.add(i); ub.add(j)
return pairs, [i for i in range(len(ba)) if i not in ua], [j for j in range(len(bb)) if j not in ub]需要注意的是,薄刮痕的框只有幾個像素高,偏移一個像素 IoU 就會大幅下降,所以框層級的不一致往往比類別層級更高,應當一起看,而不是只看一個數字。
第 4 步:需要退回複核的影像清單
kappa 值能說明意見一致到什麼程度,但不會告訴你哪些影像需要修改。因此 conflicts 函式產生附帶原因的影像清單,共有四種:缺少標註、標註格式有誤、類別不同,以及框重疊不夠。清單排序時,涉及 unsure 的類別不同情形排在前面,因為這是指南最可能還不清晰的地方。
def conflicts(A, B):
"""Images to send back for review: (image id, reason). 'unsure' on either side goes first."""
out = []
for iid in sorted(set(A) | set(B)):
a, b = A.get(iid), B.get(iid)
if a is None or b is None:
out.append((iid, "missing label from " + ("A" if a is None else "B")))
continue
va, vb = validate(a), validate(b)
if va or vb:
out.append((iid, "invalid: " + "; ".join([f"A {p}" for p in va] + [f"B {p}" for p in vb])))
elif a["cls"] != b["cls"]:
out.append((iid, f"class differs: A={a['cls']} B={b['cls']}"))
else:
pairs, ua, ub = match_boxes(a["boxes"], b["boxes"])
if ua or ub:
out.append((iid, f"boxes do not overlap enough (IoU < {IOU_MATCH})"))
return sorted(out, key=lambda r: (not (r[1].startswith("class differs") and "unsure" in r[1]), r[0]))第 5 步:類別比例和各批次的涵蓋情況
用於訓練的資料集應來自標註員意見一致的影像,仍在複核清單中的影像必須等裁定人處理。因此 balance.py 只統計不在清單中的影像,然後查看每個批次的良品是否足夠,以及是否有類別缺漏。結果會告訴你需要到哪裡補採影像。
def coverage(final, lot_of):
"""Rows (lot, counts per class, total, flag text)."""
rows = []
for lot in sorted(set(lot_of.values())):
c = Counter(cls for i, cls in final.items() if lot_of[i] == lot)
n = sum(c.values())
flags = []
if n and c["good"] / n < MIN_GOOD_SHARE:
flags.append(f"good only {c['good'] / n:.0%}")
flags += [f"no {k}" for k in CLASSES if c[k] == 0]
rows.append((lot, [c[k] for k in CLASSES], n, ", ".join(flags) or "ok"))
return rows第 6 步:用 average hash 找出近似重複的影像
average hash 把影像縮小成 8x8 個格子,每個格子的亮度高於平均值就記為 1,得到一個 64 位元的數。相似的影像只有很少幾位元不同,不同工件的影像則差異很大。與影像自身的平均值比較,使整幅影像變亮或變暗時 hash 值幾乎不變,很適合各批次照明不同的情況。
def ahash(img):
"""64x64 -> 8x8 block means -> bit = block mean above the overall mean. Returns a 64-bit int."""
small = img.reshape(8, 8, 8, 8).mean(axis=(1, 3))
bits = (small > small.mean()).ravel()
return int("".join("1" if b else "0" for b in bits), 2)def near_dup_groups(hashes, max_dist=HASH_MAX_DIST):
"""Union-find over image ids: any pair within max_dist ends up in one group id."""
# simplified: O(n^2) pair scan; production = LSH / BK-tree or embeddings for 100k+ images.
ids = list(hashes)
parent = {i: i for i in ids}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for k, a in enumerate(ids):
for b in ids[k + 1:]:
if hamming(hashes[a], hashes[b]) <= max_dist:
parent[find(a)] = find(b)
return {i: find(i) for i in ids}分組用 union-find,因為「相近」是鏈式的:如果 A 與 B 相近、B 與 C 相近,那麼三者必須歸為同一組,即使 A 與 C 相距較遠。限制是這種 hash 只能抓到明暗結構相似的影像,視角偏移或裁切差異很大的影像會漏掉。實際使用時應改用更穩健的 perceptual hash,或用模型輸出的向量來比較。
第 7 步:依群組劃分 train/val/test
概念與 scikit-learn 的 GroupKFold 相同:一個群組的所有成員必須留在同一個集合。不同的是,我們的群組不是工件編號,而是由近似重複影像分組得到的群組,因此連重新登記了新編號的同一工件也能抓到。
def group_split(group_of, fractions=(0.7, 0.15, 0.15), seed=7):
"""group_of: image id -> group id. Returns image id -> 'train'|'val'|'test'."""
names = ("train", "val", "test")
members = {}
for img, g in group_of.items():
members.setdefault(g, []).append(img)
groups = sorted(members, key=lambda g: (-len(members[g]), str(g)))
random.Random(seed).shuffle(groups) # shuffle, then big groups first keeps sizes near target
groups.sort(key=lambda g: -len(members[g]))
total, load, out = len(group_of), dict.fromkeys(names, 0), {}
for g in groups:
# simplified: fills the split furthest below its target; no per-class stratification.
# production: stratify rare classes across splits (e.g. StratifiedGroupKFold).
s = max(names, key=lambda n: fractions[names.index(n)] * total - load[n])
for img in members[g]:
out[img] = s
load[s] += len(members[g])
return outdef leaks(split_of, group_of):
"""Groups that appear in more than one split (must be empty)."""
seen = {}
for img, g in group_of.items():
seen.setdefault(g, set()).add(split_of[img])
return {g: s for g, s in seen.items() if len(s) > 1}這個劃分器沒有依類別劃分,實際執行中 test 集得到 0 張 scratch 影像。真實資料中 defect 很少時,應做依群組的 stratified 劃分(例如 scikit-learn 的 StratifiedGroupKFold),也可能需要依批次或生產日期劃分,以測試模型能否適應新批次。這是作者的結論,並非引自所參考的文件。
實際執行:一次輸出全部報告
demo.py 載入資料,執行全部五個步驟,然後印出報告。下面的結果來自實際執行 python3 demo.py。
print("== 1. agreement")
both = [i for i in part_of if i in A and i in B]
print(f"images labelled by both: {len(both)} of {len(part_of)}")
print(f"image-class kappa: {cohen_kappa([A[i]['cls'] for i in both], [B[i]['cls'] for i in both]):.3f}")
ious = [v for i in both for _, _, v in match_boxes(A[i]["boxes"], B[i]["boxes"], 0.0)[0]]
print(f"box pairs: {len(ious)}, mean IoU {sum(ious) / len(ious):.3f}")
print("== 2. review list")
review = conflicts(A, B)
for iid, why in review:
print(f"{iid}: {why}")
print(f"{len(review)} images go back for review")== 1. agreement
images labelled by both: 48 of 49
image-class kappa: 0.745
box pairs: 20, mean IoU 0.600
== 2. review list
p006_f0: class differs: A=good B=unsure
p012_f1: class differs: A=scratch B=unsure
p037_f0: class differs: A=unsure B=good
p038_f0: class differs: A=unsure B=good
p000_f0: invalid: A box [50, 50, 70, 66] leaves the 64px image
p001_f0: invalid: B unknown class 'crack'
p002_f0: invalid: B scratch box [10, 10, 13, 13] under 8px: use unsure
p010_f0: missing label from B
p011_f0: boxes do not overlap enough (IoU < 0.5)
p013_f0: boxes do not overlap enough (IoU < 0.5)
p015_f0: invalid: B scratch box [47, 43, 54, 47] under 8px: use unsure
p029_f0: boxes do not overlap enough (IoU < 0.5)
p039_f0: boxes do not overlap enough (IoU < 0.5)
13 images go back for review
== 3. class balance and lot coverage (agreed labels only)
class counts: {'good': 22, 'scratch': 8, 'dent': 6}
lot good scratch dent unsure total flag
L1 9 1 1 0 11 no unsure
L2 11 2 2 0 15 no unsure
L3 2 5 3 0 10 good only 20%, no unsure
== 4. near-duplicates (aHash, Hamming <= 6)
['p003_f0', 'p003_f1', 'p003_f2'] max dist 0
['p005_f0', 'p041_f0'] max dist 0
['p012_f0', 'p012_f1'] max dist 0
['p020_f0', 'p020_f1'] max dist 0
['p021_f0', 'p042_f0'] max dist 0
['p033_f0', 'p033_f1', 'p033_f2'] max dist 1
['p036_f0', 'p036_f1'] max dist 1
distinct groups: 40 images: 49
== 5. grouped split
split by part id only, leaking groups: 1
split by near-dup group, leaking groups: 0
sizes: {'train': 34, 'val': 8, 'test': 7}
train: good=14, scratch=7, dent=4, unsure=0, (in review)=9
val: good=5, scratch=1, dent=1, unsure=0, (in review)=1
test: good=3, scratch=0, dent=1, unsure=0, (in review)=3逐項解讀結果
- 圖像層級 kappa 為 0.745,基於兩人都標註了的 48 張影像(另有一張 B 沒有標註)。這個數字不是模型的結果,而是說明指南裡仍有臨界情形。框配對得到 20 對,平均 IoU 為 0.600,比直覺低,因為刮痕的框很薄。
- 複核清單有 13 張影像,其中類別不同 4 張(這 4 張都是某一方標了 unsure)、標註格式有誤 4 張(p000 框超出影像,p001 出現指南中沒有的 crack 類別,p002 和 p015 的框小於 8 像素)、缺少標註 1 張(p010)、框重疊不夠 4 張。
- 有一張 p012_f1,A 判定為 scratch 而 B 判定為 unsure,而它的近似重複影像 p012_f0 兩人卻意見一致。這就是為什麼應當把近似重複影像與標註對照檢查:相同影像的標註應當相同。
- 去掉等待複核的影像後,剩下 good 22 張、scratch 8 張、dent 6 張、unsure 0 張。unsure 類別全部消失,因為都被送去複核了。如果現在訓練,模型就從沒見過臨界情形。批次 L3 的良品只有 20%,因此被標上了警示標記。
- average hash 找到 7 組重複影像,涵蓋連拍的影格以及兩對被重新登記了編號的影像(p005 與 p041,p021 與 p042)。因此 49 張影像歸併為 40 組。
- 只依工件編號劃分有 1 組洩漏到不同集合,依 hash 分組劃分則洩漏 0 組。各集合大小為 34、8 和 7 張影像,而 test 集得到 0 張 scratch 影像,正如上面的說明所提醒的。
如何驗證結果確實正確
測試集檢查的是那些會悄悄出錯的地方:kappa、IoU、對有問題標註的捕捉,以及不發生洩漏。kappa 用 scikit-learn 文件印出的 0.6875 範例來測試,並測試極端情形(完全一致得 1.0,一致程度等同隨機得 0.0)。IoU 用可以手算的數字測試:50 除以 150 等於三分之一,僅邊緣相貼的框得 0,相同的框得 1。
class Agreement(unittest.TestCase):
def test_kappa_matches_sklearn_doc_example(self):
y1 = ["negative", "positive", "negative", "neutral", "positive"]
y2 = ["negative", "positive", "negative", "neutral", "negative"]
self.assertAlmostEqual(cohen_kappa(y1, y2), 0.6875) # value printed in the sklearn docs
def test_kappa_extremes(self):
self.assertEqual(cohen_kappa(["a", "b", "a"], ["a", "b", "a"]), 1.0)
self.assertAlmostEqual(cohen_kappa(["a", "a", "b", "b"], ["a", "b", "a", "b"]), 0.0)
def test_iou(self):
self.assertAlmostEqual(iou([0, 0, 10, 10], [5, 0, 15, 10]), 50 / 150)
self.assertEqual(iou([0, 0, 4, 4], [4, 0, 8, 4]), 0.0) # touching edges: no overlap
self.assertEqual(iou([1, 1, 5, 5], [1, 1, 5, 5]), 1.0)
def test_match_is_one_to_one(self):
a = [dict(xyxy=[0, 0, 10, 10])]
b = [dict(xyxy=[0, 0, 10, 10]), dict(xyxy=[1, 0, 10, 10])]
pairs, only_a, only_b = match_boxes(a, b)
self.assertEqual(len(pairs), 1)
self.assertEqual(only_b, [1])
def test_bad_labels_are_caught(self):
self.assertTrue(validate(B["p001_f0"])) # unknown class
self.assertTrue(validate(B["p002_f0"])) # 3x3 "scratch"
self.assertTrue(validate(A["p000_f0"])) # box outside image
ids = [c[0] for c in conflicts(A, B)]
self.assertIn("p010_f0", ids) # missing from B
洩漏測試最重要,共有 3 項。第一項證明只依工件編號劃分確實會洩漏(否則這個範例就沒有意義)。第二項用 20 個不同的 seed 依 hash 分組劃分,必須完全不洩漏,且每張影像都有所屬集合。第三項證明照明改變 10% 不會讓 hash 的距離超過門檻。
class NoLeak(unittest.TestCase):
def setUp(self):
self.part_of = {m["id"]: m["part"] for m in M}
self.hashes = {m["id"]: ahash(render(m)) for m in M}
self.dg = near_dup_groups(self.hashes)
def test_part_id_alone_leaks_re_photographed_parts(self):
# p041 is p005 photographed again under a new part id: grouping by part id misses it
split = group_split(self.part_of)
self.assertTrue(leaks(split, self.dg))
def test_hash_groups_never_leak(self):
for seed in range(20):
split = group_split(self.dg, seed=seed)
self.assertEqual(leaks(split, self.dg), {})
self.assertEqual(set(split), {m["id"] for m in M})
def test_lighting_shift_keeps_hash(self):
m = dict(M[0])
dark = dict(m, gain=m["gain"] * 0.9, frame_seed=5)
d = bin(ahash(render(m)) ^ ahash(render(dark))).count("1")
self.assertLessEqual(d, 6)
在範例資料夾中執行 python3 -m unittest -v,8 項全部通過。
用於實際工作:範例跳過的部分
- 真實影像:用讀取影像檔案取代 synth.py,並把中繼資料(批次、生產日期、相機、照明)與標註存在同一張表裡,以便依批次出報告。所有影像都必須有可靠的批次和工件編號。
- 標註工具:使用 CVAT 或 Label Studio 這類工具,它們內建一致性衡量和複核功能,再把這類程式碼當作對匯出檔案的額外檢查關卡。
- 多於兩位標註員:雙人 kappa 可以兩兩使用,或改用適用於多人的其他指標,並且要指定誰是最終裁定人。
- hash:如果有十萬張影像,逐對比較會很慢,應使用 BK-tree 或 LSH 這類索引,或者比較 embedding。
- 資料集劃分:依群組做 stratified 劃分,並把最新的至少一個批次留作 test 集,在最終評估之前不得觸碰。
- 裁定後的標註:保存誰在何時改了什麼的紀錄,以便日後回溯檢查,並把指南的版本與資料集一起保存。
假設範例:套用到三類業務
- 假設的射出成型工廠:檢測燒焦痕跡和多餘的毛邊。原料批次顏色不同,導致反光不同,依批次出的報告可以在訓練模型之前指出新顏色批次的良品還不夠。
- 假設的電路板組裝工廠:檢測臨界的焊點痕跡。unsure 類別和複核清單讓工程師與 QC 只需查看意見分歧的影像,不必全部看一遍。
- 假設的食品加工廠:在輸送帶上連續拍攝產品,得到大量近似重複的影格。在劃分資料集之前先合併近似重複影像的分組,可避免測試分數虛高。
常見錯誤和檢查清單
- 只蒐集不良品托盤裡的不良品影像,卻忘了每個批次、每個班次、每種照明下的良品影像。
- 沒有 unsure 類別,因而迫使人在臨界點上猜,然後拿猜出來的標註去訓練。
- 只回報影像層級的一致性,不看框層級。類別標註一致但指向不同位置,同樣會教錯模型。
- 把 kappa 當作唯一的判斷數字,而不看不一致出在哪裡,應當結合複核清單一起看。
- 依影像隨機劃分,或依不可靠的工件編號劃分,導致重複影像洩漏到不同集合。
- 複核標註後只改了訓練集,把 test 集中錯誤的標註留在原處,因此測得的分數與實際不符。
- 中途調整了指南卻沒有紀錄版本,導致之前和之後標註的影像使用了不同的標準,而沒人知道。
把資料集送去訓練前的檢查清單
- 標註指南有書面文件,附有範例影像、最小尺寸、unsure 類別和版本號。
- 每個批次、每個班次、每種照明都有良品影像,而不僅僅是不良品。
- 每筆標註都通過 validate,且沒有指南之外的類別。
- 在隨機抽取的子集上有兩位或以上的標註員,回報 kappa 和 IoU,且複核清單已全部處理完畢。
- unsure 中的影像由品質負責人裁定,或者至少與評測集分開存放。
- 依批次的報告沒有遺留的警示標記,或者有已確認的理由。
- 已合併近似重複的影像分組,且 train/val/test 沒有跨集合的群組。
- test 集單獨保存,沒有被用來調整任何模型或門檻。
本範例的注意事項:使用合成影像和假設的標註員,因此沒有用真實工廠資料測試。average hash 只能抓到明暗結構相似的影像。得到的 kappa 和 IoU 只適用於這一組資料。IoU 0.5 和最小尺寸 8 像素這類門檻必須依據實際工件和影像解析度重新設定。本範例用於學習,不是 production 程式碼。
參考資料
- Ultralytics docs: Data collection and annotation for computer vision (accessed 2026-11-21)
- Ultralytics docs: Performance metrics (IoU, mAP50, mAP50-95) (accessed 2026-11-21)
- scikit-learn: cohen_kappa_score (accessed 2026-11-21)
- scikit-learn: GroupKFold (accessed 2026-11-21)
- CVAT docs: Consensus (Min overlap, agreement score) (accessed 2026-11-21)
- Label Studio docs: Task agreement and annotator agreement (IoU for boxes, exact match) (accessed 2026-11-21)
- Google ML Crash Course: Dividing the original dataset (accessed 2026-11-21)
- Google ML Crash Course: Imbalanced datasets (accessed 2026-11-21)




