Skip to content

Add TaskAug model for binary ECG classification and paired PTB-XL MI evaluation - #1685

Open
Michaelwyx wants to merge 1 commit into
sunlabuiuc:masterfrom
Michaelwyx:taskaug-ptbxl-mi-nov28
Open

Michaelwyx wants to merge 1 commit into
sunlabuiuc:masterfrom
Michaelwyx:taskaug-ptbxl-mi-nov28

Conversation

@Michaelwyx

Copy link
Copy Markdown

Contributor: Yixuan Wang (yixuan41@illinois.edu, NetID yixuan41)

Contribution Type: Model (pyhealth.models.TaskAug) — CS 598 Deep Learning for Healthcare reproducibility contribution (developed with Codex assistance)

Original Paper: Raghu et al., Data Augmentation for Electrocardiograms, CHIL 2022 (Paper · Authors' reference code)


High-Level Description

This PR adds TaskAug (pyhealth.models.TaskAug), a BaseModel implementation adapting task-dependent ECG data augmentation for binary ECG classification in PyHealth:

  • Wraps PyHealth's 4-stage 1D ResNet1dBackbone (61,841 parameters at width=8) with a two-stage categorical augmentation policy over 7 operations (warp, wander, noise, mask, shift, scale, identity), where the 5 continuous transforms learn class-conditional magnitudes.
  • Classifier updates (forward) train on augmented ECGs without updating policy parameters; a separate policy_step() method updates only the policy via a truncated implicit hypergradient (Neumann series) using clean validation loss while keeping BatchNorm buffers private.
  • At inference (eval()), the model takes raw waveforms without labels.
  • Compared with the authors' public implementation, this adaptation uses a monotone speed-integrated temporal warp, bounded continuous transformation strengths, direct operation application (without per-class application gates), and 100 Hz PTB-XL v1.0.3 inputs via PyHealth's existing PTB-XL record reader and SCP diagnostic superclass mapping (PTB-XL v1.0.3).

Ablation Study & Missing-Lead Extension (examples/ptbxl_mi_taskaug.py)

Each of five paired seeds (41–45) draws 800 training ECGs (folds 1–8) and 200 validation ECGs (fold 9), fits per-lead normalization on the training split only, and evaluates on all 2,198 test ECGs in fold 10 (1,904 patient-disjoint test patients, 550 MI-positive). All four conditions share identical splits, classifier initialization, and minibatch order within a seed.

  • Ablations included: (1) validation-selected fixed time-mask width across {10%, 20%, 50%}, and (2) a frozen stochastic policy ablation (initial policy sampled without policy updates) to separate random transform diversity from policy learning.
  • Extension included: holding each selected checkpoint fixed (no retraining), replace standardized Lead II or Lead V1 with zero (its training mean) at test time and compare clean vs. missing-lead discrimination on the same test cohort.

Clean AUROC and average precision (AP) are percentages reported as mean ± standard error across the 5 seeds:

Training condition Clean AUROC (%) Clean AP (%) AUROC without II (%) AUROC without V1 (%)
No augmentation 77.62 ± 0.50 55.05 ± 1.02 75.74 76.73
Fixed time mask 78.57 ± 1.22 57.44 ± 1.40 76.37 78.17
Frozen policy (ablation) 79.63 ± 0.31 58.00 ± 0.73 78.30 78.59
Learned policy (TaskAug) 80.41 ± 0.37 59.98 ± 0.84 78.92 79.48
  • Clean reproduction: Learned TaskAug gained +2.78 AUROC points over no augmentation (improved in 5/5 seeds; 95% patient-bootstrap CI [+2.03, +3.56]), matching the direction of the paper's +2.3-point gain (80.0 → 82.3). Against the frozen policy ablation, learning added +0.78 AUROC points and +1.98 AP points across 4 seeds (seed 45 selected epoch 4 before the first policy update and tied frozen exactly).
  • Missing-lead extension: Removing Lead II reduced mean AUROC by 1.49 pts for the learned policy vs. 1.88 pts without augmentation; removing V1 reduced AUROC by 0.93 vs. 0.90 pts. The learned policy retained the highest absolute AUROC under both failures (78.92% without II; 79.48% without V1), while the smallest relative drop depended on which lead was removed.

Files to Review

  • pyhealth/models/taskaug.py — TaskAug model (BaseModel), 7 ECG transforms, and truncated implicit hypergradient policy_step().
  • pyhealth/models/__init__.py — exports TaskAug.
  • tests/core/test_taskaug.py — fast synthetic unit tests (PyHealth batch interface, label-free inference, state_dict save/load, fixed masking, class-conditional transform gradients, classifier/policy update separation, input validation, and an analytic finite-difference hypergradient check).
  • examples/ptbxl_mi_taskaug.py — runnable training/ablation/missing-lead evaluation script (supports --smoke on synthetic tensors and full PTB-XL reproduction/replay).
  • examples/ptbxl_taskaug_data.py — PTB-XL v1.0.3 binary MI cohort loader, patient-disjoint fold sampling, and train-only per-lead standardization.
  • docs/api/models/pyhealth.models.taskaug.rst & docs/api/models.rst — API documentation and index entry.

Reproduction & Verification

Run unit tests and the synthetic smoke example (CPU, seconds):

python -m pip install -e '.[ptbxl]' pytest
python -m pytest -q tests/core/test_taskaug.py
python examples/ptbxl_mi_taskaug.py --smoke --output taskaug-smoke

Full PTB-XL v1.0.3 experiment (PTBXL_ROOT containing metadata CSVs and records100/; supports cpu, mps, cuda):

python examples/ptbxl_mi_taskaug.py --root "${PTBXL_ROOT}" \
    --output taskaug-mi-results --cache-dir taskaug-waveform-cache \
    --device mps --seeds 41 42 43 44 45 --epochs 100 --patience 8 \
    --width 8 --batch-size 64 --policy-batch 32 --policy-every 1 \
    --warmup 5 --mask-fractions 0.1 0.2 0.5 --lr 0.001 --policy-lr 0.01

Relationship to Earlier Contributions

Other public PRs also explore TaskAug or ECG lead masking: PR #1490 targets 71 diagnostic codes, PR #1598 studies cross-backbone transfer in binary MI, and closed PR #1123 studied random lead dropout during training. This contribution provides a clean BaseModel adaptation with a finite-difference-verified hypergradient, a paired frozen-policy ablation, and a fixed-checkpoint single-lead (II / V1) stress test.

Developed with OpenAI Codex assistance. Includes synthetic checks, API documentation, train-only preprocessing, and clean and missing-lead comparisons.
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 87.99% (55969 / 63609 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 117 / 117
pyhealth/models/taskaug.py 99.30% 141 / 142

Workflow run · dca1693

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 29, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: overlap. Yesterday the maintainers compared the open TaskAug PRs and picked #1598 to merge first. It's the only one that implements the paper's bilevel optimization of the augmentation policy, with the implicit-function hypergradient checked against finite differences. Its binary PTB-XL task matches the authors' labels. This PR adds pyhealth/models/taskaug.py, the same path as #1598, so the two can't both merge. The decision is recorded in #1668.

What you can contribute instead. After #1598 merges, rebase and keep only what yours adds, as an option on #1598's TaskAugPolicy or as an example. Two possibilities: your paired PTB-XL MI evaluation, or an augmentation operation #1598 lacks. Please drop the duplicate model. If you think your implementation is better on a specific point, comment here with details.

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit dca1693

return signals


def load_ptbxl_mi(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Cohort loader for the reported MI results has no tests

load_ptbxl_mi carries the data-integrity claims the description makes: patient-disjoint folds, label-stratified 800/200 sampling, MI labels from the SCP mapping, normalization fit on the training split only, and the manifest check used by replay. None of this is tested. tests/core/test_taskaug.py covers only the model, and the --smoke path uses synthetic() and never calls this loader. The --checkpoints replay branch in examples/ptbxl_mi_taskaug.py is also never exercised by the smoke run. The existing PTB-XL dataset and task have tests in tests/core/test_ptbxl.py. Add a small test that writes a tiny ptbxl_database.csv and scp_statements.csv and stubs the record reader. It should check that _stratify keeps both classes and the requested size, that no patient appears in more than one split, that normalization statistics come from the training split only, and that a replay with a mismatched manifest raises.

**kwargs: Dataset-named fields or ``waveform`` of shape
(batch, leads, time) and optional ``label`` of shape (batch,)
or (batch, 1). Augmentation requires both training mode and
labels. Call ``eval()`` to use stored normalization statistics.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] forward docstring implies stored normalization statistics

The sentence says eval() is needed "to use stored normalization statistics". TaskAug stores no input normalization. eval() only turns off augmentation and makes BatchNorm use running statistics. Reword it to say that, for example, "Call eval() to disable augmentation and use BatchNorm running statistics."

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. TaskAug adds a BaseModel for binary ECG classification with a learned two-stage augmentation policy and a truncated implicit hypergradient policy_step(). It comes with a PTB-XL MI ablation and a missing-lead example. It looks ready to merge.

Checks:

  • The model is self-contained. The only change to existing code is the export line in pyhealth/models/__init__.py, which is registration.
  • Your description names the sharing of ResNet1dBackbone and the PTB-XL record and superclass helpers, with a clear purpose.
  • Coverage is 99.3% for pyhealth/models/taskaug.py and 87.99% for the whole repository. Both meet the bar. The tests are thorough and include a finite-difference hypergradient check.
  • The docs match the code.

Optional suggestions:

  • The description says the learned policy's +0.78 AUROC gain over the frozen policy is "across 4 seeds". The mean seems to be over 5 seeds, with seed 45 tied at zero. Please make the wording consistent.
  • The bootstrap CI and the aggregate tables aren't produced by any script in the PR. Consider adding the aggregation script, or saying how you computed them.
  • load_ptbxl_mi in examples/ptbxl_taskaug_data.py has no tests, and the smoke run bypasses it and the --checkpoints replay path. A small test with a mock PTB-XL CSV would help, but it isn't blocking for an example script.
  • The loader keeps ECGs with no diagnostic superclass as negatives. This differs from the default in the existing PTB-XL superclass task. Consider a sentence in the docs about that choice.

Reviewed commit dca1693

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants