DeepSleep 2.0 is a compact, U-Net-inspired 1D fully convolutional network that segments non-apnea sleep arousals from full-length, multi-channel polysomnographic (PSG) recordings at native 5-millisecond resolution. With only 740,551 trainable parameters, it is a lightweight successor to DeepSleep, the network that achieved the highest unofficial score in the 2018 PhysioNet/CinC Challenge, reaching comparable accuracy at a fraction of the depth, memory, and compute. Full details are in the open-access paper published in AI (MDPI, 2022).
π¬ A 300-second window of a 13-channel PSG recording with the model's predicted arousal probability (red) overlaid on the ground-truth labels (black).
Note
Training (or re-scoring) requires the ~135 GB PhysioNet/CinC 2018 Challenge training folder. See data/README.md for download instructions. The repository ships with pretrained checkpoints and cached test scores, so you can reproduce the results table below without the dataset and without a GPU.
Sleep arousals are brief intrusions of wakefulness that fragment sleep. Detecting them from PSG is laborious to do by hand and highly imbalanced (arousals are sparse). DeepSleep 2.0 casts this as a dense, per-sample segmentation problem: it consumes an entire night of raw multi-channel signal and outputs an arousal probability for every 5 ms time step in a single forward pass, with no windowing or patching at inference.
- πͺΆ Compact: a 5-level encoder/decoder with just 740,551 parameters (vs. 11 levels in the original DeepSleep).
- π Full-length input: processes complete raw PSG recordings end-to-end, padded and centered to 2Β²Β³ (8,388,608) samples.
- β±οΈ Native 5 ms resolution: one prediction per input sample at 200 Hz, no post-hoc upsampling.
- ποΈ Aggressive multi-scale pooling: downsampling factors of 4, 8, 16, 32 keep the network shallow yet wide in receptive field.
- π Masked BCE loss: unscored regions (label
-1) are excluded from the objective. - π AUPRC-first evaluation: the primary metric for this heavily imbalanced task, scored with the official PhysioNet
score2018.py. - π§ͺ Signal-space augmentations: magnitude scaling, related-channel shuffling, and Gaussian channel injection, applied on-the-fly during training.
π The DeepSleep 2.0 architecture: a 1D U-Net with a five-level encoder/decoder and skip connections.
The network (architectures/architecture_v1.py) is a 1D adaptation of the classic 2D U-Net:
- Building block (
DoubleConv): twoConv1dlayers (kernel size 7, padding 3, no bias), each followed byBatchNorm1dandReLU. - Encoder: an input conv (13 β 15 channels) followed by four
Downblocks (MaxPool1dβDoubleConv) that progressively widen the representation (15 β 30 β 60 β 120 β 240) while pooling by 4, 8, 16, and 32. - Decoder: four symmetric
Upblocks that upsample (linear interpolation by default, or transposed convolution), concatenate the corresponding encoder skip connection, and apply aDoubleConv. - Output head (
OutConv): a 1Γ1Conv1dto a single channel; aSigmoidis applied only at scoring time (training uses raw logits with a numerically stable BCE-with-logits loss). - Initialization: Xavier-uniform on all convolutional weights with ReLU gain.
Compared to the original DeepSleep (depth 11, 480-channel bottleneck), DeepSleep 2.0 halves the depth and quarters the bottleneck width, trading a modest accuracy drop for a much lighter, faster model.
The model is trained and evaluated on the PhysioNet/CinC 2018 Challenge "You Snooze You Win" dataset: 994 annotated training recordings (plus 989 test recordings whose labels are not public, so they are not used here), each roughly 7 to 8 hours long, sampled at 200 Hz. Each recording provides 13 physiological channels:
| # | Channel | Modality |
|---|---|---|
| 0β5 | F3-M2, F4-M1, C3-M2, C4-M1, O1-M2, O2-M1 | EEG (electroencephalography) |
| 6 | E1-M2 | EOG (electrooculography) |
| 7 | Chin | EMG (chin) |
| 8β9 | ABD, Chest | Respiratory effort (abdomen, chest) |
| 10 | Airflow | Respiration |
| 11 | SaOβ | Oxygen saturation |
| 12 | ECG | Single-lead electrocardiogram |
Per-sample labels are 1 (arousal), 0 (non-arousal), or β1 (unscored, masked from the loss). Preprocessing (utils.py) zero-pads and centers every recording to 2Β²Β³ samples, optionally applies per-channel Z-score normalization, and caches the result as .h5py for fast reloading.
Left: the sparse, heterogeneous distribution of arousals across recordings. Right: arousal metrics vs. sleep duration.
Evaluated on a held-out test set of 249 recordings, using the official PhysioNet gross AUPRC (area under the precision-recall curve) and gross AUROC. For this highly imbalanced task, AUPRC is the headline metric.
| Model | Z-norm | Augmentations | Gross AUPRC | Gross AUROC | Test BCE loss |
|---|---|---|---|---|---|
model_0 |
β | MagScale | 0.3879 | 0.8789 | 0.1770 |
model_1 |
β | MagScale | 0.4437 | 0.8944 | 0.1666 |
model_2 β |
β | MagScale + RandShuffle | 0.4504 | 0.9012 | 0.1643 |
model_3 |
β | MagScale + RandShuffle + Gaussian | 0.4071 | 0.8951 | 0.1700 |
| DeepSleep (reference, ensemble) | n/a | n/a | 0.550 | 0.927 | n/a |
The best configuration (model_2) reaches 0.4504 AUPRC / 0.9012 AUROC, close to the far larger original DeepSleep ensemble, while remaining compact. Z-score normalization and related-channel shuffling both help; the novel Gaussian channel-injection augmentation did not improve over channel-shuffling alone.
Distributions of per-record AUPRC (left) and AUROC (right) across the 249 test recordings.
π Per-model AUPRC-vs-AUROC correlation (all four configs)
Subject-wise AUPRC vs. AUROC for model_0 to model_3 (top-left to bottom-right).
Four trained configurations ship under models/. Each folder contains the hyperparameters.txt config, per-epoch my_checkpoint_<n>.pth.tar checkpoints (the latest one also stores the full training/validation loss history), the records.csv train/validation/test split, and cached test_loss_<epoch> / test_score_<epoch> pickles for the best epoch.
| Config | Z-norm | Augmentations | Best epoch | AUPRC | AUROC |
|---|---|---|---|---|---|
model_0 |
β | MagScale | 20 | 0.3879 | 0.8789 |
model_1 |
β | MagScale | 12 | 0.4437 | 0.8944 |
model_2 β |
β | MagScale + RandShuffle | 21 | 0.4504 | 0.9012 |
model_3 |
β | MagScale + RandShuffle + Gaussian | 18 | 0.4071 | 0.8951 |
All configs share the same recipe: Adam (lr = 1e-4, weight decay = 1e-5), batch size 2, up to 50 epochs with early stopping (patience 7), seed 1, and mixed-precision training. The "best epoch" is the checkpoint with the lowest validation loss.
git clone https://github.com/rfonod/deepsleep2.git
cd deepsleep2
python -m venv .venv && source .venv/bin/activate # or use conda
pip install -r requirements.txtThe clone is about 0.9 GB because the per-epoch checkpoints of all four pretrained models are part of the repository. A CUDA-capable GPU is strongly recommended for training (inference also runs on CPU). Install a CUDA-enabled PyTorch build to use the GPU.
π°οΈ Reproduce the exact paper environment
The published results were produced with Python 3.8 and PyTorch 1.9. To recreate that environment with the exact pinned package versions:
pip install -r requirements-legacy.txtThe notebook is backward-compatible: an AMP compatibility shim automatically uses the modern torch.amp API on PyTorch β₯ 2.4 and falls back to torch.cuda.amp on older installs, so the same code runs on both stacks.
Everything runs through the deep_sleep2.ipynb notebook, executed top-to-bottom. Set the Main Switches in the first code cell:
MODEL_NAME = 'model_2' # which config under ./models to use: model_0 .. model_3
TRAIN_MODE = True # True = train; False = evaluate the existing checkpoints
LOAD_CHECKPOINT = False # training only: resume from the latest checkpointSet TRAIN_MODE = False and run all cells. The notebook loads the latest checkpoint of the selected model, uses its loss history to pick the epoch with the lowest validation loss, loads that checkpoint, and prints the test loss and gross AUROC / AUPRC. The shipped models have cached test scores, so this reproduces the results table above in seconds. If the cache is missing (or you delete it), the test set is scored from scratch, which requires the dataset.
- Download the PhysioNet
trainingfolder intodata/training(seedata/README.md). - Set
TRAIN_MODE = Trueand run all cells. The notebook will:- build
RECORDS.txtmanifests and preprocess/cache every recording to.h5py(once; later runs reuse the cache); - split the records 60% train / 15% validation / 25% test. If the model folder already holds a
records.csv, that split is reused, so retraining a shipped model uses exactly the paper's split; deleterecords.csvto draw a new one; - train with on-the-fly augmentations and early stopping, saving
my_checkpoint_<epoch>.pth.tarafter every epoch; - score the best (lowest validation loss) checkpoint on the test set with the official scorer and cache the result.
- build
Training from scratch overwrites the checkpoints in the model folder. To continue an interrupted run instead, set LOAD_CHECKPOINT = True. Without a CUDA GPU the notebook falls back to the CPU, which is fine for evaluation but impractically slow for training.
To try a new configuration, create models/<name>/hyperparameters.txt (copy an existing one) and set MODEL_NAME = '<name>'. The JSON keys are:
| Key | Meaning |
|---|---|
ARCHITECTURE_NAME |
module in architectures/ that defines DeepSleepNet (e.g. architecture_v1) |
CHANNELS |
strictly increasing list of channel indices to use (0β12, see the channel table above) |
Z_NORM |
per-channel Z-score normalization of each recording |
LINEAR |
decoder upsampling: linear interpolation (true) or transposed convolution (false) |
TRANSFORMS |
training augmentations, any of MagScale, MagScaleRandCh, RandShuffle, AddRandGaussian2All, InjectRandGaussian, TimeScale (see transforms.py) |
LEARNING_RATE, DECAY_RATE |
Adam learning rate and weight decay |
BATCH_SIZE, NUM_WORKERS, PIN_MEMORY |
DataLoader settings |
MAX_NUM_EPOCHS, STOP_STRIP |
epoch limit and early-stopping patience (in epochs) |
SEED, DEVICE |
random seed and device (cuda; falls back to cpu if no GPU is found) |
deepsleep2/
βββ deep_sleep2.ipynb # main notebook: preprocessing, training, evaluation
βββ architectures/
β βββ architecture_v1.py # DeepSleepNet, the 1D U-Net
βββ dataset.py # CustomDataset reading the cached records
βββ transforms.py # training augmentations (MagScale, RandShuffle, ...)
βββ losses.py # masked BCE / BCE-with-logits losses
βββ utils.py # PSG I/O, padding, Z-normalization, .h5py caching
βββ score2018.py # official PhysioNet 2018 AUPRC/AUROC scorer
βββ models/ # 4 pretrained configs + checkpoints + results
βββ data/ # dataset download scripts (data itself not shipped)
βββ assets/ # figures used in this README and the paper
βββ requirements.txt # modern dependencies (Python 3.8+, PyTorch 2+)
βββ requirements-legacy.txt # exact frozen paper environment (PyTorch 1.9)
If you use DeepSleep 2.0 in your research, please cite the paper:
@Article{Fon22a,
author = {Fonod, Robert},
title = {{DeepSleep 2.0: Automated Sleep Arousal Segmentation via Deep Learning}},
journal = {AI},
year = {2022},
volume = {3},
number = {1},
pages = {164-179},
doi = {10.3390/ai3010010},
publisher = {MDPI},
}Please also consider citing the original DeepSleep paper.
- The PhysioNet/CinC 2018 Challenge organizers for the You Snooze You Win dataset and the official
score2018.pyscoring script. - The authors of the original DeepSleep architecture, on which this compact model is based.
Contributions are welcome. Please open a GitHub Issue or submit a pull request.
This project is distributed under the MIT License. See the LICENSE file for details.










