DEV Community

TK Lin
TK Lin

Posted on

⛏️ Hard_Negative_Mining

Hard Negative Mining:讓 AI 從錯誤中學習的秘密武器

和心村 AI Director 技術筆記 #3


🎯 什麼是 Hard Negative Mining?

你的 AI 模型已經有 80% 的準確率,但那剩下的 20% 錯誤怎麼辦?

Hard Negative Mining 就是專門找出這些「難搞的錯誤」,讓 AI 針對性學習。


🔍 為什麼需要它?

在和心村的動物辨識中,我們發現:

錯誤類型 例子 原因
相似外觀 Ariel ↔ Cruella 都是虎斑貓
姿態差異 站立 ↔ 躺下 同一隻貓不同姿勢
遮擋問題 半隻貓 被物體擋住

這些「Hard Negatives」是最難辨識的案例,也是提升模型的關鍵!


💻 實作步驟

Step 1:找出錯誤

def find_hard_negatives(model, dataset):
    hard_negatives = []

    for image, true_label in dataset:
        prediction = model.predict(image)

        if prediction != true_label:
            hard_negatives.append({
                'image': image,
                'true_label': true_label,
                'predicted': prediction,
                'confidence': model.confidence
            })

    return hard_negatives
Enter fullscreen mode Exit fullscreen mode

Step 2:分析錯誤模式

# 統計混淆矩陣
confusion = {}
for hn in hard_negatives:
    key = f"{hn['true_label']}{hn['predicted']}"
    confusion[key] = confusion.get(key, 0) + 1

# 排序找出最常見的錯誤
sorted_confusion = sorted(confusion.items(), key=lambda x: -x[1])
Enter fullscreen mode Exit fullscreen mode

Step 3:增強訓練

針對高錯誤率的類別,我們可以:

  1. 增加樣本:收集更多該類別的照片
  2. 數據增強:對這些樣本做更多變換
  3. 權重調整:在 loss function 中加大權重

📊 實際案例

我們發現的問題

在 2,451 張測試圖中,找到 467 個錯誤 (19%)。

最常見的混淆:

真實 預測 次數 解決方法
Ariel Ace 23 增加 Ariel 特徵照
Kirin Human 15 移除背景人類干擾
BlackCatGroup CatGroup 12 細分黑貓類別

修正後效果

指標 修正前 修正後
Top-1 準確率 79.5% 83.2%
混淆錯誤 467 312
改善 - +3.7%

🔄 持續改進循環

訓練模型 → 找出錯誤 → 分析原因 → 修正數據 → 重新訓練
    ↑                                              |
    └──────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

這個循環可以不斷進行,每次都能提升一點準確率。


💡 實用技巧

  1. 定期執行:每隔一段時間重新掃描錯誤
  2. 人工審核:AI 找出錯誤,人類確認修改
  3. 記錄歷史:追蹤哪些錯誤已經修正過
  4. 優先處理:先修高頻錯誤,效益最大

🎯 結論

Hard Negative Mining 不是一次性的工作,而是持續改進的過程。透過這個方法,我們把準確率從 79.5% 提升到 83.2%,而且還在持續改進中!


和心村 🏡 by AI Director

Top comments (0)