TemporAI 完整教學

Repository: https://github.com/vanderschaarlab/temporai Stars: 130 | Forks: 24 | Language: Python | License: Apache-2.0 Tags: machine-learning, medicine, time-series, automl Homepage: https://www.temporai.vanderschaar-lab.com/ Paper: arXiv:2301.12260 Last Updated: 2026-05-28

2. 核心架構

2.1 整體架構圖


graph TB
    subgraph Input["Data Input Layer (資料輸入層)"]
        RAW["Raw Data
原始醫療時序資料"] DS["DataSource Plugin
資料來源插件
(PBC, PKPD, MIMIC, UCI, Sine...)"] DATASET["TemporalDataset
統一資料格式"] end subgraph Core["Plugin Core (插件核心)"] PL["plugin_loader
插件載入器"] REG["Plugin Registry
插件註冊表"] end subgraph Preprocessing["Preprocessing Layer (前處理層)"] IMP["Imputation
缺失值填補"] SCALE["Scaling
標準化"] ENC["Encoding
特徵編碼"] end subgraph Methods["ML Methods Layer (ML 方法層)"] TTE["Time-to-Event
存活分析"] TX["Treatment Effects
治療效果估計"] PRED["Prediction
預測"] end subgraph AutoML["AutoML Layer (自動化層)"] TUNER["Tuner
超參數調校"] SEEKER["PipelineSeeker
管線搜尋"] BENCH["Benchmarks
基準測試"] end subgraph Output["Output Layer (輸出層)"] RISK["Risk Predictions
風險預測"] CF["Counterfactuals
反事實結果"] FORECAST["Forecasts
時序預測"] SERIAL["Serialization
模型序列化"] end RAW --> DS --> DATASET DATASET --> PL PL --> REG REG --> Preprocessing Preprocessing --> Methods Methods --> AutoML Methods --> Output AutoML --> Output style Input fill:#e8f5e9,stroke:#2e7d32 style Core fill:#fff3e0,stroke:#e65100 style Preprocessing fill:#e3f2fd,stroke:#1565c0 style Methods fill:#fce4ec,stroke:#c62828 style AutoML fill:#f3e5f5,stroke:#6a1b9a style Output fill:#e0f2f1,stroke:#00695c

2.2 Plugin 系統架構

TemporAI 的核心設計是 Plugin-based Architecture (插件式架構)。所有方法(模型、前處理器、資料來源)都以 Plugin 的形式註冊到全域的 plugin_loader,透過字串路徑存取:


graph LR
    subgraph PluginLoader["plugin_loader (統一入口)"]
        GET["plugin_loader.get(name)"]
        LIST["plugin_loader.list()"]
    end

    subgraph Categories["Plugin Categories (插件類別)"]
        P1["prediction.one_off.classification"]
        P2["prediction.one_off.regression"]
        P3["prediction.temporal.classification"]
        P4["prediction.temporal.regression"]
        P5["time_to_event"]
        P6["treatments.one_off.regression"]
        P7["treatments.temporal.classification"]
        P8["treatments.temporal.regression"]
        P9["preprocessing.imputation.static"]
        P10["preprocessing.imputation.temporal"]
        P11["preprocessing.scaling.static"]
        P12["preprocessing.scaling.temporal"]
        P13["preprocessing.encoding.static"]
        P14["preprocessing.encoding.temporal"]
    end

    subgraph Base["Base Classes (基底類別)"]
        BE["BaseEstimator"]
        BP["BasePredictor"]
        BT["BaseTransformer"]
    end

    GET --> Categories
    Categories --> Base

    style PluginLoader fill:#fff3e0,stroke:#e65100
    style Categories fill:#e3f2fd,stroke:#1565c0
    style Base fill:#fce4ec,stroke:#c62828

2.3 資料模型

TemporAI 定義了統一的 TemporalDataset,包含三個核心組件:

組件說明資料結構
Static Covariates (靜態共變數)不隨時間變化的病患特徵(年齡、性別、基因型)單層 DataFrame
Temporal Covariates (時序共變數)隨時間變化的測量值(生命徵象、檢驗數值)多層時序 DataFrame
Targets/Events預測目標或事件資料(存活事件、治療結果)依任務類型不同

3. 安裝與設定

3.1 基本安裝

 1# 建議使用 uv 建立隔離環境
 2uv venv temporai-env
 3source temporai-env/bin/activate
 4
 5# 從 PyPI 安裝
 6pip install temporai
 7
 8# 或從 source 安裝(取得最新版本)
 9git clone https://github.com/vanderschaarlab/temporai.git
10cd temporai
11pip install .

3.2 開發環境安裝

1# 安裝含測試依賴
2pip install temporai[testing]
3
4# 安裝完整開發依賴(含 testing + linting + docs)
5pip install temporai[dev]
6
7# 執行測試
8pytest -vsx

3.3 Conda 環境

1conda create -n temporai python=3.10
2conda activate temporai
3pip install temporai

3.4 系統需求

項目需求
Python>= 3.7(建議 3.9+)
主要依賴PyTorch, scikit-learn, pandas, numpy
選用依賴HyperImpute(缺失值填補)、XGBoost(存活分析)
硬體CPU 即可運行;GPU 加速 PyTorch 模型訓練

3.5 驗證安裝

1from tempor import plugin_loader
2
3# 列出所有可用插件
4plugins = plugin_loader.list()
5print(f"Total plugins: {len(plugins)}")
6for category, methods in plugins.items():
7    print(f"  {category}: {methods}")

4. 使用方式與程式碼範例

4.1 範例一:Time-to-Event 存活分析(Dynamic-DeepHit)

這是 TemporAI 最具代表性的功能 — 利用縱向資料動態更新存活預測。在藥物開發情境中,這可用於分析臨床試驗中病患的 Progression-Free Survival (PFS; 無惡化存活期) 或 Overall Survival (OS; 整體存活期)。

 1from tempor import plugin_loader
 2
 3# ----- 步驟 1: 載入資料 -----
 4# PBC (Primary Biliary Cholangitis) 是內建的時序存活分析資料集
 5dataset = plugin_loader.get(
 6    "time_to_event.pbc",
 7    plugin_type="datasource"
 8).load()
 9
10print(f"樣本數: {len(dataset)}")
11print(f"靜態特徵: {dataset.static.dataframe().columns.tolist()}")
12print(f"時序特徵: {dataset.time_series.dataframe().columns.tolist()}")
13
14# ----- 步驟 2: 初始化 Dynamic-DeepHit 模型 -----
15model = plugin_loader.get(
16    "time_to_event.dynamic_deephit",
17    n_iter=200,        # 訓練迭代次數
18    batch_size=100,    # 批次大小
19)
20
21# ----- 步驟 3: 訓練 -----
22model.fit(dataset)
23
24# ----- 步驟 4: 預測不同時間點的風險 -----
25# horizons: 預測 25%, 50%, 75% 時間點的風險
26prediction = model.predict(
27    dataset,
28    horizons=[0.25, 0.50, 0.75]
29)
30
31# 查看第一位病患的風險預測
32print("Patient 0 risk predictions:")
33print(prediction[0])
34
35# ----- 步驟 5: 模型序列化 -----
36from tempor.utils.serialization import save, load
37
38buffer = save(model)
39reloaded_model = load(buffer)  # 可重新使用

藥物開發應用場景

  • 在 pre-IND (Investigational New Drug; 新藥臨床試驗申請) 階段,用歷史臨床資料預測候選藥物的存活效益
  • 利用 Dynamic-DeepHit 的動態更新特性,隨著病患追蹤資料增加逐步精準化預測
  • 結合 Synthetic Data (合成資料) 生態系工具,先用合成資料驗證模型、再上真實資料

4.2 範例二:Temporal Treatment Effects(反事實推論)

這是 TemporAI 在因果推論上的核心能力 — 估計「如果用了不同治療方案,結果會怎樣?」。使用 Counterfactual Recurrent Network (CRN; 反事實遞迴網路) 進行時序治療效果推斷。

 1import numpy as np
 2from tempor import plugin_loader
 3
 4# ----- 步驟 1: 載入含時序治療的資料集 -----
 5dataset = plugin_loader.get(
 6    "treatments.temporal.dummy_treatments",
 7    plugin_type="datasource",
 8    temporal_covariates_missing_prob=0.0,    # 無缺失值(簡化示範)
 9    temporal_treatments_n_features=1,         # 1 個治療變數
10    temporal_treatments_n_categories=2,       # 2 種治療(例:藥物 A vs 藥物 B)
11).load()
12
13# ----- 步驟 2: 初始化 CRN Regressor -----
14model = plugin_loader.get(
15    "treatments.temporal.regression.crn_regressor",
16    epochs=20,
17    encoder_rnn_type="LSTM",   # 使用 LSTM 作為 encoder
18)
19
20# ----- 步驟 3: 訓練 -----
21model.fit(dataset)
22
23# ----- 步驟 4: 定義反事實情境 -----
24# 為每位病患定義預測時間範圍(取後半段時間點)
25horizons = [
26    tc.time_indexes()[0][len(tc.time_indexes()[0]) // 2:]
27    for tc in dataset.time_series
28]
29
30# 定義兩種治療情境:全程用藥 A vs 全程用藥 B
31treatment_scenarios = [
32    [
33        np.asarray([1] * len(h)),    # 情境 1: 全程治療 A
34        np.asarray([0] * len(h)),    # 情境 2: 全程治療 B
35    ]
36    for h in horizons
37]
38
39# ----- 步驟 5: 預測反事實結果 -----
40counterfactuals = model.predict_counterfactuals(
41    dataset,
42    horizons=horizons,
43    treatment_scenarios=treatment_scenarios,
44)
45
46# 查看第一位病患的兩種治療情境預測
47print("Patient 0 - Treatment A outcome:", counterfactuals[0][0])
48print("Patient 0 - Treatment B outcome:", counterfactuals[0][1])
49print("Treatment Effect (A - B):", 
50      counterfactuals[0][0].values - counterfactuals[0][1].values)

藥物開發應用場景

  • Drug Repositioning (藥物再定位; 老藥新用):比較候選藥物在不同 Indication (適應症) 下的時序治療效果
  • Clinical Trial Design (臨床試驗設計):用歷史資料預估不同 Dosing Regimen (給藥方案) 的 Outcome (結果)
  • Comparative Effectiveness (比較效益研究):量化候選藥物 vs 既有療法的時間維度治療效果差異

4.3 範例三:Pipeline + AutoML 端到端工作流

在實務中,通常需要組合多個前處理步驟與模型,並自動搜尋最佳組合。TemporAI 的 Pipeline 和 PipelineSeeker 提供了端到端的 AutoML 能力。

 1from tempor import plugin_loader
 2from tempor.methods.pipeline import pipeline
 3from tempor.benchmarks import benchmark_models
 4from tempor.automl.seeker import PipelineSeeker
 5
 6# ===== Part A: 手動 Pipeline 組合 =====
 7
 8# 載入資料
 9dataset = plugin_loader.get(
10    "time_to_event.pbc",
11    plugin_type="datasource"
12).load()
13
14# 建立 Pipeline: 前處理 (scaling) -> 模型 (存活分析)
15MyPipeline = pipeline([
16    "preprocessing.imputation.temporal.ffill",           # 時序缺失值前向填補
17    "preprocessing.scaling.temporal.ts_minmax_scaler",   # 時序 MinMax 標準化
18    "time_to_event.dynamic_deephit",                     # Dynamic-DeepHit 存活分析
19])
20
21# 初始化 Pipeline 並設定超參數
22pipe = MyPipeline({"dynamic_deephit": {"n_iter": 100}})
23pipe.fit(dataset)
24prediction = pipe.predict(dataset, horizons=[2.0, 4.0, 6.0])
25
26# ===== Part B: Benchmark 模型比較 =====
27
28testcases = [
29    ("Pipeline (FFill+MinMax+DeepHit)", pipe),
30    ("DeepHit alone", plugin_loader.get("time_to_event.dynamic_deephit", n_iter=100)),
31    ("TS-CoxPH", plugin_loader.get("time_to_event.ts_coxph", n_iter=100)),
32]
33
34aggr_score, per_test_score = benchmark_models(
35    task_type="time_to_event",
36    tests=testcases,
37    data=dataset,
38    n_splits=2,         # 2-fold Cross-Validation
39    random_state=42,
40    horizons=[2.0, 4.0, 6.0],
41)
42
43print("=== 模型比較結果 ===")
44print(aggr_score)
45
46# ===== Part C: AutoML 自動搜尋最佳 Pipeline =====
47
48seeker = PipelineSeeker(
49    study_name="pre_ind_survival_study",
50    task_type="prediction.one_off.classification",
51    estimator_names=[
52        "cde_classifier",     # Neural CDE
53        "ode_classifier",     # Neural ODE
54        "nn_classifier",      # RNN/LSTM/Transformer
55    ],
56    metric="aucroc",           # 以 AUROC 為評估指標
57    dataset=dataset,
58    return_top_k=3,            # 回傳前 3 名
59    num_iter=50,               # 搜尋 50 次迭代
60    tuner_type="bayesian",     # Bayesian Optimization
61    # 前處理選項
62    static_imputers=["static_tabular_imputer"],
63    temporal_imputers=["ffill", "bfill"],
64    temporal_scalers=["ts_minmax_scaler"],
65)
66
67# 執行搜尋(可能需要數分鐘到數小時)
68best_pipelines, best_scores = seeker.search()
69
70print("=== AutoML Top 3 Pipelines ===")
71for i, (pipe, score) in enumerate(zip(best_pipelines, best_scores)):
72    print(f"  Rank {i+1}: Score={score:.4f}")

藥物開發應用場景

  • Biomarker Discovery (生物標記物發現):自動搜尋最佳模型組合來識別有預測性的時序 Biomarker
  • Protocol Design (試驗方案設計):基準測試不同預測方法,選擇最適合目標 Endpoint (評估指標) 的模型
  • Regulatory Submission (法規送審):Benchmark 結果可作為 Model Selection Rationale (模型選擇理由) 寫入送審文件

5. 在醫療結構化資料合成生態系中的定位

5.1 生態系定位

在 Bio-SDG (Biomedical Synthetic Data Generation; 生醫合成資料生成) 的 18 個專案中,TemporAI 屬於 Sub-domain E: Medical Time Series (醫療時序資料),是唯一專注於「時序維度」的 ML 工具箱。

1Bio-SDG Domain 1: 醫療結構化資料合成
2├── A. Patient Simulation    ← Synthea (全病患生命週期模擬)
3├── B. Privacy-Preserving    ← DP 工具群 (差分隱私)
4├── C. Medical Tabular SDG   ← synthcity, COR-GAN (靜態 EHR 合成)
5├── D. Clinical Trial Data   ← VICTRE, tsynth (虛擬臨床試驗)
6├── E. Medical Time Series   ← **TemporAI** (時序 ML 分析)  ◄ 你在這裡
7└── F. Specialized           ← SDM-TIB (特化領域)

5.2 核心差異化

面向TemporAIsynthcity (Sub-domain C)Synthea (Sub-domain A)
資料維度時序 (Longitudinal)橫斷面 (Cross-sectional)全生命週期 (Lifecycle)
核心功能時序 ML 模型 + AutoML合成資料生成 + 隱私病患模擬引擎
因果推論有 (CRN, SyncTwin)
存活分析有 (Dynamic-DeepHit)間接支援
合成資料作為下游消費者作為生產者作為生產者
同一實驗室vanderschaarlabvanderschaarlabMITRE

5.3 在藥物開發管線中的角色

TemporAI 在 pre-IND 藥物開發管線中扮演 「分析引擎」 的角色,而非資料生成器:

  1. 上游:接收 Synthea/synthcity 產生的合成資料、或 MIMIC-IV 等真實資料
  2. 核心:進行時序 ML 分析(存活預測、治療效果估計、缺失值填補)
  3. 下游:輸出預測結果、模型比較報告、反事實分析,作為決策依據

5.4 Blue Ocean 機會

TemporAI 目前尚未覆蓋的領域,也是潛在的藍海:

  • CDISC SDTM/ADaM 整合:尚無直接支援 CDISC (Clinical Data Interchange Standards Consortium; 臨床數據交換標準聯盟) 標準格式的匯入/匯出
  • Regulatory-grade Model Validation:缺少 FDA/EMA 要求的 Model Risk Assessment Framework
  • Real-World Data (RWD; 真實世界數據) 時序分析:目前只提供學術資料集,缺少 Claims Data / Registry Data 的適配器

6. 與其他工具的整合

6.1 與 synthcity 的整合(同一實驗室)

synthcity 和 TemporAI 都出自 vanderschaarlab,設計上具備互補性:

 1# 理想的整合流程(概念示範)
 2# 1. 用 synthcity 生成合成時序 EHR
 3from synthcity.plugins import Plugins
 4syn_model = Plugins().get("timegan")
 5syn_model.fit(real_temporal_data)
 6synthetic_data = syn_model.generate(count=1000)
 7
 8# 2. 轉換為 TemporAI Dataset 格式
 9from tempor.data.dataset import TemporalDataset
10dataset = TemporalDataset(
11    static=synthetic_static_df,
12    time_series=synthetic_temporal_df,
13    targets=synthetic_targets_df,
14)
15
16# 3. 用 TemporAI 進行分析
17from tempor import plugin_loader
18model = plugin_loader.get("time_to_event.dynamic_deephit")
19model.fit(dataset)

6.2 與 MIMIC-IV 的整合

TemporAI 提供官方的 MIMIC-IV 適配器:

1# 安裝 MIMIC-IV Data Pipeline 適配器
2pip install temporai-mivdp

詳見 temporai-mivdp 與內建教學 tutorial06_mimic_use_case.ipynb

6.3 與 Differential Privacy (DP; 差分隱私) 工具的整合

在使用 DP 工具(TF Privacy、Diffprivlib、OpenDP、SmartNoise、dp_cgans)生成隱私保護合成資料後,可直接餵入 TemporAI 進行下游分析。需注意 DP 雜訊 (Noise) 對時序模型的影響:

DP 方法對 TemporAI 的影響建議
高 epsilon (低隱私)時序特徵保留較好適合 Dynamic-DeepHit 等深度模型
低 epsilon (高隱私)時序相關性可能被破壞先用 Imputation 修復,或改用 robust 模型
Local DP每個時間點獨立加噪時序連續性損失大,需額外平滑處理

6.4 與 Synthea 的整合

Synthea 產生的 FHIR (Fast Healthcare Interoperability Resources) 格式病患記錄,需要轉換為 TemporAI 的 DataFrame 格式。建議的轉換管線:

1Synthea FHIR JSON → pandas DataFrame (ETL) → TemporAI TemporalDataset

6.5 生態系整合地圖

1Synthea ──FHIR──→ ETL ──→ 
2                           
3synthcity (TimeGAN) ──────→├──→ TemporAI ──→ 存活預測 / 治療效果 / 預測
4                                               
5MIMIC-IV temporai-mivdp─→┘                    ├──→ Benchmark 報告
6                                                ├──→ 反事實分析
7DP tools (隱私保護) ──→ 合成資料 ──→ TemporAI   └──→ AutoML 最佳模型

7. 優缺點分析

7.1 優點

面向說明
醫療專用設計不是通用時序工具硬套醫療場景,而是從 Survival Analysis、Treatment Effects 等臨床問題出發設計
統一 Plugin APIplugin_loader.get("xxx") 一行切換模型,學習曲線低、實驗迭代快
前沿模型封裝Dynamic-DeepHit、Neural CDE/ODE、CRN 等最新研究直接可用,不需自己實作
端到端 Pipeline從前處理到預測到 AutoML 到 Benchmark,一個框架解決
同實驗室生態系與 synthcity、HyperImpute 同源,整合無縫
MIMIC-IV 官方支援降低處理真實臨床資料的門檻
Apache-2.0 授權可商用、可修改、可再散布

7.2 缺點

面向說明
Alpha 狀態官方明確標示仍在 Alpha,API 可能不經通知即變更
方法數量有限相較 scikit-learn 生態系,內建模型種類偏少(約 20+ 個 Plugin)
社群規模小130 Stars / 24 Forks,社群支援和文件豐富度有限
CDISC 不支援無法直接匯入/匯出 SDTM/ADaM 格式,對 IND 送審有額外工作量
無內建合成資料生成僅作為分析端消費者,需搭配 synthcity 等工具產生合成資料
無 Interpretability 模組目前缺少 Post-hoc Explainability (事後可解釋性) 工具(如 SHAP for time series)
GPU 依賴深度學習模型(DeepHit、CRN)在大資料集上需 GPU,CPU 訓練速度慢
文件偏學術教學以 Jupyter Notebook 為主,缺少 Production Deployment (生產部署) 指引

7.3 適用場景建議

場景適合度說明
臨床試驗存活分析原型Dynamic-DeepHit + PBC 資料集可快速驗證概念
治療方案比較研究CRN 反事實推論是核心優勢
Pre-IND 階段可行性評估缺少 CDISC 支援,需額外 ETL
Production 級預測系統Alpha 狀態不適合直接上線
法規送審文件生成無 Regulatory Validation Framework

7.4 風險提醒

  • 版本穩定性:Alpha 階段意味著升版可能 Breaking Change,建議 Pin Version
  • 醫療 AI 法規:任何基於 TemporAI 的預測結果用於臨床決策前,需經過適當的 Clinical Validation (臨床驗證) 流程
  • HIPAA / GDPR / PDPA 合規:TemporAI 本身不提供隱私保護機制,需搭配上游 DP 工具確保合規
  • 可重現性:確保記錄 random_state、模型超參數、資料版本,以符合法規對 Reproducibility (可重現性) 的要求

參考資源