Skip to content

Add SequenceTransformerNetwork for clinical time series - #1662

Merged
solarsys merged 3 commits into
sunlabuiuc:masterfrom
ghiamalireza:contribution/sequence-transformer-review
Nov 29, 2026
Merged

solarsys merged 3 commits into
sunlabuiuc:masterfrom
ghiamalireza:contribution/sequence-transformer-review

Conversation

@ghiamalireza

@ghiamalireza ghiamalireza commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Adds a PyHealth model that learns a temporal affine transformation and a magnitude scale and shift for each sequence before CNN classification. We based it on Oh, Wang and Wiens, “Learning to Exploit Invariances in Clinical Time-Series Data using Sequence Transformer Networks,” MLHC 2018. The contribution includes a MIMIC-III demo experiment, synthetic tests, and API documentation.

Contribution type: Model. We implemented the model idea and evaluated it on the public demo because full MIMIC-III access was unavailable. The differences from the paper's benchmark are described below.

Contributors:

  • Matthew Nguyen (mnguyen358, mnguyen358@gatech.edu)
  • Alireza Ghiam (aghiam3, aghiam3@gatech.edu)

Behavior and implementation

SequenceTransformerNetwork inherits from BaseModel and uses fitted PyHealth label processors. It accepts dense time series tensors and numeric sequences with one level of variable length. It returns the standard logit, y_prob, loss, and y_true fields when labels are provided. A separate transform() method exposes the transformed series and learned parameters. Short sequences repeat their last value, and empty sequences become zeros. Disabling both transformations gives the CNN baseline.

The localizer follows the paper's diagram with 1D convolutions. The authors' released code uses 2D convolutions, a different parameter restriction, and different dropout placement. Our implementation uses a continuous leaky clamp and configurable dropout after the classifier's hidden layer. The model docs explain these choices.

Experiment and findings

The example uses the public MIMIC-III demo v1.4 with PyHealth's YAIB ICU mortality task. After filtering, the cohort contains 99 ICU stays from 70 patients, including 21 positive labels. Inputs contain 25 hourly bins numbered 0 through 24, with dynamic measurements and missing value indicators. We excluded the entire static input field, including age, sex, height, and weight, because the stock height and weight summaries can include measurements taken later in the stay. The original paper predicts hospital mortality from the first 48 hours.

We completed 60 fits across six configurations and ten patient splits. Each split assigns 60% of patients to training, 20% to validation, and 20% to testing. All stays from a patient remain in the same partition. Preprocessing is fitted on training patients only. Within each split, configurations share the initial CNN weights and training sample order. We used Adam with a learning rate of 0.001, batch size 15, and ten epochs. Evaluation uses the checkpoint with the lowest validation loss. The paper selected checkpoints using validation AUROC.

Configuration Test AUROC, mean ± SD Test average precision, mean ± SD
Baseline CNN 0.493 ± 0.109 0.399 ± 0.081
Temporal only 0.495 ± 0.106 0.396 ± 0.096
Magnitude only 0.453 ± 0.126 0.356 ± 0.126
STN, both 0.472 ± 0.140 0.368 ± 0.120
STN, dropout 0 0.462 ± 0.132 0.370 ± 0.103
STN, dropout 0.5 0.497 ± 0.126 0.380 ± 0.114

The full STN had lower mean scores than the baseline in this demo. We also compared dropout values of 0, 0.2, and 0.5 within the full model. Differences between these settings were small relative to the variation across splits. The paper already studies the temporal and magnitude components and tunes dropout. Our additional dropout runs examine sensitivity on this implementation and demo task.

The initial comparison used dropout 0.3 for CNN and 0.2 for STN, following the paper's selected values. We added --study matched-dropout to compare both models with dropout 0.2. It uses the same splits, classifier initialization, sample order, and training settings. These 20 additional fits bring the total to 80, including ten repeated fits of the full STN condition.

Configuration with dropout 0.2 Test AUROC, mean ± SD Test average precision, mean ± SD
CNN 0.478 ± 0.113 0.387 ± 0.100
STN 0.472 ± 0.140 0.368 ± 0.120

Subtracting CNN from STN within each split gives mean differences of −0.0062 ± 0.1108 AUROC and −0.0191 ± 0.0894 AP. STN has higher AUROC on five splits, ties on three, and lower AUROC on two. For AP, it has four wins, two ties, and four losses. Absolute differences of at most 1e−12 count as ties. One larger negative split difference affects the means, and all runs are included. Matching dropout did not show a consistent STN benefit. STN also has the extra localizer, so the models still differ in capacity.

The demo is small and consists of patients who eventually died, although ICU mortality labels can still be either class. YAIB's cohort selection still uses information from across the stay. The splits overlap, and the reported sample SD describes variation across those splits. We did not perform significance tests. The task, features, cohort, architecture, and checkpoint rule differ from the original paper, which limits what these results can say about its reported improvement. AP is computed with scikit-learn's average_precision_score.

Validation

  • 27 synthetic tests and five subtests passed. They cover initialization, forward and backward passes, interpolation, disabled transformations, tensor and jagged inputs, empty sequences, and saving and loading model state.
  • A regression test changes later height and weight measurements and checks that the example's dynamic inputs and predictions stay the same. The retrospective cohort selection remains a limitation.
  • Ruff lint and formatting checks passed for all four Python files. The local PR contribution checks also passed.
  • Both experiments completed on CPU. Running the example saves the scores, split counts, settings, software versions, and source hashes to a local JSON file.
  • The original 60 fits used PyHealth revision 454b394340f6c2e078c9f54e09668ad79ae17199. The 20 control fits used contribution revision 33776d8ac362d50ea152f55770007fe2c0104f1f with the study selector changes applied. All ten repeated STN runs exactly reproduced their original metrics.
  • The current PR was rebased onto upstream revision 089b35645f59ff37cc75f2b6ff5a3fdafa63874e. All 27 tests and five subtests passed again on PR revision a12c7e9579bdf18bc58e16865a07d7f0d01ced3e, using Python 3.12.

File guide

File Purpose
pyhealth/models/sequence_transformer.py Model, localizer, sampler, and CNN
pyhealth/models/__init__.py Public model and helper exports
tests/core/test_sequence_transformer.py Model tests using synthetic inputs
tests/core/test_sequence_transformer_example.py Regression test for later height and weight measurements
examples/mimic3_mortality_sequence_transformer.py Demo results, both experiments, and how to compute the paired differences
docs/api/models/pyhealth.models.SequenceTransformerNetwork.rst Model docs and demo setup
docs/api/models.rst Model documentation index entry
python -m pytest tests/core/test_sequence_transformer.py \
  tests/core/test_sequence_transformer_example.py -q

python examples/mimic3_mortality_sequence_transformer.py \
  --root /path/to/mimic-iii-clinical-database-demo-1.4

python examples/mimic3_mortality_sequence_transformer.py \
  --root /path/to/mimic-iii-clinical-database-demo-1.4 \
  --study matched-dropout

The example runs the six configurations by default. Each study writes its own JSON file. Use --output to choose the path.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.51% (52820 / 60361 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 108 / 108
pyhealth/models/deephit.py 95.27% 141 / 148
pyhealth/models/hicu.py 96.61% 285 / 295
pyhealth/models/sequence_transformer.py 95.12% 156 / 164
pyhealth/tasks/__init__.py 98.35% 119 / 121
pyhealth/tasks/mimic3_icd9_category_classification.py 100.00% 70 / 70

Workflow run · 9b2bdfb

Alireza Ghiam and others added 2 commits November 28, 2026 10:41
Implement the model with synthetic tests, API documentation, and a runnable
MIMIC-III demo experiment. Record the scoped reproduction limitations and
the completed six-configuration, ten-split study.

Co-authored-by: Matthew Nguyen <mnguyen358@gatech.edu>
Compare CNN and STN at dropout 0.2 using the same ten patient splits, classifier initialization, and training procedure. Preserve the historical six-configuration results and record all 20 control fits with separate provenance.

Co-authored-by: Matthew Nguyen <mnguyen358@gatech.edu>
@solarsys solarsys added the status: manual Pending maintainer's review label Nov 28, 2026
@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.

Previous review

Reviewed commit a12c7e9

@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.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for contributing SequenceTransformerNetwork. It adds a time-warp and magnitude-transformer model for clinical time series, with a MIMIC-III demo experiment, tests and API docs. It looks ready to merge.

What I checked:

  • The model is self-contained. It subclasses BaseModel without changing it. The pyhealth/models/__init__.py change only adds exports, so it counts as registration.
  • The links to other components are named in the description with a clear purpose. The example subclasses YAIBMortalityMIMIC3 to drop the static fields, and the regression test loads the example module to check that later height and weight values don't change the inputs.
  • Coverage meets the bar. The new model file is at 95.12% and the whole repository at 87.43%.
  • The docs match the code. The description states the differences from the paper, the use of the demo data, and the limits of the results.
  • The paper is cited in the model docstring. The model is not a dataset, so no dataset source link is needed.

Optional suggestions:

  • The docstring mentions the deprecated sequence_v2 name. Consider updating it.
  • Jagged fields and irregular timestamps are read as evenly spaced steps. Dense 2-D tensors are treated as static features. A short note in the docstring would help users.
  • The paired-difference statistics in the description come from no code in the PR. You could add a short script, or say how they were computed.

Reviewed commit a12c7e9

@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: it adds files at the repo root, README_STN.md and results/*.json. Only changes under docs/ examples/ pyhealth/ test-resources/ tests/ can go through automatic review. The AI review already suggests approve, so this is the only thing in the way.

To make it eligible for automatic review:

  • Move the useful parts of README_STN.md into the model's docs page (docs/api/models/pyhealth.models.SequenceTransformerNetwork.rst) or the example's module docstring.
  • Drop the results/ JSON files. A short results table in the example's docstring is enough; raw run outputs don't belong in the repo.

Once that's pushed, we'll switch the label to status: automatic and request a fresh AI review. If the AI review approves, it merges the PR.

@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 9b2bdfb

value = torch.as_tensor(value).to(self.device).float()
if value.dim() == 1:
value = value.unsqueeze(-1)
if value.dim() == 2:

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] 2D dense tensors are silently treated as static features

In series(), any dense tensor with two dimensions is treated as a static [batch, features] vector and broadcast across all time steps. A univariate series passed as [batch, time] therefore becomes time constant channels with no temporal information, and no error is raised. The contract is documented in the class docstring, so this is not a blocker, but it is an easy silent misuse. Consider requiring 3D [batch, time, features] for series fields and rejecting ambiguous 2D inputs with a clear error, or documenting the [batch, time] case explicitly.

"supported (not tokens or nested records)."
)
offsets = value[-1].long()
parts = [fields[(0, "values")].flatten(1).float()]

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] The jagged series time role is ignored

_jagged reads only the values and mask roles and uses record position as the time step. For YAIB's dense hourly grid (YAIBMortalityMIMIC3._dynamic emits one row per hour) position equals hour, so the demo is correct. For any other ordering: series input with irregular timestamps, the temporal transform would silently treat gaps as consecutive steps. Add a sentence to the class docstring saying that series records are assumed to be consecutive bins, or raise when a series field has a time role that is not a regular grid.

@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 contributing SequenceTransformerNetwork. It adds a new model that learns a per-sample temporal warp and magnitude shift and scale before a CNN classifier. It comes with documentation, a MIMIC-III demo experiment, and tests. It looks ready to merge.

  • Model: It subclasses BaseModel and doesn't modify any shared code. The only change outside the new files is registering exports in pyhealth/models/__init__.py.
  • Sharing between components: The example subclasses YAIBMortalityMIMIC3 as DynamicOnlyMortality. The description explains why: it drops the static fields that can leak later height and weight values.
  • Coverage: sequence_transformer.py is at 95.12%, above the 80% bar. Total repository coverage is 87.51%, above the 60% bar.
  • Documentation: The docs match the code. They state clearly how the model and demo differ from the paper.

Optional suggestions:

  • A 2D dense tensor of shape [batch, time] is always treated as a static feature vector, so a univariate series would silently become constant channels. A line in the docstring would help.
  • The jagged path ignores the series time role and assumes an already regular grid. A note in the docstring would help here too.
  • The example summary prints nanmean over splits. You could state the number of valid splits if a test partition ever lacks positive labels.

Reviewed commit 9b2bdfb

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving. Thanks for moving the README content and results out of the repo root.

@solarsys
solarsys merged commit e01a4ee into sunlabuiuc:master Nov 29, 2026
3 checks passed
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