Installation and data
Install the training code in an isolated Python environment, download the dataset and the pre-trained models, learn what every file and column contains, see how subjects are divided into training, validation and test sets, and check that everything works by running the pre-trained detector.
In this tutorial you will
- Create a virtual environment and install the
portiloop_softwarepackage in editable mode. - Download (or generate) the synthetic practice dataset and put it in the right folder.
- Understand what the synthetic data imitate (MODA consensus labels on MASS recordings), where the pre-trained model's data came from, and which real databases you can request.
- Read the dataset files: columns, 145 s segments, labels, subject lists.
- Understand the subject-wise train/validation/test split, and why splitting by samples would cheat.
- Run the offline inference notebook as a sanity check, and fix the most common errors.
Prerequisites
| What | Needed for | Notes |
|---|---|---|
Python 3 and pip | Everything | Use a Python version for which PyTorch publishes packages. The code examples on this page were tested with Python 3.14, PyTorch 2.9 and pandas 2.3 (CPU only). |
git | Getting the code | Or download the repository as a ZIP from GitHub. |
| Disk space | Dataset | dataset.zip is 185 MB and unzips to about 450 MB; keep about 1 GB free. |
| RAM | Training | The training code loads a whole dataset text file into memory, once for the training set and once for the validation set. We did not measure the peak; the example SLURM job in scripts.zip requests --mem=32000M. |
| NVIDIA GPU with CUDA | Training only | The training configuration uses 'device_train': 'cuda' and stops with CUDA unavailable without a GPU. Inference uses 'device_inference': 'cpu': a laptop is enough. |
| MATLAB with Simulink | Only to preprocess real recordings with the original MATLAB scripts (a Python alternative exists) | See Tutorials 03 and 09. |
Installing the code
- Open a terminal and check the tools. On Windows, use "Anaconda Prompt" or PowerShell.
Expected output (your versions will differ):python3 --version git --versionPython 3.11.9 git version 2.43.0 - Clone the repository and move into it. All later commands assume you are in this folder (the one containing
setup.py).
If you cloned it before, update it withgit clone https://github.com/Portiloop/portiloop-training.git cd portiloop-traininggit pull: recent fixes (saving the best model during training, theonnxdependency insetup.py, loading the pre-trained model for offline inference, compatibility with pandas 3) are needed by these tutorials. - Create and activate a virtual environment. Choose one of the two variants.
python3 -m venv .venv source .venv/bin/activate # Windows PowerShell: .venv\Scripts\Activate.ps1 python -m pip install --upgrade pipYour prompt now starts withconda create -n portiloop python=3.11 conda activate portiloop python -m pip install --upgrade pip(.venv)or(portiloop). Activate the environment again in every new terminal before working on the project. - (GPU machines only) install PyTorch with CUDA first. Open the selector at pytorch.org/get-started/locally, choose your OS, "Pip" and your CUDA version, and run the command it gives you. If you skip this step, the next step installs the default PyTorch build from PyPI, which is fine for inference on a CPU.
- Install the package in editable mode.
pip install -e .-e("editable") tells Python to use the files of your clone directly instead of copying them. This matters here: the code finds the dataset and saves trained models relative to its own location, so the package must live in your clone. The command installs the dependencies listed insetup.py:
In short:install_requires = [ 'numpy', 'pandas', 'scikit-learn', 'torch', 'wandb', 'pyedflib', 'scipy', 'matplotlib', 'requests', 'pyinstrument', 'onnx', # used to export the best model to ONNX during training ]numpy,pandas,scipy(arrays, tables, signal processing),torch(the neural network library),scikit-learn(only for the train/validation/test split),wandb(training dashboards, Tutorial 05),pyedflib(reading EDF files when rebuilding the dataset),matplotlib(plots),onnx(model export, Tutorial 10),requestsandpyinstrument(utilities). - Install Jupyter to run the notebooks (it is not in
setup.py):pip install notebook - Check the installation.
Expected output on a machine without GPU (on a GPU machine with a CUDA build of PyTorch, the last word ispython -c "import torch, portiloop_software; print('torch', torch.__version__, '| CUDA available:', torch.cuda.is_available())"True):
If you seetorch 2.9.1 | CUDA available: FalseModuleNotFoundError, the environment is not activated or step 5 failed; see Troubleshooting. - (Training only) Weights & Biases. The training script logs its curves to Weights & Biases (W&B). Three options: log in once with your own account (
wandb login); train without an account withWANDB_MODE=offline(the curves are saved locally in a./wandbfolder and can be uploaded later withwandb sync); or switch W&B off completely withWANDB_MODE=disabled(nothing is recorded). Details in Tutorial 05. Never paste an API key into code you share.
Getting the practice dataset and the pre-trained models
There are two equivalent ways to get the dataset. The archive was made with the generator (seed 2022, numpy 2.3 and scipy 1.16); generating it yourself with the same versions gives identical files (we checked the checksums). Other versions of numpy or scipy may give slightly different files, which does not matter for the tutorials, but then the numbers quoted in them will not match exactly.
| Archive | Size | Contains | Needed? |
|---|---|---|---|
dataset.zip | 185 MB | The synthetic practice dataset and an example signal | Yes, for training and for the notebooks (or generate it, option B) |
experiments.zip | 2.7 MB | 10 pre-trained checkpoints | No: identical copies are already in portiloop_software/experiments/ (we compared their checksums) |
scripts.zip | 1.9 KB | Example SLURM job scripts for computing clusters | Only if you train on a SLURM cluster (Tutorial 05) |
Option A: download dataset.zip
- Download
dataset.zipintoportiloop_software/.
On Windows PowerShell:cd portiloop_software curl -L -O https://github.com/Portiloop/portiloop-training/releases/download/synthetic-dataset-v1/dataset.zipInvoke-WebRequest -Uri <the URL above> -OutFile dataset.zip, or download it with your browser and move it there. - Unzip it in place. The archive contains a top-level
dataset/folder, so unzipping insideportiloop_software/puts the files exactly where the code looks for them.
On Windows:unzip -n dataset.zip # -n: never overwrite, keeps the repository's dataset/.gitignore rm dataset.zip # optional cd ..Expand-Archive dataset.zip -DestinationPath .
Option B: generate the dataset yourself
The archive is the output of synthetic_dataset_generator.py, which only needs numpy and scipy. Generating the files takes about two minutes and writes them directly into portiloop_software/dataset/:
python "portiloop_software/portiloop_python/Dataset generation/synthetic_dataset_generator.py"
Options: --p1 and --p2 set the number of younger and older subjects (default 20 and 14, at least 6 each), --long the number of subjects per group with 10 segments instead of 3 (default 2), --seed the random seed (default 2022: the same seed gives the same subjects), --out another folder. A larger dataset gives larger validation and test sets (more reliable scores) at the cost of longer training: --p1 100 --p2 80 approaches the size of the original files.
Check the result:
ls -l portiloop_software/dataset portiloop_software/experiments
You should now have this layout:
portiloop-training/
├── setup.py
├── notebooks/
│ ├── offline_inference.ipynb
│ ├── simulate_Portiloop_1_input_classification.ipynb
│ └── model_extraction.ipynb
└── portiloop_software/
├── dataset/
│ ├── dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt 150 MB
│ ├── dataset_classification_p1_big_250_matlab_standardized_envelope_pf.txt 85 MB
│ ├── dataset_classification_p2_big_250_matlab_standardized_envelope_pf.txt 64 MB
│ ├── dataset_regression_full_big_250_matlab_standardized_envelope_pf.txt 150 MB
│ ├── example_data_not_annotated.txt 1.0 MB
│ ├── subject_sequence_full_big.txt
│ ├── subject_sequence_p1_big.txt
│ ├── subject_sequence_p2_big.txt
│ └── synthetic_dataset_info.json (generator settings and per-subject parameters)
├── experiments/
│ ├── pareto_search_15_35_v4_0 (the model of the paper, used by default)
│ ├── pareto_search_15_35_v4_3, _7, _9, _11, _12, _14, _15, _16, _18
├── matlab/ (online filter model and preprocessing script)
└── portiloop_python/
├── ANN/ (network, training, inference, ONNX export)
├── Dataset generation/ (synthetic dataset generator; original MASS + MODA generators)
├── PMBO/ (hyperparameter search)
└── Utils/
portiloop_software/dataset/ is hard-coded in the training module: path_dataset = Path(__file__).absolute().parent.parent.parent / 'dataset'. The code reads the dataset files from there and also writes the checkpoints of the models you train there (Tutorial 05). The repository ignores the content of this folder in git (its .gitignore says "Ignore everything in this directory").
portiloop_software/experiments/ holds the pre-trained checkpoints (PyTorch files without extension, about 314 KB each). The notebooks load models from there.
Where the data come from
The synthetic practice dataset
The generator (portiloop_software/portiloop_python/Dataset generation/synthetic_dataset_generator.py) imitates the structure of the data the Portiloop was trained on, described in the next sections: 115 s blocks of N2 sleep scored by a group of experts, from a younger and an older group of adults. By default it creates 34 subjects (20 "phase 1", younger; 14 "phase 2", older), 3 blocks each except 2 subjects per group with 10 blocks: 130 segments, 4.2 hours of labelled signal. For each subject it draws a background EEG level and a typical spindle frequency, amplitude, duration and density, so that subjects differ from each other as real people do; older subjects have fewer, smaller and shorter spindles.
- Background: about 1/f noise (a sum of autoregressive processes), slow oscillations between 0.5 and 2 Hz, and K-complexes (about 1.5 per minute).
- Spindles: waxing and waning bursts between 10.5 and 16 Hz, 0.4 to 2.2 s long, with log-normally distributed amplitudes: most are clear, some are small enough to be missed.
- Distractors: alpha bursts (8 to 10.5 Hz), short muscle bursts, and 60 Hz line noise in some subjects (removed by the Portiloop notch filter).
- Labels: 4 to 8 simulated scorers per block mark each spindle with a probability and a confidence (1, 0.75 or 0.5) that grow with its amplitude, with onsets and offsets that vary between scorers; alpha bursts are occasionally marked with low confidence. As in MODA (below), the scores are averaged sample by sample (the regression labels) and thresholded at 0.2 for phase 1 and 0.35 for phase 2, adjacent events are merged and events shorter than 0.3 s or longer than 2.5 s are removed (the classification labels).
- Processing: the same chain as the original MATLAB script (below): Portiloop low-pass and notch filters, online standardization, sigma envelope and power ratio. Each segment is simulated with 30 s of extra signal before it so that the filters have settled.
About 6.1% of the labelled samples are spindles (8.5% in phase 1, 3.0% in phase 2); for comparison, the Portiloop paper reports that "only about 5% of the signal is labeled as sleep spindles" in MODA [3]. As a check that the synthetic spindles resemble real ones, we ran the pre-trained network (trained on real EEG) on all synthetic segments, sample by sample with a 0.5 threshold:
| Synthetic subjects | Precision | Recall | F1 |
|---|---|---|---|
| Phase 1 (younger) | 0.81 | 0.58 | 0.68 |
| Phase 2 (older) | 0.67 | 0.44 | 0.54 |
The network recognizes most labelled synthetic spindles without ever having seen synthetic data; it misses mostly the small ones, which the simulated scorers sometimes still marked. These scores are of the same order as those the paper reports on real test subjects (F1 0.64 for phase 1 and 0.55 for phase 2, mean over ten splits [3]; Tutorial 06), so the synthetic task is neither trivial nor impossible for this network. The two evaluations are not strictly comparable (different subjects, and the paper's numbers come from test sets only).
MASS: the recordings behind the pre-trained model
The Montreal Archive of Sleep Studies [1] is a database of laboratory polysomnography: "whole-night recordings from 200 participants [...] were pooled from eight different research protocols performed in three different hospital-based sleep laboratories. All recordings feature a sampling frequency of 256 Hz" [1]. Its first cohort is split into five subsets, SS1 to SS5. MASS file names follow this structure: 01-02-0017 is cohort 01, subset SS2, subject 0017, which you will see in the subject lists below.
MODA: the spindle labels behind the pre-trained model
The Massive Online Data Annotation project [2] crowd-sourced spindle annotations on part of MASS:
"180 subjects were sampled from the SS1-SS5 subsets. The dataset was split into “phase 1” and “phase 2”; 100 younger subjects (mean age of 24.1 years old) and 80 older subjects (mean age of 62.0 years old) respectively. “Blocks” of 115 s were randomly extracted from artifact free Stage N2 sleep. Three blocks (~6 mins) were extracted in 85 subjects in phase 1 and 65 subjects in phase 2; and 10 blocks (~20 mins) were extracted in the remaining 15 subjects of each phase."
Lacourse et al. (2020), Scientific Data, Methods [2]
Each scorer marked spindles on the C3 channel and rated their confidence; scores were averaged across scorers, sample by sample, and thresholded:
"each sample of the EEG time series had a score weighted by the confidence rate given by the scorer; 1 for high, 0.75 for medium, 0.5 for low confidence and 0 for no spindle at all. Then, sample by sample, the scores were averaged across scorers, and if they exceed the chosen Group Consensus Threshold (GCt) then these samples were identified to be part of the GC spindle dataset."
Lacourse et al. (2020), Scientific Data, Methods [2]
The thresholds of the expert "gold standard" are 0.2 for phase 1 and 0.35 for phase 2 [2], and "Too short (<0.3 s) adjacent (<0.1 s apart) spindles were merged, and spindle longer than 2.5 s or shorter than 0.3 s were filtered out of the GC" [2]. The Portiloop training code still contains these two thresholds: threshold_list = {'p1': 0.2, 'p2': 0.35, 'full': 0.2}.
How to obtain the original data
- MODA annotations are public. They are on the Open Science Framework (osf.io/8bma7, doi:10.17605/OSF.IO/8BMA7) and in the GitHub repository klacourse/MODA_GC (release 3.0 at the time of writing). That repository contains the files the Portiloop dataset generator reads:
input/6_segListSrcDataLoc_p1.txt,input/7_segListSrcDataLoc_p2.txt,input/8_MODA_primChan_180sjt.txtand oneoutput/exp/annotFiles/<subject>_MODA_GS.txtper subject (columnsstartSec,durationSec,eventName). - MASS recordings are available on request. As of November 2026, the MASS web page states that access to the biosignals "requires that the investigators submit a copy of their project (as approved by their local ethics board) and a proof of ethical approval", that requests are made by e-mail to the address given on that page, and that the data are then shared through the Borealis (Canadian Dataverse) repository; "PSG biosignals will never be available for direct download." The MODA README adds that the MODA subjects come from "the complete PSG MASS data V2.0 (SS1 to SS5)". Check the MASS page for the current procedure before you apply.
portiloop_software/experiments/ were trained by the Portiloop authors on MASS recordings with MODA labels (the paper states that "Ethical approval for use of the dataset was obtained from the database’s scientific committee and Concordia University’s Research Ethics Unit" [3]). The MASS-derived training files are not distributed with these tutorials. If you use the pre-trained models, cite the Portiloop paper [3], MASS [1] and MODA [2].Real EEG databases you can use
To train a detector for real EEG you need recordings with spindle annotations, ideally on a central channel (C3, C4 or Cz). Few public databases have them. The list below was checked on the official pages in November 2026; licences and procedures change, so read the current terms before you download, and ask your ethics board whether your use needs approval.
| Database | Access | Central EEG | Spindle labels |
|---|---|---|---|
| MASS + MODA (the data of the pre-trained model) MASS; MODA on OSF and GitHub | MASS: on request with your approved project and proof of ethics approval, then a licence. MODA annotations: open ("not subject to licencing requirements") | C3, 256 Hz | Yes: group consensus of experts on 180 subjects (5,342 gold-standard spindles) |
| MASS SS2 annotations doi:10.5683/SP3/Y889CS | Annotations open on Borealis; signals as MASS above | 19 EEG electrodes, 256 Hz | Yes: "Expert 1 scored the sleep spindles and k-complexes for all the subjects. Expert 2 scored the sleep spindle for 15 out of 19 subjects." |
| DREAMS Sleep Spindles doi:10.5281/zenodo.2650142 | Open download; CC BY-NC-ND 3.0 (no commercial use, do not share modified copies) | C3-A1 or Cz-A1; 50, 100 or 200 Hz depending on the excerpt | Yes: "8 excerpts of 30 minutes [...] annotated independently by two experts"; the second expert scored only 6 excerpts |
| Nap EEG (Mei et al.) osf.io/chav7 | Open (OSF) | 64 channels including C3 and C4, 1 kHz | Yes, one rater: "A single rater (KTN) manually annotated sleep stages and spindles" (2,528 spindles, daytime naps) |
| HMC sleep staging (PhysioNet) doi:10.13026/t79q-fr32 | Open; CC BY 4.0 | C3/M2 and C4/M1, 256 Hz | No: sleep stages only |
| Dreem Open Datasets DOD-H and DOD-O doi:10.5281/zenodo.15900394 | Open download; MIT licence | C3/M2, 250 Hz (the Portiloop rate) | No: sleep stages by 5 scorers |
| NSRR cohorts (SHHS, MrOS, ...) sleepdata.org | Online request and Data Access and Use Agreement | SHHS: C3-A2 and C4-A1 at 125 Hz; MrOS: C3, C4 at 256 Hz | No spindle events; SHHS provides automated spindle summary variables |
Databases with sleep stages only are still useful: you can run the pre-trained detector on their N2 sleep (Tutorial 09), check its output against your own visual scoring of a subset, or annotate spindles yourself. Note that a PhysioNet search for "spindle" returned no open-access database with spindle annotations, and that Sleep-EDF has no central channel (only Fpz-Cz and Pz-Oz). Whatever the source, resample to 250 Hz and apply the Portiloop preprocessing (Tutorial 03), then write the four-column files described below, one 145 s segment per labelled block. Cite the database as its maintainers request.
How the original files were built
This is the recipe to follow if you convert a real database to the Portiloop format. The folder portiloop_software/portiloop_python/Dataset generation/ builds the files from MASS EDF files and MODA annotations, followed by MATLAB/Simulink scripts (portiloop_software/matlab/old_matlab/my_full_dataset_generation.m). In order, the code:
- reads channel C3 of each EDF file (256 Hz), re-referenced to A2 when MODA's channel list says
C3-A2; - cuts every MODA 115 s block with 15 s of extra signal before and 15 s after, and builds a label vector at 250 Hz: −1 before, −2 after, 0 or 1 inside;
- (MATLAB) resamples to 250 Hz, runs the signal through the Simulink model of the Portiloop filters (
filter_lp.slx), standardizes it online, computes an envelope and a power ratio, and writes the four columns.
fe = 256
new_fe = 250
signal_list = []
pre_sequence_length_s = 15
...
spindle_seq_list[i][index] = np.zeros((lenSignal,), dtype=float)
spindle_seq_list[i][index][:pre_sequence_length] = -1
spindle_seq_list[i][index][-post_sequence_length:] = -2
datasetupdate = single([lp_standard, envelope_homemade_simulink, r, spindle_250]);
writematrix(datasetupdate, path+"dataset_classification_"+phase + "_"+size_data+"_250_matlab_standardized_envelope_pf.txt");
Not every MODA subject made it into the original files: their subject lists contained 162 subjects (98 from phase 1 with 398 blocks, 64 from phase 2 with 297 blocks), against 180 subjects (404 and 345 blocks) in MODA. We do not know why the other subjects are missing; the generator skips EDF files that raise an error when read ("File ... ignored because of corruption"), which is one possibility. Preprocessing real recordings, with MATLAB or with a Python equivalent, is covered in Tutorials 03 and 09. The synthetic generator follows the same steps, so its source code is also a compact Python reference for the whole chain.
File formats
The dataset files
The four dataset_*_big_250_matlab_standardized_envelope_pf.txt files share one format: plain text, comma separated, no header, one row per sample at 250 Hz, four columns. The first rows of the classification file read:
0.3315376,1.051416,0.9155247,-1
0.1576234,1.046089,0.9770969,-1
0.0871462,1.038516,1.036036,-1
| Column | Content | Used by the published model? |
|---|---|---|
| 0 | EEG after the Portiloop online filtering (21-tap low-pass FIR, 60 Hz notch) and online standardization; dimensionless (roughly in standard deviations) | Yes: the only input |
| 1 | Sigma envelope: band-pass FIR, standardization, squaring and exponential smoothing | No (only when envelope_input is True) |
| 2 | Power ratio: mean FFT amplitude between 9 and 16 Hz divided by the mean between 2 and 8 Hz, over the last 125 samples (0.5 s), from compute_ratio.m (0 for the first 124 rows of the original files; the synthetic files have no zeros, thanks to the extra signal before each segment) | No (only when power_features_input is True) |
| 3 | Label. −1: 15 s lead-in; −2: 15 s tail; inside the 115 s block, 0 or 1 (no spindle / spindle) in the classification files, or a score between 0 and 1 in the regression file | Yes: the target |
Each file is a concatenation of 145 s segments (36,250 rows): 15 s lead-in, the 115 s labelled block (a MODA block in the original files), 15 s tail. Segments follow the order of the subject list (next section). The training code relies on this layout when it cuts the file:
self.data = pd.read_csv(self.path_file, header=None).to_numpy()
assert list_subject is not None
used_sequence = np.hstack([range(int(s[1]), int(s[2])) for s in list_subject])
split_data = np.array(np.split(self.data, int(len(self.data) / (len_segment + 30 * fe)))) # 115+30 = nb seconds per sequence in the dataset
split_data = split_data[used_sequence]
...
# list of indices that can be sampled:
self.indices = [idx for idx in range(len(self.data[0]) - self.window_size) # all possible idxs in the dataset
if not (self.data[3][idx + self.window_size - 1] < 0 # that are not ending in an unlabeled zone
or idx < self.past_signal_len)] # and far enough from the beginning to build a sequence up to here
Here len_segment is LEN_SEGMENT * fe = 115 × 250 samples, so each piece is (115 + 30) × 250 = 36,250 rows. A training example is a window whose last sample is labelled 0 or 1; windows ending in the lead-in or the tail are never used as targets. The lead-in still matters: the network looks back 8.5 s, and for the first labelled samples of a block that history lies in the lead-in.
What you will find in the synthetic files (we checked the first two segments of the classification and regression files):
- Rows 0 to 3,749 of each segment are labelled −1 and rows 32,500 to 36,249 are labelled −2, exactly 15 s each.
- In the classification file, labels inside the block are 0 or 1; in these two blocks 4.4% of the labelled samples are spindles (the first subject of the full list belongs to phase 2, which has fewer spindles; over all subjects the figure is 6.1%).
- Columns 0 to 2 are identical in the classification and regression files; only the labels differ.
- In the regression file, labels vary in steps of 0.05, like MODA's averaged scores. No sample with a score of 0.2 or less is labelled 1 in the classification file, but 609 samples with a score above 0.2 are labelled 0: those belong to the phase 2 subject (threshold 0.35) or to events removed by the duration rule. The original files showed the same pattern.
example_data_not_annotated.txtis a single column of 100,000 values (400 s at 250 Hz) of already preprocessed EEG from an extra synthetic subject that is in none of the dataset files, with a clear spindle at 117.6 s.
Explore a segment (interactive)
dataset_classification_full_big_...txt: all 34 subjects (130 segments), 0/1 labels. Used by--phase full, the default.dataset_classification_p1_big_...txtand..._p2_big_...txt: the younger (20 subjects, 74 segments) and older (14 subjects, 56 segments) subjects only. Used by--phase p1and--phase p2.dataset_regression_full_big_...txt: all subjects, graded labels. Used with--regression.example_data_not_annotated.txt: one column of preprocessed EEG, the template for running the detector on your own data (Tutorial 09).
The subject lists
Each subject_sequence_*_big.txt file maps subjects to segments of the matching dataset file. Columns are separated by spaces: subject ID, index of the first segment, index of the end segment (excluded, Python style).
syn-p2-001 0 3
syn-p1-005 3 6
syn-p2-013 6 9
syn-p2-012 9 12
syn-p1-002 12 15
So subject syn-p2-001 (a phase 2 subject) owns segments 0, 1 and 2, that is rows 0 to 108,749 of the full dataset file. In the full list, 30 subjects have 3 segments and 4 have 10, as in MODA where most subjects contributed 3 blocks and some 10. Segment indices are relative to each file: in subject_sequence_p1_big.txt, syn-p1-005 owns segments 0 to 2 of the p1 file. The synthetic IDs read syn-<phase>-<number>; the original files used MASS IDs such as 01-02-0017 (cohort 01, subset SS2, subject 0017).
How subjects are split into training, validation and test sets
A detector must be evaluated on people it has never seen. The code therefore splits subjects, not samples. Here is the function that does it:
all_subject = pd.read_csv(Path(path_dataset) / subject_list, header=None, sep=r"\s+").to_numpy()
test_subject = None
if PHASE == 'full':
p1_subject = pd.read_csv(Path(path_dataset) / subject_list_p1, header=None, sep=r"\s+").to_numpy()
p2_subject = pd.read_csv(Path(path_dataset) / subject_list_p2, header=None, sep=r"\s+").to_numpy()
train_subject_p1, validation_subject_p1 = train_test_split(p1_subject, train_size=0.8, random_state=split_i)
if TEST_SET:
test_subject_p1, validation_subject_p1 = train_test_split(validation_subject_p1, train_size=0.5, random_state=split_i)
train_subject_p2, validation_subject_p2 = train_test_split(p2_subject, train_size=0.8, random_state=split_i)
if TEST_SET:
test_subject_p2, validation_subject_p2 = train_test_split(validation_subject_p2, train_size=0.5, random_state=split_i)
train_subject = np.array([s for s in all_subject if s[0] in train_subject_p1[:, 0] or s[0] in train_subject_p2[:, 0]]).squeeze()
...
else:
train_subject, validation_subject = train_test_split(all_subject, train_size=0.8, random_state=split_i)
if TEST_SET:
test_subject, validation_subject = train_test_split(validation_subject, train_size=0.5, random_state=split_i)
Step by step, for the default --phase full:
- The phase 1 (younger) and phase 2 (older) subject lists are split separately, so that both age groups are represented in every set (the statistical term is a split stratified by phase).
- For each phase, scikit-learn's
train_test_splitshuffles the subjects and keeps 80% for training (rounded down: 16 of 20, 11 of 14 with the default synthetic dataset; 78 of 98 and 51 of 64 with the original files). - If a test set is requested (the default,
--test_set), the remaining 20% is halved: the first half becomes the test set, the second half the validation set (2 and 2 in phase 1; 1 and 2 in phase 2, as the odd subject goes to validation). With--no_test_set, all of it is used for validation. - The phase lists are then mapped back to rows of
subject_sequence_full_big.txt, whose segment indices point into the full dataset file. - The shuffle is seeded with
random_state=split_i: the same split index always gives the same split. From the command line,--experiment_indexselects it: even indices use split 0, odd indices use split 2 (possible_split = [0, 2]).
For split 0 this gives 27 training, 4 validation and 3 test subjects (109, 12 and 9 segments); with the original files it gave 129, 17 and 16 subjects. Such small validation and test sets give noisy scores: generate a larger dataset (option B) when you want to compare models seriously. The paper describes the same proportions: "we choose to use only 10% of subjects as our validation set (for model selection), and another 10% of subjects as our test set (for final model evaluation)" [3]. With --phase p1 or --phase p2, only that phase's list is split.
Subject-wise split, and what a sample-wise split would do (interactive)
Why is a sample-wise split wrong? Two reasons. First, the network's input for one labelled sample is 8.45 s of signal ((50 − 1) × 42 + 54 = 2,112 samples); with samples assigned at random, every test input overlaps signal the network was trained on. Second, spindles are a personal signature: "These characteristics are predominately trait-like, and remain remarkably stable night after night within an individual, but vary between individuals" [2]. A network evaluated on new samples of known subjects can recognize the subjects' spindles rather than spindles in general, and its score says little about the next participant you record.
A first sanity check: offline inference on the example signal
The notebook notebooks/offline_inference.ipynb runs the pre-trained network on example_data_not_annotated.txt and plots its output. It needs the dataset (for the example file) but no GPU.
- Start Jupyter from the repository root, with the environment activated:
A browser tab opens with the notebook.jupyter notebook notebooks/offline_inference.ipynb - Run the cells one by one (Shift+Enter). The configuration cell calls
get_final_model_config_dict(), whose model name'sanity_check_final_model_0'is resolved automatically to the distributed checkpointportiloop_software/experiments/pareto_search_15_35_v4_0. - Check the loading cell. The cell
print(f"The data has been loaded as a torch Tensor of {len(data)} data points:\n{data}")prints:The data has been loaded as a torch Tensor of 100000 data points: tensor([-0.5693, -0.8419, -1.0572, ..., 1.3280, 0.7578, 0.1721]) - Run the inference cell (
run_offline_unlabelled(...)). It processes every sample: in our test it took 8 s on the CPU of the computer used to write this page (expect longer on a slower machine) and returned 99,918 outputs, one per input window, for windows ending at sample indices 54 to 99,971 (true_idxis the last sample of each window). Warnings aboutpin_memory(no GPU) and about copying a tensor withtorch.tensor()are harmless. - Look at the plot. The last cell plots 10 s (from 115 s to 125 s) of the signal (blue) and of the network output (orange). The output is drawn shifted down by 5 so that both fit on one plot: its scale is the right-hand axis (0 to 1), and the dotted grey line is the 0.5 threshold. You should see a large spindle from 117.6 s to about 119.2 s (placed there by the generator): the orange curve crosses the threshold about 0.3 s after its onset (the network needs a few cycles to recognize it) and stays close to 1 until about 119 s. A second, smaller spindle near 124 s also crosses the threshold; elsewhere the output stays near 0, with a few small bumps. Over the whole 400 s, about 5% of the outputs outside 115 to 125 s exceed 0.5, because the example signal contains other spindles.
If you only want to check that the pre-trained network loads (without the dataset), this short script uses get_trained_model(), which has the fallback:
from pathlib import Path
import portiloop_software
from portiloop_software import get_final_model_config_dict, get_trained_model
path_experiments = Path(portiloop_software.__file__).parent / "experiments"
config = get_final_model_config_dict()
net = get_trained_model(config, path_experiments)
print(sum(p.numel() for p in net.parameters()), "trainable parameters")
Expected output: 25679 trainable parameters.
Troubleshooting
ModuleNotFoundError: No module named 'portiloop_software' (or 'torch')
The environment is not activated in this terminal or Jupyter kernel, or pip install -e . was not run from the folder containing setup.py. Activate the environment, run pip install -e . again, and in Jupyter choose the kernel of that environment. Check which Python you are using with python -c "import sys; print(sys.executable)": the path should be inside .venv or your conda environment.
pip cannot install torch or pyedflib
For PyTorch, use the exact command from the PyTorch selector before pip install -e .; very new Python versions sometimes have no PyTorch package yet, in which case create the environment with an older Python (for example with conda, python=3.11). If pip tries to compile pyedflib and fails, you are probably also on a Python version without a ready-made package for it; the same remedy applies. pyedflib is only used to rebuild the dataset from EDF files.
AssertionError: CUDA unavailable
You started training on a machine without an NVIDIA GPU, or PyTorch was installed without CUDA support. Check with python -c "import torch; print(torch.cuda.is_available())". On a GPU machine, reinstall PyTorch with the selector command for your CUDA version. Inference does not need CUDA.
FileNotFoundError: ... portiloop_software/dataset/subject_sequence_full_big.txt
The dataset is not where the code looks. Common causes: the archive was unzipped one level too deep (portiloop_software/dataset/dataset/...) or at the repository root (portiloop-training/dataset/); or the package was installed without -e, so path_dataset points inside the environment's site-packages. Print the folder the code uses:
python -c "import portiloop_software, pathlib; print(pathlib.Path(portiloop_software.__file__).parent / 'dataset')"
FileNotFoundError: ... experiments/sanity_check_final_model_0
Your copy of the code predates the fix that maps this name to the distributed checkpoint: run git pull. Alternatively, name the checkpoint explicitly after creating the configuration: config_dict['experiment_name'] = 'pareto_search_15_35_v4_0'. If the error persists, check that portiloop_software/experiments/pareto_search_15_35_v4_0 exists.
TypeError: ... unexpected keyword argument 'delim_whitespace'
You have pandas 3 or newer, which "Removed the deprecated delim_whitespace keyword in read_csv()" (pandas 3.0.0 release notes), with a copy of the code older than the fix (the code now uses sep=r"\s+"). Run git pull, or install pip install "pandas<3".
ValueError: array split does not result in an equal division
Raised by np.split in SignalDataset when the number of rows of the dataset file is not a multiple of 36,250. The file is truncated (interrupted download, unzip or generation, full disk) or was not written in segments of 145 s. Compare its size with the listing above and download or generate the dataset again.
AssertionError: Dataset smaller than window size. / Segment smaller than window size.
These checks fire when the signal handed to the network is shorter than one input window (54 samples, 0.216 s). Dataset smaller than window size. comes from SignalDataset (training files): in practice it means that the subject list selected (almost) no data, for example a subject list edited by hand or not matching the dataset file. Segment smaller than window size. comes from UnlabelledSignalDatasetSingleSegment (your own data in run_offline_unlabelled): check that your file was read as one long column and not, for example, as one row.
IndexError: index ... is out of bounds
A subject list refers to segments that do not exist in the dataset file: typically a subject_sequence_p1_big.txt used with the full dataset file, or the other way around, after renaming files. Keep the original names; the code chooses matching pairs from --phase.
Killed, MemoryError, or the computer freezes when training starts
The training code loads the full text file with pandas, once for training and once for validation. The default synthetic file (150 MB) fits in a few GB of RAM; the original files were 825 MB, and the example SLURM job requested 32,000 MB. If you generated a large synthetic dataset, use a machine with more RAM, close other programs, or start with --phase p2, whose file is the smallest.
W&B asks for an API key, or training stops at wandb.init
Run wandb login once, or train without an account: WANDB_MODE=offline keeps the curves locally in ./wandb (upload them later with wandb sync), WANDB_MODE=disabled records nothing (for example WANDB_MODE=offline python portiloop_software/portiloop_python/ANN/portiloop_detector_training.py ...). If offline mode fails with an older copy of the code, run git pull. See Tutorial 05.
Warnings you can ignore
UserWarning: 'pin_memory' argument is set as true but no accelerator is found(CPU-only machine).UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.detach().clone()(offline inference).
Exercises
How much labelled EEG is there?
Using only subject_sequence_full_big.txt and pandas, compute the number of subjects, the number of segments, the number of hours of labelled (115 s) EEG, and the number of rows the full dataset file should have.
Answer
from pathlib import Path
import pandas as pd
import portiloop_software
path_dataset = Path(portiloop_software.__file__).parent / "dataset"
subjects = pd.read_csv(path_dataset / "subject_sequence_full_big.txt", header=None, sep=r"\s+",
names=["subject", "first_segment", "end_segment"])
subjects["n_segments"] = subjects["end_segment"] - subjects["first_segment"]
print(len(subjects), "subjects,", subjects["n_segments"].sum(), "segments")
print(subjects["n_segments"].value_counts())
print("labelled hours:", round(subjects["n_segments"].sum() * 115 / 3600, 1))
print("rows expected in the file:", subjects["n_segments"].sum() * 36250)
34 subjects, 130 segments
n_segments
3 30
10 4
Name: count, dtype: int64
labelled hours: 4.2
rows expected in the file: 4712500
Note sep=r"\s+", the pandas 3 compatible spelling of delim_whitespace=True. For comparison, the original MASS-derived files had 162 subjects, 695 segments and 22.2 labelled hours, close to the paper's "∼24 h of annotated data" [3].
Same number of subjects, different amounts of data
In the split widget, compare split 0 and split 6. Both have 27 / 4 / 3 subjects. Do the validation sets contain the same amount of EEG? Why not, and why could this matter when you compare models trained on different splits?
Answer
No: split 0 has 12 validation segments, split 6 has 26 (the test sets happen to have 9 each). Subjects contribute 3 or 10 segments, so the amount of data per set depends on how many 10-segment subjects land in it. Validation scores computed on different splits therefore rest on different amounts of data and different people, which is why the paper repeats training over several splits and reports the mean and standard deviation of the test score [3].
Is the 15 s lead-in long enough?
For the published model, the network's input for one labelled sample spans (seq_len − 1) × seq_stride + window_size samples, with seq_len = 50, seq_stride = int(0.17 × 250) = 42 and window_size = 54. Is a 15 s lead-in long enough so that, for the first labelled sample of a block, this input lies entirely within the same block's 145 s segment?
Answer
49 × 42 + 54 = 2,112 samples = 8.45 s, shorter than the 15 s (3,750 samples) lead-in. In SignalDataset.__getitem__ the input is self.full_signal[idx - (self.past_signal_len - self.idx_stride):idx + self.window_size] cut into 50 windows, so for the first labelled row of a block (row 3,750 of the segment) the oldest sample used is row 3,750 − 2,112 + 1 = 1,639 of the same segment, inside its lead-in. A model looking further back than 15 s would start mixing signal from the previous block, recorded at another time of the night.
References
- O'Reilly C, Gosselin N, Carrier J, Nielsen T (2014). Montreal Archive of Sleep Studies: an open-access resource for instrument benchmarking and exploratory research. Journal of Sleep Research 23(6): 628 to 635. doi:10.1111/jsr.12169. Access procedure: ceams-carsm.ca/en/mass.
- Lacourse K, Yetton B, Mednick S, Warby SC (2020). Massive online data annotation, crowdsourcing to generate high quality sleep spindle annotations from EEG data. Scientific Data 7: 190. doi:10.1038/s41597-020-0533-4. Data: osf.io/8bma7; code and annotation files: github.com/klacourse/MODA_GC.
- Valenchon N, Bouteiller Y, Jourde HR, L'Heureux X, Sobral M, Coffey EBJ, Beltrame G (2022). The Portiloop: a deep learning-based open science tool for closed-loop brain stimulation. PLOS ONE 17(8): e0270696. doi:10.1371/journal.pone.0270696
- pandas development team (2026). What's new in 3.0.0. pandas.pydata.org/docs/whatsnew/v3.0.0.html