Tutorial 02 · Getting started

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.

Time
45 minutes (plus download time)
Level
Beginner
You need
A terminal, Python 3, git, about 1 GB of free disk
Runs in browser
The widgets yes; the installation runs on your computer

In this tutorial you will

  • Create a virtual environment and install the portiloop_software package 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

WhatNeeded forNotes
Python 3 and pipEverythingUse 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).
gitGetting the codeOr download the repository as a ZIP from GitHub.
Disk spaceDatasetdataset.zip is 185 MB and unzips to about 450 MB; keep about 1 GB free.
RAMTrainingThe 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 CUDATraining onlyThe 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 SimulinkOnly to preprocess real recordings with the original MATLAB scripts (a Python alternative exists)See Tutorials 03 and 09.
For neuroscientists: why a virtual environment?A virtual environment is a private copy of Python with its own set of installed packages, stored in one folder. It is the software equivalent of a dedicated, labelled reagent shelf for one protocol: installing PyTorch or an old pandas for this project will not break the toolboxes you use for other analyses, and deleting the folder removes everything.

Installing the code

  1. Open a terminal and check the tools. On Windows, use "Anaconda Prompt" or PowerShell.
    python3 --version
    git --version
    Expected output (your versions will differ):
    Python 3.11.9
    git version 2.43.0
  2. Clone the repository and move into it. All later commands assume you are in this folder (the one containing setup.py).
    git clone https://github.com/Portiloop/portiloop-training.git
    cd portiloop-training
    If you cloned it before, update it with git pull: recent fixes (saving the best model during training, the onnx dependency in setup.py, loading the pre-trained model for offline inference, compatibility with pandas 3) are needed by these tutorials.
  3. 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 pip
    Your prompt now starts with (.venv) or (portiloop). Activate the environment again in every new terminal before working on the project.
  4. (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.
  5. 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 in setup.py:
    install_requires = [
        'numpy',
        'pandas',
        'scikit-learn',
        'torch',
        'wandb',
        'pyedflib',
        'scipy',
        'matplotlib',
        'requests',
        'pyinstrument',
        'onnx',  # used to export the best model to ONNX during training
    ]
    In short: 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), requests and pyinstrument (utilities).
  6. Install Jupyter to run the notebooks (it is not in setup.py):
    pip install notebook
  7. Check the installation.
    python -c "import torch, portiloop_software; print('torch', torch.__version__, '| CUDA available:', torch.cuda.is_available())"
    Expected output on a machine without GPU (on a GPU machine with a CUDA build of PyTorch, the last word is True):
    torch 2.9.1 | CUDA available: False
    If you see ModuleNotFoundError, the environment is not activated or step 5 failed; see Troubleshooting.
  8. (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 with WANDB_MODE=offline (the curves are saved locally in a ./wandb folder and can be uploaded later with wandb sync); or switch W&B off completely with WANDB_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

The practice dataset is syntheticThe dataset used in these tutorials is synthetic EEG, generated by a script of this repository; it was not recorded from any person. It has exactly the format of the files the Portiloop authors trained on, so every command, notebook and tutorial works with it, and its spindles look like spindles to the pre-trained network (see below). A network trained on it, however, learns synthetic spindles: it is not a detector for real EEG. To train a real detector, request one of the annotated databases listed below and convert it to the same format (Tutorials 03 and 09).

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.

ArchiveSizeContainsNeeded?
dataset.zip185 MBThe synthetic practice dataset and an example signalYes, for training and for the notebooks (or generate it, option B)
experiments.zip2.7 MB10 pre-trained checkpointsNo: identical copies are already in portiloop_software/experiments/ (we compared their checksums)
scripts.zip1.9 KBExample SLURM job scripts for computing clustersOnly if you train on a SLURM cluster (Tutorial 05)

Option A: download dataset.zip

  1. Download dataset.zip into portiloop_software/.
    cd portiloop_software
    curl -L -O https://github.com/Portiloop/portiloop-training/releases/download/synthetic-dataset-v1/dataset.zip
    On Windows PowerShell: Invoke-WebRequest -Uri <the URL above> -OutFile dataset.zip, or download it with your browser and move it there.
  2. Unzip it in place. The archive contains a top-level dataset/ folder, so unzipping inside portiloop_software/ puts the files exactly where the code looks for them.
    unzip -n dataset.zip     # -n: never overwrite, keeps the repository's dataset/.gitignore
    rm dataset.zip           # optional
    cd ..
    On Windows: 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/
On the hard drive

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.

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 subjectsPrecisionRecallF1
Phase 1 (younger)0.810.580.68
Phase 2 (older)0.670.440.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).

What the synthetic data do not containNo sleep stages other than N2, no arousals, movement or electrode artifacts, no eye movements or ECG contamination, no differences between amplifiers and montages, and no real inter-individual variability beyond a few parameters. Results obtained on them (F1 scores, best hyperparameters, training curves) teach you how the pipeline behaves; they say nothing about performance on real EEG. Every number you report in a paper must come from real data.

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

The pre-trained modelsThe checkpoints in 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.

DatabaseAccessCentral EEGSpindle 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 HzYes: 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 above19 EEG electrodes, 256 HzYes: "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 excerptYes: "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 kHzYes, 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.0C3/M2 and C4/M1, 256 HzNo: sleep stages only
Dreem Open Datasets DOD-H and DOD-O
doi:10.5281/zenodo.15900394
Open download; MIT licenceC3/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 AgreementSHHS: C3-A2 and C4-A1 at 125 Hz; MrOS: C3, C4 at 256 HzNo 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:

  1. reads channel C3 of each EDF file (256 Hz), re-referenced to A2 when MODA's channel list says C3-A2;
  2. 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;
  3. (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
ColumnContentUsed by the published model?
0EEG 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
1Sigma envelope: band-pass FIR, standardization, squaring and exponential smoothingNo (only when envelope_input is True)
2Power 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)
3Label. −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 fileYes: 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.

For neuroscientists: why a 15 s lead-in?The online standardization of the Portiloop is a running estimate of the mean and variance, like a slowly adapting baseline; the variance estimate has a memory of about 1/0.001 = 1,000 samples (4 s). The network itself integrates 8.5 s of past signal. Because consecutive blocks come from different moments of the night, the 15 s of EEG before each block let the filters, the baseline and the network's history "settle" on the right signal before the first labelled sample. A device switched on at the start of a block would behave worse during its first seconds, as the warm-up option of the widget in Tutorial 01 shows.

What you will find in the synthetic files (we checked the first two segments of the classification and regression files):

Explore a segment (interactive)

Dataset file explorer

A replica of one 145 s segment, computed in your browser the way the dataset files are built (Portiloop filters and standardization for column 0, an envelope for column 1, the power ratio for column 2), with spindles at the positions labelled in the first segment of the synthetic dataset file. What to try: click a column header to plot it and read what it means; move the row slider or use the jump buttons to visit the lead-in, a spindle and the tail, and check whether that row can be a training target.

Time in segment
…
Zone
…
Can be a training target?
…
Synthetic EEG; column 1 uses the 21-tap band-pass in matlab/old_matlab/coef1216.coe as a stand-in (we did not check that it is the filter inside envelope_extractor_simulink.slx). Row numbers start at 0, as in Python.
On the hard drive
  • dataset_classification_full_big_...txt: all 34 subjects (130 segments), 0/1 labels. Used by --phase full, the default.
  • dataset_classification_p1_big_...txt and ..._p2_big_...txt: the younger (20 subjects, 74 segments) and older (14 subjects, 56 segments) subjects only. Used by --phase p1 and --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).
From the segment counts, the full classification file should contain 130 × 36,250 = 4,712,500 rows; a file of another length is truncated (see Troubleshooting).

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:

  1. 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).
  2. For each phase, scikit-learn's train_test_split shuffles 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).
  3. 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.
  4. The phase lists are then mapped back to rows of subject_sequence_full_big.txt, whose segment indices point into the full dataset file.
  5. The shuffle is seeded with random_state=split_i: the same split index always gives the same split. From the command line, --experiment_index selects 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.

For neuroscientists: training, validation, testThe training set is what the network learns from. The validation set is used during training to decide when to stop and which version of the model to keep (like a pilot sample used to tune a protocol). The test set is touched once, at the end, to report performance (like the confirmatory sample of a pre-registered study). Reusing test subjects to make decisions inflates the reported performance.

Subject-wise split, and what a sample-wise split would do (interactive)

Who goes where?

The 34 subjects of the synthetic subject_sequence_full_big.txt, each drawn as a block whose width is proportional to its number of segments (3 or 10). Colors show the set of each subject for the selected split. What to try: (1) move the split index and watch subjects change sets while the proportions stay the same; (2) untick "test set" (--no_test_set); (3) tick "split samples instead of subjects" and click a subject to see why that would leak information.

trainingvalidationtest
Phase 1 (younger subjects)
Phase 2 (older subjects)
One subject, 20 s of its first segment
Selected subject
…
Test windows whose 8.45 s input contains training samples
…
Split computed offline with scikit-learn's train_test_split, exactly as in generate_dataloader, on the default synthetic subject lists (seed 2022).

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.

  1. Start Jupyter from the repository root, with the environment activated:
    jupyter notebook notebooks/offline_inference.ipynb
    A browser tab opens with the notebook.
  2. 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 checkpoint portiloop_software/experiments/pareto_search_15_35_v4_0.
  3. 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])
  4. 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_idx is the last sample of each window). Warnings about pin_memory (no GPU) and about copying a tensor with torch.tensor() are harmless.
  5. 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

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

  1. 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.
  2. 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.
  3. 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
  4. pandas development team (2026). What's new in 3.0.0. pandas.pydata.org/docs/whatsnew/v3.0.0.html