⌚ Sleep Stage Classification Wearable Algorithm
An algorithm for classifying sleep stages using data from an accelerometer and pulse sensor worn on the body.
Raw Signal Acquisition — Accelerometer, PPG, and Skin Temperature
Every wearable sleep tracker starts from the same raw material: a handful of peripheral physiological signals measured at the wrist or finger, far from the brain activity that clinical sleep staging actually depends on. The entire algorithmic challenge is to infer central nervous system sleep state from these indirect, noisy, peripheral proxies.
- ~50 Hz: Accelerometer sample rate (tri-axial MEMS sensor)
- 25–100 Hz: PPG sample rate (green/IR photoplethysmography)
- 0.01–0.1°C: Skin temp resolution (thermistor or thermopile)
- Multi-night: Typical monitoring span (vs. single-night lab PSG)
Three channels, three different physiologies
Accelerometry (actigraphy): a 3-axis MEMS accelerometer records wrist movement. Sleep researchers have used actigraphy since the 1990s as a rough sleep/wake proxy — the core assumption being that a still wrist usually means a sleeping body. Movement is summarized into "activity counts" per epoch.
Photoplethysmography (PPG): green or infrared LEDs shine into the skin; a photodiode measures light absorption changes as blood volume pulses with each heartbeat. From the pulse waveform, instantaneous heart rate and heart-rate variability (HRV) are derived — signals that reflect autonomic nervous system activity, which shifts characteristically across sleep stages.
Skin temperature: distal skin temperature rises as peripheral vasodilation increases heat loss during the sleep-onset process, and continues to shift subtly across the night in a circadian- and stage-linked pattern — a comparatively weak but still informative channel.
None of these three signals directly measures brain activity. Clinical polysomnography scores sleep stage from EEG, EOG (eye movement), and EMG (muscle tone) — wearables must infer the same four-way label from indirect, peripheral, autonomic-nervous-system proxies instead.
Noise, artifacts, and the real-world recording environment
Unlike a supervised sleep lab, home recordings are contaminated by motion artifacts (PPG signal drops out when the wrist moves), loose-fit variability (looser bands attenuate the PPG signal), skin tone and perfusion differences (PPG amplitude varies with skin pigmentation and peripheral blood flow), and cold extremities (delayed or blunted temperature signal).
Manufacturers apply substantial pre-processing before any classifier ever runs: band-pass filtering of the PPG waveform (typically 0.5–4 Hz to isolate the cardiac pulse), motion-artifact rejection using accelerometer-PPG cross-correlation, and interpolation across brief signal dropouts. The quality of this front-end conditioning is itself a major driver of downstream staging accuracy.
Commercial implementations
Oura Ring (Gen 3): PPG at the finger artery (stronger, more stable signal than the wrist), plus body temperature and accelerometer; validated against PSG with published epoch-by-epoch agreement studies (de Zambotti et al., 2019).
Whoop 4.0 and 5.0: wrist-worn, 5-LED PPG array plus accelerometer, tuned for HRV-driven recovery metrics alongside sleep staging.
Apple Watch: accelerometer plus wrist-based PPG; Apple published its staging validation methodology (Walch et al., 2019, developed with independent Apple Watch data) ahead of watchOS Sleep Stages.
Fitbit (Sense, Charge, Versa lines): one of the first mass-market four-stage systems, validated in Beattie et al. (2017) against PSG using a combination of movement and heart-rate variability.
Epoch Segmentation & Feature Extraction
Classifiers do not see raw waveforms directly — they see engineered summaries. The 30-second epoch is the atomic unit of sleep staging, inherited directly from the clinical AASM (American Academy of Sleep Medicine) scoring manual, and every downstream feature and label is defined at that resolution.
- 30 sec: Standard epoch length (AASM clinical convention)
- 20–100+: Features per epoch (time- & frequency-domain)
- RMSSD: Key HRV feature (root-mean-square of successive NN differences)
- Counts / epoch: Activity metric (summed rectified acceleration)
Why 30 seconds?
Human PSG scorers historically reviewed sleep records on 30-second paper epochs (a page-per-epoch convention from the original Rechtschaffen & Kales 1968 manual, later refined by the AASM in 2007). Wearable algorithms inherited this window so that model outputs can be directly compared, epoch-for-epoch, against PSG ground truth — the entire validation literature depends on this shared time base.
Within each 30-second window, and often a sliding context of several minutes before and after, features are computed and handed to the classifier.
Activity and movement features
Activity counts: the classic actigraphy feature — accelerometer signal is high-pass filtered, rectified, and summed over the epoch, producing a single scalar that correlates with gross motor movement.
Zero-crossing rate and movement index: how often the signal crosses a threshold, capturing fidgeting versus stillness.
Posture / orientation: static accelerometer axes indicate body position (supine, side, prone), useful because REM sleep involves near-total skeletal muscle atonia — almost no posture change — while light sleep shows more frequent repositioning.
Heart-rate and HRV features — the autonomic fingerprint
Mean and standard deviation of instantaneous HR per epoch.
RMSSD (root mean square of successive differences): a time-domain HRV metric reflecting parasympathetic (vagal) tone; it rises during deep sleep as parasympathetic activity dominates.
LF/HF ratio: the ratio of low-frequency to high-frequency spectral power in the HR tachogram, a classic marker of sympathovagal balance; REM sleep shows a distinctive shift toward sympathetic activation despite muscle atonia, closely resembling a wake-like autonomic signature.
HR variability envelope: REM epochs typically show irregular, "bursty" heart-rate fluctuations correlated with phasic eye movements, while deep sleep shows the most stable, slow, low heart rate of the night.
HRV features are what let algorithms tell REM apart from quiet wakefulness and light sleep — accelerometer data alone is nearly identical in both states, since the body is still in each. The autonomic nervous system signature captured by PPG-derived HRV is the single biggest accuracy driver added on top of pure actigraphy.
The Classification Algorithm — Gradient-Boosted Trees and CNN-LSTM Networks
With a clean per-epoch feature vector in hand, a trained classifier assigns one of four labels — Wake, Light (N1–N2), Deep (N3), or REM — to every 30-second window of the night. Two architecture families dominate the published and commercial literature.
- GBM / CNN-LSTM: Common model families (XGBoost, LightGBM, deep sequence nets)
- PSG scoring: Training ground truth (AASM-certified sleep technologists)
- 1,000s of nights: Typical training corpus (multi-site sleep-lab datasets)
- 4: Output classes (Wake / Light / Deep / REM)
Gradient-boosted trees (XGBoost, LightGBM)
A large fraction of shipped commercial staging algorithms use gradient-boosted decision tree ensembles over hand-engineered features (the ones described in Stage 2). Trees are cheap to run on-device or in a lightweight cloud pipeline, naturally handle heterogeneous feature types and missing data (e.g. a dropped PPG segment), and are straightforward to validate and audit against clinical datasets — an important consideration for regulatory clearance (several sleep-staging features have received FDA clearance as software, e.g. via 510(k) pathways for actigraphy-based systems).
A typical model ensembles hundreds of shallow trees, each correcting the residual errors of the previous ones, trained with a multi-class log-loss objective against PSG epoch labels.
CNN-LSTM and transformer sequence models
Deep sequence models take a longer window of raw or lightly processed signal (minutes of accelerometer + PPG) and let convolutional layers learn their own local features, followed by a recurrent (LSTM/GRU) or self-attention layer that models transitions between epochs — capturing the fact that sleep stages are highly autocorrelated (a Deep-sleep epoch is far more likely to be followed by another Deep or Light epoch than by REM).
This end-to-end approach can outperform hand-engineered feature pipelines when enough training data is available, but requires much larger labeled PSG datasets and more compute, and is harder to interpret or certify.
Training against polysomnography ground truth
Every commercial or research staging algorithm is ultimately supervised by human PSG scoring: overnight recordings of EEG (brain electrical activity), EOG (eye movement), and EMG (chin muscle tone), independently reviewed by one or more AASM-certified sleep technologists following standardized scoring rules.
Because human scorers themselves only agree with each other on the four-class label roughly 80–85% of the time (inter-rater reliability), the "ground truth" the wearable model is trained against already contains inherent ambiguity — a ceiling that limits how much better any algorithm can ever score.
Hypnogram Construction — Assembling a Night of Sleep Architecture
A hypnogram is the classic staircase chart of sleep science: sleep stage plotted against clock time across the whole recording. Turning noisy, independently-classified 30-second epochs into a coherent, clinically interpretable hypnogram requires temporal smoothing and knowledge of normal sleep-cycle structure.
- ~90 min: NREM–REM cycle length (per full sleep cycle)
- 4–6: Cycles per night (in a typical 7–8 hour night)
- First half: Deep sleep concentration (of the night, decays across cycles)
- Increases: REM proportion growth (REM bouts lengthen toward morning)
Smoothing raw predictions into a plausible hypnogram
Raw per-epoch classifier output is "flickery" — isolated single epochs can be misclassified even when surrounding context is unambiguous. Post-processing steps commonly include:
Minimum bout duration: a single epoch of Deep sleep surrounded by Light sleep is often merged into the surrounding stage, since real sleep-stage bouts rarely last under 1–2 minutes.
Transition constraints: some stage transitions are physiologically implausible in a single step (e.g. Deep sleep directly to REM is rare); a hidden Markov model (HMM) or similar temporal smoother can be layered on top of the raw classifier to favor plausible sequences.
Majority-vote / median filtering: a sliding window vote over neighboring epochs' predicted labels reduces isolated misclassifications.
Typical night architecture used to sanity-check output
A healthy adult night cycles through roughly 4–6 full NREM–REM cycles of about 90 minutes each. Deep sleep (N3) is concentrated in the first one to two cycles and becomes rare later in the night; REM sleep, by contrast, is brief early in the night (first REM bout, "REM latency," typically 70–120 minutes after sleep onset) and lengthens progressively toward the early morning hours, so the longest REM bouts usually occur just before waking.
Summary statistics computed from the finished hypnogram — Total Sleep Time (TST), Sleep Efficiency (TST / time in bed), REM latency, Wake After Sleep Onset (WASO), and percentage time in each stage — are the numbers most consumer sleep apps actually surface to users, even though the underlying hypnogram is far richer.
Why accelerometer-only systems get the shape of the night wrong
Purely actigraphy-based hypnograms (no heart-rate channel) systematically overestimate total sleep time and underestimate wake after sleep onset — a person lying still but awake in bed looks identical to a sleeping person from the accelerometer's point of view. This bias is well documented in the actigraphy validation literature going back decades and is precisely the gap that adding PPG-derived heart rate and HRV closes: autonomic signatures (elevated, variable heart rate; reduced HRV) can flag quiet wakefulness that movement alone would miss.
Clinical Validation Against Polysomnography
The only way to know whether a wearable's hypnogram is trustworthy is to record it simultaneously with lab-grade polysomnography and compare stage labels epoch by epoch. Published validation studies consistently show a pattern: coarse wake/sleep discrimination is quite good, but four-stage discrimination — especially deep sleep and REM — remains meaningfully harder.
- 70–90%: Wake/sleep binary agreement (epoch-by-epoch vs PSG)
- 60–75%: 4-stage overall accuracy (Wake / Light / Deep / REM)
- ~0.5–0.6: Cohen's kappa (4-stage) ("moderate" agreement by convention)
- +15–20 pts: REM sensitivity gain from HRV (vs. accelerometer-only baseline)
Reading the accuracy numbers correctly
Two-class (asleep vs. awake) epoch agreement between consumer wearables and PSG is typically reported in the 70–90% range across published validations — respectable, but remember that always guessing "asleep" already scores well given how few epochs of a night are spent awake.
Four-class staging (Wake/Light/Deep/REM) is a much harder problem: published overall accuracy figures cluster around 60–75%, and Cohen's kappa — a chance-corrected agreement statistic — typically lands around 0.5–0.6, conventionally interpreted as "moderate" agreement. For comparison, agreement between two independent human PSG scorers on the same recording is itself only around kappa 0.6–0.75, so wearables are approaching, but not yet matching, human-to-human reliability.
Deep sleep and REM are consistently the hardest stages to call correctly. Deep sleep is often confused with Light sleep because both can present as physiologically "quiet"; REM is confused with either Light sleep or brief wake because REM muscle atonia looks physically still (like sleep) while REM's autonomic activation looks aroused (like wake) — it sits ambiguously between the two on peripheral signals alone.
What improves accuracy
Adding PPG-derived heart rate and HRV on top of accelerometer-only actigraphy is the single largest accuracy improvement documented in the literature — particularly for REM detection, since REM's distinctive autonomic signature (irregular, elevated heart rate despite muscular stillness) is invisible to an accelerometer but clearly visible in HRV features.
Adding skin temperature contributes a smaller, secondary improvement, mainly helping refine sleep-onset and wake-transition timing rather than deep/REM discrimination.
Longer training datasets, multi-night personalization (learning an individual's own resting HR and movement baseline), and sequence-aware models that use context from neighboring epochs also measurably improve four-stage accuracy over naïve single-epoch classifiers.
Regulatory and research status
Several wearable sleep-staging features have undergone formal validation studies against PSG and, in some cases, regulatory clearance as software (e.g. FDA 510(k) clearance for specific actigraphy- or PPG-based sleep-staging algorithms). Independent academic validation remains an active research area — device firmware and algorithms are periodically updated, so published accuracy figures for any specific consumer product can become outdated within a product generation.
Despite the four-stage accuracy gap, wearables' continuous, multi-night, low-burden monitoring captures night-to-night variability that a single lab PSG night cannot — making them clinically useful as a longitudinal screening and trend tool even where they fall short of PSG's single-night precision.
Sensor modality vs. per-stage classification accuracy
| Product | Indication | Trial Design | Key Result |
|---|---|---|---|
| Actigraphy only | Wake vs Sleep: 75–85% | Movement-based; misreads quiet wakefulness as sleep, cannot see autonomic state at all | Lowest power draw, simplest hardware |
| Actigraphy + Heart Rate | Wake vs Sleep: 85–90% · 4-stage: ~65% | Adds mean HR trend; some REM/Light separation via HR elevation | Good balance of accuracy and battery life |
| Actigraphy + HR + HRV | 4-stage: 65–75% · REM sensitivity highest | Full autonomic feature set (RMSSD, LF/HF) captures parasympathetic/sympathetic shifts across stages | Best commercially available accuracy (Oura, Whoop, Apple Watch) |
| Actigraphy + HR + HRV + Temperature | 4-stage: modest gain over HRV alone | Temperature mainly sharpens sleep-onset/wake-transition timing, not deep/REM discrimination | Best available, still short of PSG precision |
An algorithm for classifying sleep stages using data from an accelerometer and pulse sensor worn on the body.
2D · HTML5 Canvas 2D · 60 FPS target · runs fully client-side, no install