Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
b5f4b8f
update dreamt dataset with stage mapping
NathanCYee Nov 27, 2026
a05a969
add sleep staging and ibi transformation processor
NathanCYee Nov 27, 2026
25dee6e
add tests for sleep staging ibi task
NathanCYee Nov 27, 2026
b4c603e
extend dataset tests with ibi processing
NathanCYee Nov 27, 2026
78ac479
add references to original watchsleepnet repo
NathanCYee Nov 27, 2026
c14ad2c
add watchsleepnet model
NathanCYee Nov 27, 2026
186514a
add tests for watchsleepnet
NathanCYee Nov 27, 2026
55ffe75
add comments to reference where the original watchsleep code from pap…
NathanCYee Nov 27, 2026
017bd1a
add custom losses
NathanCYee Nov 27, 2026
07398b5
add examples
NathanCYee Nov 27, 2026
85e031a
add sleep accel dataset class
NathanCYee Nov 27, 2026
c50e502
add ibi processing for isruc (existing dataset) and sleep-accel
NathanCYee Nov 28, 2026
d6fe2b7
update tests to factor in isruc and sleep accel, remove references to…
NathanCYee Nov 28, 2026
dd60db3
update documentation
NathanCYee Nov 28, 2026
6733436
update examples to use isruc and sleep accel, remove stale docs from …
NathanCYee Nov 28, 2026
0e8bab9
add new evaluation script on trained model and any given dataset
NathanCYee Nov 28, 2026
7f71acf
set default behavior to zero-out no signal sections of sleep accel (m…
NathanCYee Nov 28, 2026
aeb445b
Merge branch 'master' of https://github.com/NathanCYee/PyHealth into …
NathanCYee Nov 28, 2026
3479d2a
remove unused ablation example
NathanCYee Nov 28, 2026
c47e707
reformat long comments
NathanCYee Nov 28, 2026
a89c287
add synthetic data generator for testing
NathanCYee Nov 28, 2026
b9c4427
update isruc processing to check other columns in transducer as fallback
NathanCYee Nov 28, 2026
772116d
update isruc tests to simulate transducer column
NathanCYee Nov 28, 2026
09553b7
update evaluation to reuse cache instead of reprocessing
NathanCYee Nov 28, 2026
359adc9
add readme to watchsleepnet examples
NathanCYee Nov 28, 2026
11e1933
Merge branch 'master' of https://github.com/NathanCYee/PyHealth into …
NathanCYee Nov 28, 2026
63ee7bb
add citation to watchsleepnet paper
NathanCYee Nov 28, 2026
f8b9f5d
remove unnecessary nsrr sleep comments
NathanCYee Nov 29, 2026
de45f1c
migrate added ibi tests to their own test suite
NathanCYee Nov 29, 2026
f72628d
change backend default from auto to scipy and make user opt in to uni…
NathanCYee Nov 29, 2026
c18a77e
update examples with new backend
NathanCYee Nov 29, 2026
b3af457
move dreamt task-specific helpers to the task
NathanCYee Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/api/datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,11 @@ PyHealth does not ship any data: you download each dataset from its source and p
- `ISRUC <https://sleeptight.isr.uc.pt/>`__
- No
- —
* - :doc:`Sleep-Accel <datasets/pyhealth.datasets.SleepAccelDataset>`
- Open
- `PhysioNet <https://physionet.org/content/sleep-accel/1.0.0/>`__
- No
- —
* - :doc:`EESM23 (ear-EEG) <datasets/pyhealth.datasets.EESM23Dataset>`
- Open
- `OpenNeuro <https://openneuro.org/datasets/ds005178>`__
Expand Down Expand Up @@ -670,6 +675,7 @@ Available Datasets
datasets/pyhealth.datasets.DREAMTDataset
datasets/pyhealth.datasets.SHHSDataset
datasets/pyhealth.datasets.SleepEDFDataset
datasets/pyhealth.datasets.SleepAccelDataset
datasets/pyhealth.datasets.NSRRSleepDataset
datasets/pyhealth.datasets.EHRShotDataset
datasets/pyhealth.datasets.Support2Dataset
Expand Down
17 changes: 17 additions & 0 deletions docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
pyhealth.datasets.SleepAccelDataset
===================================

PhysioNet Sleep-Accel contains wrist heart rate, acceleration, step counts and
30 s sleep-stage labels from a night of polysomnography. The PyHealth loader
writes ``sleep_accel-pyhealth.csv`` with absolute paths for each complete
subject and exposes the four modalities as one event per recording.

Because the dataset has no raw PPG or ECG waveform, IBI staging derives
``60 / bpm`` samples from the heart-rate stream. Use
:class:`~pyhealth.tasks.SleepStagingIBISleepAccel` to build the shared
``(T, 750)`` IBI tensors and three-class labels.

.. autoclass:: pyhealth.datasets.SleepAccelDataset
:members:
:undoc-members:
:show-inheritance:
4 changes: 4 additions & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ routes each feature type automatically.
* - :doc:`models/pyhealth.models.UNet`
- Your task is pixel/voxel-level segmentation with an image and a mask
- ``UNet2D``/``UNet3D``; pair with ``PatchDataset``, ``PatchSampler`` and Dice/IoU metrics
* - :doc:`models/pyhealth.models.WatchSleepNet`
- You have whole-night IBI sequences and want one sleep-stage label per 30 s epoch
- CNN + TCN + BiLSTM + attention; masks padded and unknown epochs from loss/metrics
* - :doc:`models/pyhealth.models.GNN`
- Features include graph-structured data
- Works with ``GraphProcessor``; see :doc:`graph` for setup
Expand Down Expand Up @@ -328,6 +331,7 @@ API Reference
models/pyhealth.models.CLIPStress
models/pyhealth.models.EEGNet
models/pyhealth.models.DeepSleepNet
models/pyhealth.models.WatchSleepNet
models/pyhealth.models.SleepKD
models/pyhealth.models.SparcNet
models/pyhealth.models.StageNet
Expand Down
19 changes: 19 additions & 0 deletions docs/api/models/pyhealth.models.WatchSleepNet.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
pyhealth.models.WatchSleepNet
===================================

WatchSleepNet, a CNN + TCN + BiLSTM + attention model that stages every 30 s epoch of an IBI sequence.

This module is a PyHealth implementation of the original WatchSleepNet paper:

Wang, W.K., Chen, B., Yang, J., Jeong, H., Hershkovich, L., Islam, S.M.M.,
Liu, M., Roghanizad, A.R., Shandhi, M.M.H., Spector, A.R. & Dunn, J. (2025).
`WatchSleepNet: A Novel Model and Pretraining Approach for Advancing Sleep
Staging with Smartwatches
<https://proceedings.mlr.press/v287/wang25a.html>`_. Proceedings of the sixth
Conference on Health, Inference, and Learning (CHIL 2025), Proceedings of
Machine Learning Research 287:145-165.

.. autoclass:: pyhealth.models.WatchSleepNet
:members:
:undoc-members:
:show-inheritance:
5 changes: 5 additions & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,11 @@ Available Tasks
Sleep Staging (SleepEDF) <tasks/pyhealth.tasks.SleepStagingSleepEDF>
Sleep-EDF Forecasting <tasks/pyhealth.tasks.SleepEDFForecasting>
Sleep Staging (Cardio-Respiratory, NSRR) <tasks/pyhealth.tasks.SleepStagingCardioRespiratory>
IBI Sleep Staging (DREAMT) <tasks/pyhealth.tasks.SleepStagingIBIDREAMT>
IBI Sleep Staging (NSRR SHHS) <tasks/pyhealth.tasks.SleepStagingIBISHHS>
IBI Sleep Staging (NSRR MESA) <tasks/pyhealth.tasks.SleepStagingIBIMESA>
IBI Sleep Staging (ISRUC) <tasks/pyhealth.tasks.SleepStagingIBIISRUC>
IBI Sleep Staging (Sleep-Accel) <tasks/pyhealth.tasks.SleepStagingIBISleepAccel>
Sleep Staging Sequences (SleepEDF) <tasks/pyhealth.tasks.SleepStagingSequenceSleepEDF>
Sleep Staging (ISRUC) <tasks/pyhealth.tasks.SleepStagingISRUC>
Sleep Staging Sequences (ISRUC) <tasks/pyhealth.tasks.SleepStagingSequenceISRUC>
Expand Down
11 changes: 11 additions & 0 deletions docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
pyhealth.tasks.SleepStagingIBIDREAMT
=====================================

Per-recording inter-beat-interval sleep staging for DREAMT. Reads the
``data_100Hz`` BVP signal by default, recovers the 30 s epoch grid from stage
changes, and emits ``(T, 750)`` IBI tensors with three-class labels.

.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIDREAMT
:members:
:undoc-members:
:show-inheritance:
13 changes: 13 additions & 0 deletions docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
pyhealth.tasks.SleepStagingIBIISRUC
===================================

ECG-derived inter-beat-interval sleep staging for ISRUC-Sleep. By default the
task reads the ``X2`` ECG channel at its native 200 Hz rate, strides the IBI
signal by eight, and emits ``(T, 750)`` tensors with three-class labels. Choose
``scorer="expert2"`` to use the second expert's hypnogram instead of the
first.

.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIISRUC
:members:
:undoc-members:
:show-inheritance:
11 changes: 11 additions & 0 deletions docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
pyhealth.tasks.SleepStagingIBIMESA
===================================

Per-recording inter-beat-interval sleep staging for NSRR MESA. Resamples the
Pleth channel from 256 Hz to 100 Hz, strides IBI by four, and emits
``(T, 750)`` tensors with three-class labels.

.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIMESA
:members:
:undoc-members:
:show-inheritance:
11 changes: 11 additions & 0 deletions docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
pyhealth.tasks.SleepStagingIBISHHS
===================================

Per-recording inter-beat-interval sleep staging for NSRR SHHS. Reads the ECG
channel at 125 Hz, strides IBI by five, and emits ``(T, 750)`` tensors with
three-class labels.

.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISHHS
:members:
:undoc-members:
:show-inheritance:
12 changes: 12 additions & 0 deletions docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
pyhealth.tasks.SleepStagingIBISleepAccel
========================================

Heart-rate-derived inter-beat-interval sleep staging for Sleep-Accel. The task
interpolates ``60 / bpm`` onto a 25 Hz grid and emits ``(T, 750)`` tensors with
three-class labels. It maps R&K stages to Wake ``0``, NREM ``1``, REM ``2`` and
unknown ``-1``, and caps each recording at 1100 epochs by default.

.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISleepAccel
:members:
:undoc-members:
:show-inheritance:
135 changes: 135 additions & 0 deletions examples/watchsleepnet/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# WatchSleepNet Examples

WatchSleepNet is a sleep-stage classification algorithm that uses inter-beat interval (IBI) signals derived from polysomnography (PSG) data (ECG, PPG, heart rate). The original paper utilized a two-stage pre-training process, where the model was pre-trained on a large corpus of high quality PSG data like the Sleep Heart Health Study (SHHS) and the Multi-Ethnic Study of Atherosclerosis (MESA) and then fine-tuned on a smaller set of data collected from wearable devices like the Dataset for Real-time sleep stage EstimAtion using Multisensor wearable Technology (DREAMT).

These examples run an end-to-end pipeline for processing datasets to extract IBI from signals, pre-training a model, fine-tuning, and then performing evaluation of a trained model.

Run the commands from the PyHealth repository root with the environment where PyHealth is installed.

## Synthetic Data Generation

If you do not have access to the restricted datasets (SHHS, MESA, DREAMT), the synthetic data generator script can be used to generate datasets for testing. Run the command and pass in the desired dataset to generate (`dreamt`, `mesa`, `shhs`), the number of samples, and the output folder path.

```bash
python examples/watchsleepnet/watchsleepnet_synthetic_data.py \
--dataset shhs --num-samples 5 --output-dir synthetic/shhs
```

The script will create a folder with the same structure and simulated PSG files as the target dataset. Since the PSG files are randomly generated, they will likely result in poor model training results compared to real data but they can be used to validate the pipeline works.

Generate enough samples for a 60/20/20 train/test/validate split. Each recording defaults to 20 epochs of 30 seconds; use `--epochs` to change this, `--seed` for deterministic output, and `--overwrite` to replace a non-empty output directory. If `--output-dir` is omitted, the dataset is written to `synthetic_data/<dataset>`.

## Training Model

To train the model, specify paths to the SHHS and MESA dataset, output path, and number of epochs.

The script will perform data transformation to IBI and train the model on the extracted IBI. `--loss` accepts `ce` (default), `weighted_ce`, `focal`, or `inverse_focal`.

```bash
python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
--shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
--output-dir output/watchsleepnet-pretrain
```

The output directory contains `pretrained.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable PyHealth cache under `cache/shhs` and `cache/mesa`.

### Ablations

Use `--quantization` to train with `fp32` (default), `bf16`, or `fp16` compute:

```bash
python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
--shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
--output-dir output/watchsleepnet-pretrain-bf16 --quantization bf16
```

Architecture flags override the defaults for one run. For example, to disable the TCN and self-attention and shrink the model:

```bash
python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \
--shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \
--output-dir output/watchsleepnet-no-tcn-attn \
--use-tcn false --use-attention false \
--hidden-dim 128 --num-heads 8 --num-layers 2 --tcn-layers 1
```

## Fine Tuning Model

After a model is trained, a `pretrained.pt` model checkpoint will be saved in the output folder. This checkpoint is used for reloading the model for further training or evaluation.

To fine tune the model, specify the checkpoint model path, the dataset, path to the fine tune dataset, number of epochs to fine tune, and the output folder for the trained model. `--loss` and the architecture flags from the pretraining section can also be overridden here.

```bash
python examples/watchsleepnet/watchsleepnet_finetune.py --dataset dreamt \
--root /path/to/dreamt \
--checkpoint output/watchsleepnet-pretrain/pretrained.pt \
--epochs 5 --output-dir output/watchsleepnet-finetune
```

The output directory contains `finetuned.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable cache under `cache`.

## Quantizing Model

A model trained at full precision `fp32` can be quantized to a lower precision `bf16` or `fp16`.

```bash
python examples/watchsleepnet/watchsleepnet_quantize.py \
--checkpoint output/watchsleepnet-pretrain/pretrained.pt \
--output output/watchsleepnet-pretrain/pretrained_bf16.pt \
--quantization bf16
```

The quantized model will be saved to a separate `.pt` file that can be loaded for further fine tuning or evaluation. A `quantization.json` report (or the path passed to `--report`) records the resulting tensor dtype counts.

## Evaluating Performance

To evaluate a trained model checkpoint, specify the dataset, path to the dataset, the trained model checkpoint, and the output folder.

To avoid reprocessing the dataset, pass `--cache-dir` pointing to the PyHealth cache generated during training or fine tuning.

```bash
python examples/watchsleepnet/watchsleepnet_evaluate.py \
--checkpoint output/watchsleepnet-finetune/finetuned.pt \
--dataset dreamt --root /path/to/dreamt \
--cache-dir output/watchsleepnet-finetune/cache \
--output-dir output/watchsleepnet-evaluate
```

Evaluation reuses the task settings stored in the checkpoint (`points_per_epoch`, `max_epochs`, `signal_source`, and `scorer`); the matching CLI flags override them. The output folder saves `results.csv`, `results.json`, and `confusion_matrix.png` with overall metrics (Accuracy, macro/weighted F1, AUROC, Cohen's Kappa) and per-class Wake/NREM/REM F1.

All real-data training and evaluation scripts accept `--peak-backend`; it defaults to `scipy` so IBI extraction is reproducible. Pass `--peak-backend auto`, `neurokit`, or `biosppy` to opt into the reference detectors, which require optional packages that PyHealth does not install.

## Additional Datasets

Two additional datasets that were not used by the original model were implemented: Sleep-Accel and ISRUC. For ISRUC, IBI signals are extracted from the ECG channel; for Sleep-Accel, they are extracted from heart rate.

For ISRUC, point `--root` at one extracted subgroup folder. Each subject folder contains `<id>/<id>.rec` plus the expert hypnograms `<id>_1.txt` and `<id>_2.txt`. The ECG channel may be named (`X2`, `ECG`, `EKG`, etc.) or, in some exports, numerically labelled; in the latter case the EDF transducer field (`EKG_Channel`) is used to locate it. Use `--scorer expert1` (default) or `expert2`.

```bash
python examples/watchsleepnet/watchsleepnet_finetune.py --dataset isruc \
--root /path/to/ISRUC-Sleep-I \
--checkpoint output/watchsleepnet-pretrain/pretrained.pt \
--epochs 10 --output-dir output/watchsleepnet-finetune-isruc
```

For Sleep-Accel, point `--root` at a directory containing `heart_rate/`, `labels/`, `motion/`, and `steps/` subdirectories.

```bash
python examples/watchsleepnet/watchsleepnet_finetune.py --dataset sleep_accel \
--root /path/to/sleep-accel \
--checkpoint output/watchsleepnet-pretrain/pretrained.pt \
--epochs 10 --output-dir output/watchsleepnet-finetune-sleep-accel
```

To evaluate a trained model on either dataset, use the same `--dataset` and `--root` pattern (plus `--cache-dir` to reuse the training cache).

```bash
python examples/watchsleepnet/watchsleepnet_evaluate.py \
--checkpoint output/watchsleepnet-finetune-sleep-accel/finetuned.pt \
--dataset sleep_accel --root /path/to/sleep-accel \
--cache-dir output/watchsleepnet-finetune-sleep-accel/cache \
--output-dir output/watchsleepnet-evaluate-sleep-accel
```

`sleep-accel` is not a valid dataset name; use `sleep_accel`.

Loading