foundation-cancer-image-biomarker 完整教學
Repository: https://github.com/AIM-Harvard/foundation-cancer-image-biomarker Stars: 132 | Tags: cancer, imaging, biomarker 論文: Nature Machine Intelligence 2024 授權: MIT License | 語言: Python (Jupyter Notebook / PyTorch) 作者: Suraj Pai, AIM Lab @ Harvard
2. 核心架構
2.1 系統架構總覽
flowchart TB
subgraph INPUT["輸入層 Input Layer"]
CSV["CSV 檔案
image_path, coordX, coordY, coordZ"]
NIFTI["NIfTI / NRRD
3D 醫學影像"]
end
subgraph PREPROCESS["前處理 Preprocessing"]
LOAD["LoadImage
(ITKReader)"]
ORIENT["Orientation
LPS 標準化"]
SPACING["Spacing
1x1x1 mm 重採樣"]
NORM["NormalizeIntensity
(-1024 ~ 2048 HU)"]
CROP["SeedBasedPatchCrop
50x50x50 voxels"]
end
subgraph MODEL["基礎模型 Foundation Model"]
TRUNK["3D ResNet-50
(widen_factor=2)"]
FEAT["Feature Vector
4096-dim"]
end
subgraph DOWNSTREAM["下游應用 Downstream Tasks"]
LINEAR["Linear Probe
(LogisticRegression)"]
FINETUNE["Fine-tuning
(project-lighter)"]
CUSTOM["自定義 Pipeline"]
end
subgraph OUTPUT["輸出層 Output Layer"]
CLASS["病灶分類"]
MALIG["惡性度預測"]
SURV["存活期預測"]
BIOM["定量生物標記"]
end
CSV --> LOAD
NIFTI --> LOAD
LOAD --> ORIENT --> SPACING --> NORM --> CROP
CROP --> TRUNK --> FEAT
FEAT --> LINEAR --> CLASS
FEAT --> LINEAR --> MALIG
FEAT --> FINETUNE --> SURV
FEAT --> CUSTOM --> BIOM
style INPUT fill:#e8f4fd,stroke:#1e88e5
style PREPROCESS fill:#fff3e0,stroke:#ff9800
style MODEL fill:#fce4ec,stroke:#e53935
style DOWNSTREAM fill:#e8f5e9,stroke:#43a047
style OUTPUT fill:#f3e5f5,stroke:#8e24aa
2.2 SSL 預訓練架構
flowchart LR
subgraph DATA["資料準備"]
IMG["3D CT Image"]
POS1["Positive View 1
(RandomResizedCrop)"]
POS2["Positive View 2
(RandomResizedCrop)"]
NEG["Negative Patch
(Background Region)"]
end
subgraph AUG["資料增強"]
FLIP["RandAxisFlip"]
HIST["RandHistogramShift"]
GAUSS["RandGaussianSmooth"]
end
subgraph SIMCLR["ExNeg SimCLR"]
ENC["3D ResNet-50
Encoder"]
PROJ["Projection Head
(4096 → 2048 → 128)"]
LOSS["NegativeMiningInfoNCE
Loss"]
end
IMG --> POS1 & POS2 & NEG
POS1 --> AUG
POS2 --> AUG
AUG --> ENC --> PROJ --> LOSS
NEG --> ENC
style SIMCLR fill:#fce4ec,stroke:#e53935
2.3 專案目錄結構
1foundation-cancer-image-biomarker/
2├── fmcib/ # 核心 Python 套件
3│ ├── models/ # 模型定義
4│ │ ├── load_model.py # LoadModel — 權重載入 + trunk/heads 架構
5│ │ ├── autoencoder.py # Autoencoder baseline
6│ │ └── models_genesis.py # Models Genesis UNet3D baseline
7│ ├── ssl/ # 自監督學習模組
8│ │ ├── modules/
9│ │ │ ├── simclr.py # Standard SimCLR
10│ │ │ ├── exneg_simclr.py # Extended Negative SimCLR (核心)
11│ │ │ ├── nnclr.py # NNCLR variant
12│ │ │ └── swav.py # SwAV variant
13│ │ └── losses/
14│ │ ├── ntxent_loss.py # NT-Xent loss
15│ │ └── neg_mining_info_nce_loss.py # 負樣本挖掘 InfoNCE
16│ ├── datasets/
17│ │ └── ssl_radiomics_dataset.py # SSL 資料集 (positive + negative pairs)
18│ ├── preprocessing/
19│ │ └── seed_based_crop.py # SeedBasedPatchCrop (核心前處理)
20│ ├── transforms/ # 3D 資料增強
21│ ├── callbacks/ # 預測儲存 callback
22│ └── run.py # 高階 API 入口 (get_features)
23├── experiments/ # 實驗設定 (YAML)
24│ ├── pretraining/ # 預訓練設定
25│ ├── inference/ # 推論設定
26│ ├── adaptation/ # 線性探測 fine-tuning
27│ └── baselines/ # Med3D / Models Genesis 比較
28├── analysis/ # 結果分析 notebooks
29├── tutorials/ # 教學 notebooks
30├── docs/ # MkDocs 文件網站
31├── tests/ # 測試
32├── pyproject.toml # Poetry 設定 + 依賴
33└── Makefile # 開發工具指令
3. 安裝與設定
3.1 快速安裝 (推論用)
1# 建立虛擬環境 (推薦)
2conda create -n fmcib python=3.10 -y
3conda activate fmcib
4
5# pip 安裝
6pip install foundation-cancer-image-biomarker
7
8# 驗證安裝
9python -c "from fmcib.models import fmcib_model; print('FMCIB installed successfully')"
3.2 開發者安裝 (含完整原始碼)
1# Clone repo
2git clone https://github.com/AIM-Harvard/foundation-cancer-image-biomarker.git
3cd foundation-cancer-image-biomarker
4
5# 使用 Poetry 安裝
6make setup
7make install
8
9# 或手動 Poetry
10pip install poetry
11poetry install
12
13# 安裝 pre-commit hooks
14make pre-commit-install
3.3 系統需求
| 項目 | 推論最低需求 | 訓練建議需求 |
|---|---|---|
| RAM | 4 GB | 12 GB+ |
| CPU | 4 cores | 4+ cores |
| GPU VRAM | 4 GB (可無) | 12 GB+ |
| OS | Linux / macOS / Windows | Linux (Ubuntu 20.04/22.04) |
| Python | 3.9 ~ 3.11 | 3.9 ~ 3.11 |
3.4 預訓練權重下載
1# 自動下載 (呼叫 fmcib_model() 時自動觸發)
2# 手動下載
3wget https://zenodo.org/records/10528450/files/model_weights.torch?download=1 -O model_weights.torch
權重檔案約 ~200 MB,來自 Zenodo,首次呼叫 fmcib_model() 會自動下載至工作目錄。
4. 使用方式與程式碼範例
4.1 範例一:從 CT 影像擷取 4096-dim 特徵向量
這是最常見的使用情境:給定一組 CT 影像和腫瘤中心座標,萃取定量生物標記特徵。
Step 1 — 準備 CSV 檔案
1image_path,coordX,coordY,coordZ
2/data/patient_001.nii.gz,55.0,119.0,27.0
3/data/patient_002.nii.gz,-32.5,84.2,15.8
4/data/patient_003.nii.gz,12.0,65.0,-5.0
座標系統為 LPS (Left-Posterior-Superior),與 ITK / SimpleITK 相同。若你的座標系為 RAS (如 3D Slicer 預設),需將 X 和 Y 取反 (negate)。
Step 2 — 一行指令萃取特徵
1from fmcib.run import get_features
2
3# 萃取特徵 — 自動下載權重、前處理、推論
4feature_df = get_features(
5 csv_path="patients.csv",
6 spatial_size=(50, 50, 50), # patch 大小 (預設)
7 precropped=False # False = 從完整 CT 裁切; True = 已預裁切
8)
9
10# 結果:原始 CSV 欄位 + pred_0 ~ pred_4095 (4096 個特徵欄位)
11print(f"Feature shape: {feature_df.filter(regex='pred_').shape}")
12# → Feature shape: (3, 4096)
13
14# 儲存特徵
15feature_df.to_csv("patient_features.csv", index=False)
Step 3 — 驗證 seed point 是否正確
1from fmcib.visualization.verify_io import visualize_seed_point
2import pandas as pd
3
4df = pd.read_csv("patients.csv")
5# 視覺化第 0 筆病人的 seed point 在 CT 上的位置
6visualize_seed_point(df.iloc[0])
4.2 範例二:使用萃取特徵做下游分類 (Linear Probe)
萃取的 4096-dim 特徵可以直接餵入傳統 ML classifier (分類器) 做下游任務,不需 GPU。
1import pandas as pd
2import numpy as np
3from sklearn.linear_model import LogisticRegression
4from sklearn.preprocessing import StandardScaler
5from sklearn.model_selection import train_test_split
6from sklearn.metrics import roc_auc_score, classification_report
7
8# ---- 1. 載入已萃取的特徵 ----
9df = pd.read_csv("patient_features.csv")
10
11# 分離特徵與標籤
12X = df.filter(regex="pred_").values # shape: (N, 4096)
13y = df["malignancy"].values # 0 = benign, 1 = malignant
14
15# ---- 2. 標準化 + 切分 ----
16scaler = StandardScaler()
17X_train, X_test, y_train, y_test = train_test_split(
18 X, y, test_size=0.2, random_state=42, stratify=y
19)
20X_train = scaler.fit_transform(X_train)
21X_test = scaler.transform(X_test)
22
23# ---- 3. 線性分類器 ----
24clf = LogisticRegression(
25 C=1.0,
26 max_iter=1000,
27 random_state=42,
28 class_weight="balanced"
29)
30clf.fit(X_train, y_train)
31
32# ---- 4. 評估 ----
33y_prob = clf.predict_proba(X_test)[:, 1]
34auc = roc_auc_score(y_test, y_prob)
35print(f"AUC-ROC: {auc:.4f}")
36print(classification_report(y_test, clf.predict(X_test)))
此範例對應論文中 Task 2 (malignancy prediction),展示 SSL 特徵在簡單線性模型上即可達到接近 supervised 方法的表現。
4.3 範例三:Fine-tuning 基礎模型 (自定義 Pipeline)
若需要針對特定資料集微調整個 backbone,可直接取得帶有預訓練權重的模型物件。
1import torch
2import torch.nn as nn
3from torch.utils.data import DataLoader
4from fmcib.models import fmcib_model
5from fmcib.preprocessing import preprocess
6import pandas as pd
7
8# ---- 1. 載入預訓練模型 (eval_mode=False 以啟用梯度) ----
9model = fmcib_model(eval_mode=False)
10device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11model = model.to(device)
12
13# ---- 2. 加上分類頭 ----
14classifier = nn.Sequential(
15 model, # 4096-dim output
16 nn.Linear(4096, 256),
17 nn.ReLU(),
18 nn.Dropout(0.3),
19 nn.Linear(256, 2) # 2-class classification
20).to(device)
21
22# ---- 3. 前處理單筆資料 (示範) ----
23df = pd.read_csv("patients.csv")
24image_tensor = preprocess(df.iloc[0]) # 回傳 shape: (1, 50, 50, 50) tensor
25image_tensor = image_tensor.unsqueeze(0).to(device)
26
27# ---- 4. Forward pass ----
28logits = classifier(image_tensor)
29print(f"Logits: {logits}")
30
31# ---- 5. 訓練迴圈 (簡化版) ----
32optimizer = torch.optim.AdamW(classifier.parameters(), lr=1e-4, weight_decay=1e-5)
33criterion = nn.CrossEntropyLoss()
34
35# 微調時建議凍結前幾層,只訓練後面的 layers
36for name, param in model.named_parameters():
37 if "layer4" not in name: # 只解凍 layer4
38 param.requires_grad = False
使用 project-lighter 的 YAML 設定做 fine-tuning (替代方案)
1# experiments/adaptation/my_finetune.yaml
2system:
3 _target_: lighter.LighterSystem
4 batch_size: 16
5 model:
6 _target_: fmcib.models.LoadModel
7 trunk:
8 _target_: monai.networks.nets.resnet50
9 widen_factor: 2
10 n_input_channels: 1
11 feed_forward: False
12 weights_path: "./model_weights.torch"
13 heads: [4096, 256, 2] # 加上分類頭
14 datasets:
15 train:
16 _target_: fmcib.datasets.SSLRadiomicsDataset
17 path: "./my_data/train.csv"
18 label: "malignancy"
19 radius: 25
20 orient: True
21 resample_spacing: [1, 1, 1]
22 enable_negatives: False
5. 在生醫影像合成生態系中的定位
5.1 Domain 2-F: Cancer Imaging 的關鍵角色
FMCIB 在 Bio-SDG 生態系 Domain 2 (生物醫學影像合成) 的 16 個專案中,屬於 Sub-domain F: Cancer Imaging — 唯一聚焦於「從癌症影像學習通用表徵」的基礎模型。其特殊定位在於:
| 面向 | FMCIB | 其他 Domain 2 工具 |
|---|---|---|
| 目標 | 影像特徵萃取 (representation) | 影像生成 (synthesis) |
| 輸入 | 真實 CT + seed point | 真實影像 / noise / 條件 |
| 輸出 | 4096-dim feature vector | 合成影像 (synthetic image) |
| 用途 | 生物標記發現、預後預測 | 資料增量、隱私保護、跨模態轉換 |
5.2 與其他 Sub-domain 的互補關係
- Sub-domain A (MONAI / nnUNet): FMCIB 的 backbone 使用 MONAI 的
resnet50,前處理使用 MONAI transforms。MONAI 是 FMCIB 的底層基礎設施。 - Sub-domain B (CLAM / CONCH): CLAM 做 whole-slide image (WSI) 的注意力聚合,FMCIB 做 3D CT 的 seed-based 特徵萃取。兩者可在多模態研究中互補 (CT + pathology)。
- Sub-domain C/D (medSynthesis / Diffusion Models): 合成影像可以用來增量 FMCIB 的預訓練資料,例如用 conditional DDPM 生成更多 CT lesion patches。反向地,FMCIB 的特徵空間可以作為合成影像品質的定量評估指標 (synthetic image quality metric)。
- Sub-domain E (VICTRE): VICTRE 做虛擬臨床試驗 (virtual clinical trials),FMCIB 的影像生物標記可以作為 VICTRE 模擬試驗的 endpoint (終點指標)。
5.3 對藥物開發的價值
FMCIB 對 pharmaceutical imaging biomarker (藥物影像生物標記) 有三個直接應用面:
- Imaging Biomarker as Endpoint (影像生物標記作為臨床終點): 在藥物臨床試驗中,FMCIB 萃取的 4096-dim 特徵可以作為 response assessment (療效評估) 的定量指標,取代或補充 RECIST 測量。
- Patient Stratification (病人分層): 基於 FMCIB 特徵的 clustering (聚類),可以在 pre-IND 階段識別哪些病人亞群最可能受益於候選藥物。
- Synthetic Data for Rare Cancers (罕見癌症的合成資料): 結合 Domain 2 其他生成模型,用 FMCIB 特徵空間引導合成罕見癌種的 CT 影像,解決稀有資料不足的問題。
6. 與其他工具的整合
6.1 與 MONAI 整合
FMCIB 的 backbone 和前處理完全建立在 MONAI 之上:
1# FMCIB 模型就是 MONAI resnet50
2from monai.networks.nets import resnet50
3
4trunk = resnet50(
5 pretrained=False,
6 n_input_channels=1,
7 widen_factor=2,
8 conv1_t_stride=2,
9 feed_forward=False,
10 bias_downsample=True
11)
12# 載入 FMCIB 預訓練權重後,可以無縫嵌入任何 MONAI pipeline
6.2 與 3D Slicer / ITK 整合
FMCIB 使用 LPS 座標系統,與 SimpleITK / ITK 一致。若使用 3D Slicer (RAS 座標系):
1# RAS → LPS 轉換
2coordX_lps = -coordX_ras
3coordY_lps = -coordY_ras
4coordZ_lps = coordZ_ras # Z 軸不變
6.3 與 AIKT Pipeline 整合
在 AI-Knowledge Template 系統中,FMCIB 的整合路徑:
1# 1. 用 paper-search 查找 FMCIB 相關論文
2# paper: FMCIB cancer imaging biomarker foundation model year=2023-2024
3
4# 2. 用 gh-tutorial-qd 生成完整教學 (已完成 — 即本文件)
5
6# 3. 特徵萃取結果可匯入 paper-qa-lite 做交叉比對
7# pq: "Compare FMCIB features with traditional radiomics on NSCLC dataset"
8
9# 4. 若結合 ToolUniverse 的 ADMET/PK 工具,可評估 imaging biomarker
10# 與藥物動力學的相關性
11# tu repos: <drug> <indication> — FMCIB features as imaging endpoint
6.4 與 medigan 整合
medigan 是 Domain 2 中的統一合成影像 API。可以用 medigan 生成合成 CT patches,再用 FMCIB 評估合成品質:
1# 概念範例:合成影像品質評估
2from fmcib.run import get_features
3
4# 真實影像特徵
5real_features = get_features("real_lesions.csv")
6
7# 合成影像特徵 (由 medigan 或 DDPM 生成)
8synthetic_features = get_features("synthetic_lesions.csv")
9
10# 計算 FID-like 距離作為品質指標
11from scipy.spatial.distance import cdist
12import numpy as np
13
14real_X = real_features.filter(regex="pred_").values
15synth_X = synthetic_features.filter(regex="pred_").values
16
17# Mean feature distance as quality metric
18quality_score = np.mean(cdist(real_X, synth_X, metric="cosine"))
19print(f"Feature distance (lower=better): {quality_score:.4f}")
7. 優缺點分析
7.1 優點
| 面向 | 說明 |
|---|---|
| 低門檻輸入 | 僅需 seed point (3D 座標),不需 segmentation mask,大幅降低標註成本 |
| 一行指令萃取 | get_features("csv_path") 即完成全部前處理 + 推論,API 極簡 |
| 穩定性 | 論文實驗證明 FMCIB features 在 test-retest (重複掃描) 中的 ICC > 0.8,優於傳統 radiomics |
| 遷移性 | 同一組預訓練權重可用於病灶分類、惡性度預測、存活期分析等多種下游任務 |
| 輕量推論 | CPU 上即可推論,單張影像 < 10 秒,適合臨床部署 |
| 完整工程品質 | 有 CI/CD、pre-commit、bandit 安全掃描、pytest 測試、MkDocs 文件 |
| MIT 授權 | 商業友善,適合藥廠內部研究使用 |
7.2 限制
| 面向 | 說明 |
|---|---|
| 僅限 CT | 目前只在 CT 影像上預訓練,不直接支援 MRI / PET / pathology |
| 僅限病灶中心 | 需要已知的 seed point,不含自動偵測 (detection) 功能 |
| 3D patch 限制 | 固定 50x50x50 voxel patch,對非常大的腫瘤 (>5 cm) 可能涵蓋不完全 |
| DeepLesion 偏差 | 預訓練資料來自單一機構 (NIH Clinical Center),可能有 dataset bias |
| 無 2D 支援 | 不支援 2D 影像 (如 X-ray, mammography),需要 3D 體積資料 |
| Poetry 依賴管理 | 依賴鏈較重 (lightly, MONAI, SimpleITK, pydicom 等),可能有版本衝突 |
| 無即時推論 API | 沒有提供 REST API / ONNX export,需自行包裝推論服務 |
7.3 Blue Ocean 機會
- Multi-modal Foundation Model: 擴展至 MRI + PET + CT 多模態預訓練,目前沒有同類開源方案
- 3D Volumetric Synthesis + Evaluation: 結合 Domain 2 的生成模型,用 FMCIB 特徵空間做合成影像品質控制
- Pathology Foundation Model Bridge: 與 CONCH (pathology FM) 做 cross-modal alignment,實現「CT 特徵預測病理結果」
- Privacy-Preserving Biomarker: 只分享 4096-dim features 而非原始影像,天然具備去識別化 (de-identification) 特性
- Federated FMCIB: 多機構聯邦學習版本,解決 DeepLesion 單一機構偏差問題
附錄:快速參考卡
1# 安裝
2pip install foundation-cancer-image-biomarker
3
4# 萃取特徵 (Python)
5from fmcib.run import get_features
6df = get_features("input.csv")
7
8# 載入模型 (Python)
9from fmcib.models import fmcib_model
10model = fmcib_model(eval_mode=True) # 推論模式
11
12# 前處理單筆 (Python)
13from fmcib.preprocessing import preprocess
14tensor = preprocess(row) # row = DataFrame 的一列
15
16# 視覺化驗證 (Python)
17from fmcib.visualization.verify_io import visualize_seed_point
18visualize_seed_point(df.iloc[0])
19
20# 開發指令 (Makefile)
21make install # 安裝依賴
22make test # 執行測試
23make codestyle # 格式化程式碼
24make lint # 完整 lint (test + style + mypy + security)
25make check-safety # 安全掃描 (bandit)
Comments