nnU-Net 完整教學
Repository: https://github.com/MIC-DKFZ/nnUNet Stars: 8,527 | Language: Python | License: Apache-2.0 Tags: segmentation, self-configuring 最新版本: v2.8.0 (pyproject.toml) / v2.4.1 (GitHub Release, 2024-04) 維護單位: German Cancer Research Center (DKFZ) — Helmholtz Imaging Applied Computer Vision Lab (ACVL)
2. 核心架構
2.1 自配置管線總覽
flowchart TB
subgraph INPUT["輸入層"]
RAW["nnUNet_raw/
原始影像 + 標注"]
end
subgraph FINGERPRINT["Stage 1: Dataset Fingerprint
資料集指紋分析"]
FP1["影像間距 Spacing"]
FP2["體素尺寸 Voxel Size"]
FP3["通道數 Channels"]
FP4["強度分佈 Intensity Distribution"]
FP5["類別比例 Class Ratios"]
end
subgraph PLANNING["Stage 2: Experiment Planning
實驗規劃"]
PL1["選擇網路拓撲
2D / 3D_fullres / 3D_lowres / 3D_cascade"]
PL2["決定 Patch Size"]
PL3["決定 Batch Size"]
PL4["決定 Normalization Scheme"]
PL5["決定 Resampling Strategy"]
end
subgraph PREPROCESS["Stage 3: Preprocessing
前處理"]
PP1["Cropping 裁剪"]
PP2["Resampling 重採樣"]
PP3["Normalization 正規化"]
end
subgraph TRAINING["Stage 4: Training
訓練"]
TR1["5-Fold Cross Validation"]
TR2["Data Augmentation
batchgeneratorsv2"]
TR3["Dice + CE Loss
Deep Supervision"]
TR4["SGD / Adam Optimizer
PolyLR Scheduler"]
end
subgraph POSTPROCESS["Stage 5: Model Selection & Inference
模型選擇與推論"]
MS1["Best Configuration Selection"]
MS2["Optional Ensembling"]
MS3["Postprocessing
Connected Components"]
MS4["Sliding Window Inference"]
end
INPUT --> FINGERPRINT
FINGERPRINT --> PLANNING
PLANNING --> PREPROCESS
PREPROCESS --> TRAINING
TRAINING --> POSTPROCESS
style INPUT fill:#e1f5fe
style FINGERPRINT fill:#f3e5f5
style PLANNING fill:#fff3e0
style PREPROCESS fill:#e8f5e9
style TRAINING fill:#fce4ec
style POSTPROCESS fill:#f1f8e9
2.2 原始碼模組結構
| 模組 | 路徑 | 功能 |
|---|---|---|
| Dataset Conversion | nnunetv2/dataset_conversion/ | 將各挑戰賽資料集轉為 nnU-Net 格式 |
| Experiment Planning | nnunetv2/experiment_planning/ | 指紋分析 + 實驗規劃(含 ResEnc Planner) |
| Preprocessing | nnunetv2/preprocessing/ | Cropping、Normalization、Resampling |
| Training | nnunetv2/training/ | Trainer、DA、Loss、LR Scheduler、DataLoader |
| Inference | nnunetv2/inference/ | Sliding Window、Export Prediction |
| Evaluation | nnunetv2/evaluation/ | Dice/IoU 計算、Best Configuration 搜尋 |
| Ensembling | nnunetv2/ensembling/ | 多模型集成 |
| Postprocessing | nnunetv2/postprocessing/ | Connected Component Removal |
| ImageIO | nnunetv2/imageio/ | NIfTI / SimpleITK / TIFF / 自然影像讀寫 |
| Utilities | nnunetv2/utilities/ | Label Handling、Plans Handling、DDP |
2.3 Trainer 變體繼承樹
nnU-Net v2 的核心設計是以 nnUNetTrainer 為基底類別,透過繼承覆寫來客製化行為:
classDiagram
class nnUNetTrainer {
+initialize()
+run_training()
+perform_actual_validation()
+predict_from_raw_data()
+configure_optimizers_and_lr_scheduler()
+configure_rotation_dummyDA_mirroring_and_inital_patch_size()
+get_dataloaders()
}
nnUNetTrainer <|-- nnUNetTrainerDA5
nnUNetTrainer <|-- nnUNetTrainerNoDA
nnUNetTrainer <|-- nnUNetTrainerNoMirroring
nnUNetTrainer <|-- nnUNetTrainerCELoss
nnUNetTrainer <|-- nnUNetTrainerDiceLoss
nnUNetTrainer <|-- nnUNetTrainerTopkLoss
nnUNetTrainer <|-- nnUNetTrainerCosAnneal
nnUNetTrainer <|-- nnUNetTrainerAdam
nnUNetTrainer <|-- nnUNetTrainerBN
nnUNetTrainer <|-- nnUNetTrainerNoDeepSupervision
nnUNetTrainer <|-- nnUNetTrainer_probabilisticOversampling
note for nnUNetTrainerDA5 "加強版 Data Augmentation"
note for nnUNetTrainerNoDA "完全關閉 DA\n(用於對照實驗)"
note for nnUNetTrainerCELoss "僅用 Cross-Entropy Loss"
note for nnUNetTrainerCosAnneal "Cosine Annealing LR"
3. 安裝與設定
3.1 前置需求
| 需求 | 版本 | 備註 |
|---|---|---|
| Python | >= 3.10 | 建議 3.11+ |
| PyTorch | >= 2.1.2, != 2.9.* | 須先手動安裝(含 CUDA) |
| GPU VRAM | >= 8 GB | 建議 >= 16 GB(3D 全解析度) |
| 磁碟空間 | 視資料集而定 | 前處理後可能膨脹 2-5 倍 |
3.2 安裝步驟
1# 1. 建立虛擬環境(推薦使用 uv)
2uv venv nnunet-env --python 3.11
3source nnunet-env/bin/activate
4
5# 2. 安裝 PyTorch(依硬體選擇,以 CUDA 12.4 為例)
6uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
7
8# 3. 安裝 nnU-Net
9uv pip install nnunetv2
10
11# 4. 驗證安裝
12python -c "import nnunetv2; print(nnunetv2.__version__)"
3.3 環境變數設定
nnU-Net 依賴三個環境變數來管理資料路徑,必須在使用前設定:
1# 加入 ~/.bashrc 或 ~/.zshrc
2export nnUNet_raw="/data/nnUNet/raw"
3export nnUNet_preprocessed="/data/nnUNet/preprocessed"
4export nnUNet_results="/data/nnUNet/results"
5
6# 建立目錄
7mkdir -p $nnUNet_raw $nnUNet_preprocessed $nnUNet_results
| 變數 | 用途 |
|---|---|
nnUNet_raw | 原始影像與標注(nnU-Net 格式) |
nnUNet_preprocessed | 前處理後的資料(自動產生) |
nnUNet_results | 訓練結果、模型權重、Plans 檔案 |
3.4 資料集格式
nnU-Net 使用特定的資料夾結構,稱為 Dataset Fingerprint Format:
1nnUNet_raw/
2└── Dataset001_BrainTumour/
3 ├── dataset.json # 資料集描述(通道、類別、檔案數)
4 ├── imagesTr/ # 訓練影像
5 │ ├── BrainTumour_001_0000.nii.gz # case_001, modality_0
6 │ ├── BrainTumour_001_0001.nii.gz # case_001, modality_1
7 │ └── ...
8 ├── labelsTr/ # 訓練標注
9 │ ├── BrainTumour_001.nii.gz
10 │ └── ...
11 └── imagesTs/ # 測試影像(選填)
12 └── ...
dataset.json 範例:
1{
2 "channel_names": {
3 "0": "T1",
4 "1": "T1ce",
5 "2": "T2",
6 "3": "FLAIR"
7 },
8 "labels": {
9 "background": 0,
10 "edema": 1,
11 "non-enhancing_tumor": 2,
12 "enhancing_tumor": 3
13 },
14 "numTraining": 484,
15 "file_ending": ".nii.gz"
16}
4. 使用方式與程式碼範例
4.1 範例一:標準三步驟訓練流程(CLI)
這是 nnU-Net 最核心的使用方式——只需三個指令即可完成整個管線:
1# ============================================================
2# 範例:腦腫瘤分割(BraTS 資料集,Dataset ID = 001)
3# ============================================================
4
5# Step 1: 驗證資料集完整性 + 指紋分析 + 實驗規劃 + 前處理
6# -d: Dataset ID
7# --verify_dataset_integrity: 檢查檔案配對、標注值
8nnUNetv2_plan_and_preprocess -d 001 --verify_dataset_integrity
9
10# Step 2: 訓練模型
11# -d: Dataset ID
12# -c: Configuration(2d / 3d_fullres / 3d_lowres / 3d_cascade_fullres)
13# -f: Fold(0-4,或 all 一次跑完 5-fold)
14# --npz: 同時儲存 softmax 輸出(用於 Ensembling)
15nnUNetv2_train 001 3d_fullres 0 --npz
16
17# Step 3: 找出最佳配置 + 推論
18# 自動比較所有訓練過的 configuration,選出最佳
19nnUNetv2_find_best_configuration 001 -c 2d 3d_fullres 3d_lowres 3d_cascade_fullres
20
21# 使用最佳配置進行推論
22nnUNetv2_predict \
23 -i /path/to/test_images/ \
24 -o /path/to/predictions/ \
25 -d 001 \
26 -c 3d_fullres \
27 -f 0 1 2 3 4 \
28 --save_probabilities
執行時間參考(以 NVIDIA A100 40GB 為例):
- Step 1 (Plan & Preprocess): 5-30 分鐘(視資料集大小)
- Step 2 (Training, 1 fold): 12-72 小時(視解析度與 patch size)
- Step 3 (Inference): 數分鐘到數小時
4.2 範例二:Python API 進行客製化推論
當需要將 nnU-Net 整合進更大的管線時(例如合成影像驗證),可使用 Python API:
1"""
2範例:使用 nnU-Net Python API 對合成影像進行分割驗證
3適用場景:驗證 GAN / Diffusion 合成的醫學影像品質
4"""
5import torch
6from pathlib import Path
7from nnunetv2.inference.predict_from_raw_data import nnUNetPredictor
8
9# --- 初始化 Predictor ---
10predictor = nnUNetPredictor(
11 tile_step_size=0.5, # Sliding window 步長(越小越精確但越慢)
12 use_gaussian=True, # Gaussian weighting for sliding window
13 use_mirroring=True, # Test-Time Augmentation (TTA; 測試時增強)
14 device=torch.device('cuda', 0),
15 verbose=False,
16 verbose_preprocessing=False,
17 allow_tqdm=True
18)
19
20# --- 載入訓練好的模型 ---
21predictor.initialize_from_trained_model_folder(
22 model_training_output_dir=str(Path.home() / "nnUNet_results/Dataset001_BrainTumour/nnUNetTrainer__nnUNetPlans__3d_fullres"),
23 use_folds=(0, 1, 2, 3, 4), # 使用全部 5 folds 做 ensemble
24 checkpoint_name='checkpoint_final.pth'
25)
26
27# --- 對合成影像進行推論 ---
28# 輸入:合成影像資料夾(格式需符合 nnU-Net inference 格式)
29# 輸出:分割結果
30predictor.predict_from_files(
31 list_of_lists_or_source_folder="/path/to/synthetic_images/",
32 output_folder_or_list_of_truncated_output_files="/path/to/segmentation_results/",
33 save_probabilities=True, # 保存 softmax 機率圖
34 overwrite=True,
35 num_processes_preprocessing=4,
36 num_processes_segmentation_export=4,
37)
38
39print("分割完成!可計算 Dice Score 驗證合成影像品質。")
4.3 範例三:自訂 Trainer 變體(整合合成資料增強)
當需要在 nnU-Net 訓練中加入合成影像作為額外增強時,可透過繼承 Trainer 來實現:
1"""
2範例:自訂 Trainer,在訓練時混入合成影像
3適用場景:將 GAN/Diffusion 合成的影像與真實影像混合訓練
4"""
5import numpy as np
6from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
7
8
9class nnUNetTrainerWithSyntheticData(nnUNetTrainer):
10 """
11 繼承 nnUNetTrainer,在每個 training step 中
12 以一定機率將 real batch 替換為 synthetic batch。
13
14 使用方式:
15 nnUNetv2_train DATASET_ID CONFIG FOLD \
16 -tr nnUNetTrainerWithSyntheticData
17 """
18
19 def __init__(self, plans, configuration, fold, dataset_json,
20 unpack_dataset=True, device=None):
21 super().__init__(plans, configuration, fold, dataset_json,
22 unpack_dataset, device)
23 # 合成資料混入比例(30% 的 batch 改用合成影像)
24 self.synthetic_ratio = 0.3
25 self.synthetic_data_dir = "/path/to/synthetic_training_data/"
26
27 def train_step(self, batch):
28 """
29 覆寫 train_step:以 synthetic_ratio 機率
30 將 batch 資料替換為合成影像
31 """
32 if np.random.rand() < self.synthetic_ratio:
33 # 從合成資料來源載入一批影像
34 batch = self._load_synthetic_batch(batch)
35
36 # 呼叫原始 train_step 進行前向/反向傳播
37 return super().train_step(batch)
38
39 def _load_synthetic_batch(self, original_batch):
40 """
41 載入合成影像並替換 batch 中的資料。
42 實際實作需根據合成影像的儲存格式調整。
43 """
44 # 此處為概念示範——實際需實作合成影像載入邏輯
45 # 保持 batch 結構 (data, target) 不變
46 self.print_to_log_file("Using synthetic batch for this step")
47 return original_batch # 替換為實際載入邏輯
將上述檔案存為 nnUNetTrainerWithSyntheticData.py,放入 nnunetv2/training/nnUNetTrainer/variants/ 目錄下,即可透過 -tr 參數指定使用。
5. 在生醫影像合成生態系中的定位
5.1 Bio-SDG Domain 2 角色定位
在 Bio-SDG 的 16 個專案中,nnU-Net 屬於 Sub-domain A: Medical Imaging Platforms(醫學影像平台),與 MONAI、MONAI GenerativeModels 並列為基礎工具箱。
flowchart LR
subgraph GENERATION["合成生成層"]
GAN["Patho-GAN
medigan
medSynthesis"]
DIFF["conditional_DDPM
DenseDiffusion
SD-Messenger"]
MONAI_GEN["MONAI
GenerativeModels"]
end
subgraph PLATFORM["基礎平台層"]
NNUNET["nnU-Net
分割基準線 + DA 標準"]
MONAI["MONAI
訓練框架"]
end
subgraph EVALUATION["驗證評估層"]
SEG_EVAL["分割品質驗證
Dice / IoU / HD95"]
FID["影像品質指標
FID / IS / SSIM"]
CLINICAL["臨床可用性
Virtual Trials"]
end
subgraph APPLICATION["應用層"]
VICTRE["VICTRE
虛擬臨床試驗"]
CANCER["foundation-cancer-
image-biomarker"]
end
GAN --> SEG_EVAL
DIFF --> SEG_EVAL
MONAI_GEN --> SEG_EVAL
NNUNET --> SEG_EVAL
MONAI --> GAN
MONAI --> DIFF
SEG_EVAL --> CLINICAL
FID --> CLINICAL
CLINICAL --> VICTRE
CLINICAL --> CANCER
style NNUNET fill:#ff9800,color:#000,stroke:#e65100,stroke-width:3px
5.2 對藥物開發的意義
| 應用場景 | nnU-Net 角色 | 整合方式 |
|---|---|---|
| Imaging Biomarker (影像生物標記) | 分割腫瘤 / 器官,計算體積、形狀、異質性指標 | 結合 foundation-cancer-image-biomarker |
| Virtual Clinical Trials (虛擬臨床試驗) | 驗證合成影像的分割一致性 | 結合 VICTRE |
| Privacy-Preserving Data (隱私保護合成資料) | 驗證合成資料能否取代真實資料做分割訓練 | 結合 medigan / conditional DDPM |
| Data Augmentation (資料增強) | 內建 DA 管線可與合成影像互補 | 自訂 Trainer 混入合成影像 |
| Pre-IND Imaging Study | 動物模型影像分割、腫瘤體積追蹤 | 直接使用,搭配自訂 dataset |
5.3 Blue Ocean 觀察
| 方向 | 現狀 | 機會 |
|---|---|---|
| 3D 體積合成驗證 | 大部分合成模型只產 2D slice | nnU-Net 的 3D 管線可做端對端 3D 合成品質驗證 |
| 多模態合成 | Cross-modal Synthesis(MRI→CT)產出需驗證 | nnU-Net 支援多通道輸入,可直接驗證多模態合成品質 |
| 病理基礎模型 | CONCH / CLAM 產出的 WSI 特徵需分割驗證 | nnU-Net 可透過 natural_image_reader_writer 處理 tile-level 分割 |
| Diffusion + Segmentation 聯合訓練 | 目前合成與分割分離 | 未來可在 Diffusion 訓練迴圈中內嵌 nnU-Net 作為 perceptual loss |
6. 與其他工具的整合
6.1 與 MONAI 的互補關係
| 面向 | nnU-Net | MONAI |
|---|---|---|
| 定位 | 自配置分割,專注開箱即用 | 通用醫學影像框架,需手動設計 |
| 適合場景 | 新資料集快速建立 baseline | 自訂複雜管線(含生成模型) |
| DA 框架 | batchgeneratorsv2(自家) | MONAI Transforms |
| 推論 | Sliding Window + Ensemble | 更靈活的 inference pipeline |
| 整合方式 | MONAI GenerativeModels 合成 → nnU-Net 驗證 | 共用資料格式 (NIfTI) |
6.2 與 AIKT Pipeline 的整合點
1# AIKT Pipeline 整合流程:
2# 1. paper-search 找到最新合成方法
3# 2. gh-tutorial-qd 建立合成模型教學
4# 3. 合成模型產出影像
5# 4. nnU-Net 驗證合成品質
6# 5. paper-qa-lite 交叉比對分割指標與文獻
7
8# 具體指令範例:
9# 將合成影像轉為 nnU-Net 格式
10python -c "
11from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
12generate_dataset_json(
13 output_folder='/data/nnUNet/raw/Dataset100_SyntheticLiver/',
14 channel_names={0: 'CT'},
15 labels={'background': 0, 'liver': 1, 'tumor': 2},
16 num_training_cases=500,
17 file_ending='.nii.gz'
18)
19"
6.3 與合成模型的具體整合方式
| 合成模型 | 整合策略 |
|---|---|
| medigan | medigan 產出 → 轉 nnU-Net 格式 → 混合訓練 |
| conditional DDPM | DDPM 合成 + segmentation mask pair → 直接餵入 nnU-Net |
| medSynthesis (Cross-modal) | MRI→CT 合成結果 → nnU-Net 分割驗證 Dice 對比 |
| MONAI GenerativeModels | 共用 NIfTI 格式,無縫對接 |
| VICTRE | VICTRE 虛擬乳房影像 → nnU-Net 分割 → ROC 分析 |
7. 優缺點分析
7.1 優點
| 項目 | 說明 |
|---|---|
| 自配置能力無可匹敵 | 從 282 個原始碼檔案中的指紋分析到實驗規劃,全自動化 |
| 極強的泛化能力 | 在 MSD、BraTS、AMOS、KiTS、AutoPET 等多種挑戰賽中表現頂尖 |
| 高度模組化 | 13+ 種 Trainer 變體覆蓋 Loss / DA / LR / Optimizer / Architecture 的排列組合 |
| Residual Encoder Presets | v2.4.1 新增的 ResEnc 預設進一步提升 3D 分割效能 |
| 完善的 CLI 設計 | nnUNetv2_plan_and_preprocess / nnUNetv2_train / nnUNetv2_predict 三指令流 |
| Pretrain + Finetune 支援 | 可在大資料集上預訓練後遷移到小資料集 |
| 社群活躍 | 8,500+ Stars、2,400+ Forks、DKFZ 持續維護 |
| Apache-2.0 授權 | 商業友好,可用於藥廠內部管線 |
7.2 缺點與限制
| 項目 | 說明 | 緩解策略 |
|---|---|---|
| GPU 記憶體需求高 | 3D 全解析度訓練常需 >= 16 GB VRAM | 使用 3D lowres 或 2D config |
| 訓練時間長 | 5-fold × 1000 epochs,完整跑完可能需數天 | 指定單一 fold 或減少 epochs |
| 僅限語意分割 | 不支援 Instance Segmentation / Object Detection | 結合 Cellpose / StarDist |
| 不含生成功能 | 無法直接產出合成影像 | 需搭配 MONAI GenerativeModels / medigan |
| 自配置黑箱性 | 自動決策過程不易理解與干預 | 閱讀 Plans JSON 了解決策 |
| 資料格式嚴格 | 檔案命名必須嚴格遵守 _XXXX.nii.gz 格式 | 使用 --verify_dataset_integrity |
| 不原生支援 WSI | Whole Slide Image 需預切 tile 再餵入 | 結合 CLAM 做 tile extraction |
7.3 適用性判斷
1✅ 適合使用 nnU-Net 的情況:
2 - 新資料集需要快速建立強基準線
3 - 3D 醫學影像(CT / MRI / PET)語意分割
4 - 驗證合成影像的分割品質
5 - 挑戰賽或 benchmark 比較
6 - 需要自動化超參數選擇的團隊
7
8❌ 不適合的情況:
9 - 需要生成合成影像(改用 MONAI GenerativeModels / medigan)
10 - Instance Segmentation(改用 Cellpose / Mask R-CNN)
11 - 即時推論(nnU-Net 推論較慢,改用蒸餾後的輕量模型)
12 - Whole Slide Imaging 原生處理(改用 CLAM + nnU-Net 組合)
附錄:快速參考卡
CLI 指令速查
| 指令 | 功能 |
|---|---|
nnUNetv2_plan_and_preprocess -d ID | 指紋分析 + 規劃 + 前處理 |
nnUNetv2_train ID CONFIG FOLD | 訓練指定配置與 fold |
nnUNetv2_predict -i IN -o OUT -d ID -c CONFIG | 推論 |
nnUNetv2_find_best_configuration ID | 找最佳配置 |
nnUNetv2_ensemble -i FOLDER1 FOLDER2 -o OUT | 模型集成 |
nnUNetv2_convert_MSD_dataset -i PATH | 轉換 MSD 格式 |
主要依賴
| 套件 | 版本 | 用途 |
|---|---|---|
torch | >= 2.1.2 | 深度學習引擎 |
dynamic-network-architectures | >= 0.4.4 | U-Net 架構定義 |
batchgeneratorsv2 | >= 0.3.2 | Data Augmentation 框架 |
SimpleITK | >= 2.2.1 | 醫學影像 I/O |
nibabel | any | NIfTI 讀寫 |
acvl-utils | >= 0.2.6 | ACVL 共用工具 |
文件版本: 2026-06-11 | 資料來源: GitHub MIC-DKFZ/nnUNet (v2.8.0) | Bio-SDG Domain 2 - Sub-domain A
Comments