Portable electroencephalogram sleep detection and analysis system and method
By combining intra-ear EEG acquisition with low-power pulse neural network calculations, the problems of high cost, cumbersome wearing, and low accuracy of existing EEG sleep monitoring devices have been solved, realizing a portable, low-cost, and highly accurate sleep staging system.
Patent Information
- Application Number
- CN202511692303.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-18
- Publication Date
- 2026-02-17
AI Technical Summary
Existing EEG sleep monitoring devices suffer from high costs, cumbersome wearing, lack of portability, and low accuracy in sleep segmentation. Wearable devices, in particular, are ineffective in sleep segmentation and most require computer or cloud platform calculations.
By combining intra-ear EEG acquisition with low-power spiking neural network computation, EEG signals are acquired through intra-ear dry electrodes and integrated into an embedded platform for signal processing and sleep staging, including feature extraction, population coding, and spiking neural network modeling, thus realizing portable sleep staging.
It achieves a low-cost, highly portable, and easy-to-use sleep staging solution, featuring high staging accuracy and low power consumption, significantly improving the response speed and prediction accuracy of sleep staging.
Smart Images

Figure CN121533688A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of wearable bioelectrical signal acquisition and sleep monitoring, and particularly to a portable EEG sleep detection and analysis system and method. Background Technology
[0002] Existing EEG monitoring technologies used for sleep staging are mostly medical-grade scalp EEG monitoring systems, characterized by high accuracy, strict wearing requirements, and difficulty in home application. Commonly used wet EEG caps also have certain wearing requirements and are not suitable for prolonged overnight wear. Implantable electrodes have low public acceptance, while wearable sleep monitoring suffers from large staging errors and low accuracy.
[0003] For intra-ear EEG acquisition systems, there are CN 117796815 and CN 210871574, both of which achieve the acquisition and transmission of intra-ear EEG data. However, their systems are unsuitable for sleep staging applications, especially lacking a host computer for deploying an automatic classification model. CN 222285483 is also an EEG acquisition system, but it does not involve specific electrode design or sleep staging models.
[0004] Existing EEG sleep staging devices have the following problems: 1. They are obviously costly, and are cumbersome and inconvenient to wear or inaccurate (forehead patch); 2. Because current sleep staging systems have high computational requirements, they are currently based on computers or cloud platforms for calculation. Summary of the Invention
[0005] To overcome the high cost and cumbersome process of existing medical scalp EEG monitoring and sleep staging systems, the present invention aims to provide a portable EEG sleep detection and analysis system and method. By fusing in-ear EEG acquisition with low-power pulse neural network calculation, the sleep staging system is integrated into an embedded platform, while solving the problem of poor staging effect of wearable sleep monitoring devices. Ultimately, it achieves an EEG signal detection and sleep staging solution that combines high portability, ease of use, low power consumption, and low cost.
[0006] The objective of this invention is achieved through the following technical solution: A portable EEG sleep monitoring and analysis system, comprising: An intra-ear EEG acquisition unit is used to acquire differential EEG signals within the ear canal and convert them into a digital data stream for transmission. This unit specifically includes an acquisition module and a signal processing and transmission module. The acquisition module includes an earplug suitable for insertion into the ear canal and at least two dry electrodes embedded in the surface of the earplug for acquiring differential EEG signals within the ear canal. The signal processing and transmission module is electrically connected to the acquisition module and is used to filter, amplify, and perform analog-to-digital conversion on the acquired analog EEG signals, and output a digital data stream.
[0007] A data processing and computing unit is used to preprocess the digital data stream; the unit is configured to perform preprocessing operations, including: frequency domain filtering to extract EEG signals in the target frequency band, power frequency interference suppression, and separation and removal of motion artifacts.
[0008] The sleep staging unit is used to input preprocessed data into an event-driven spiking neural network model to classify sleep stages; this model is the core of the sleep staging unit and includes: The feature extraction module is used to extract local spatiotemporal features from the input EEG signal sequence; The population coding module, connected to the feature extraction module, is used to convert the extracted continuous features into high-dimensional distributed population coding features; A spiking neural network reservoir module, connected to the population encoding module, is used to dynamically capture time-series information in the population encoding features through the spiking of neurons, and convert the dynamic spiking sequence into a static feature vector; The classifier module, connected to the spiking neural network reservoir module, is used to generate classification probabilities for multiple sleep stages based on the static feature vector.
[0009] This invention also provides a portable method for EEG sleep detection and analysis, comprising the following steps: Intra-auricular EEG acquisition: Differential EEG signals are acquired within the ear canal and converted into digital data streams for transmission; Data processing and computation: Preprocessing the digital data stream; Sleep staging: The preprocessed data is input into an event-driven spiking neural network model to classify sleep stages.
[0010] This invention employs in-ear electroencephalography (EEG) detection technology to replace traditional scalp EEG detection, and uses a spiking neural network (SNN) for signal analysis. All components of this system are integrated into a microcontroller. In-ear EEG acquisition completely replaces scalp EEG acquisition, and a portable system for EEG acquisition, processing, and sleep quality detection is constructed. A complete closed-loop system is built, encompassing in-ear dry electrode acquisition, digital processing, and upper-level temporal classification. The system is compact, comfortable to wear, and possesses excellent anti-interference capabilities. Optional implementation methods include: replacing the wireless modulation mode to support long-distance communication; replacing the processing platform to improve processing flexibility; and supporting dual-channel synchronous acquisition to expand data analysis capabilities. Compared to traditional PSG or head-mounted device-based models, this invention significantly improves the response speed and prediction accuracy of sleep staging.
[0011] Compared with the prior art, the present invention has the following advantages and beneficial effects: (1) The sleep staging algorithm model of the present invention has the characteristics of low training cost, short training time and low power consumption. Since the internal structure of the water reservoir does not need to be trained, only the convolutional layer and the classifier are trained, the training speed of the model is relatively fast. At the same time, since the spiking neurons process discrete pulse signals, the power consumption of the model is also low.
[0012] (2) The portable EEG sleep detection and analysis system of the present invention has controllable cost and addresses the problems in the prior art: medical cap-type EEG cables are numerous, components are scattered, and there are many customized connectors, resulting in high BOM and assembly time; it proposes specific solutions: using universal AFE (such as ADS1299) for in-ear dry electrodes and universal MCU; using USB direct supply to eliminate battery / charging management; board-to-board with FPC modularization to reduce dedicated wiring harnesses; engineering mechanism: eliminating the battery and charging link can directly eliminate DC / DC ripple and safety isolation devices; unified interface and standard parts reduce procurement and spare parts costs.
[0013] (3) The present invention simplifies the acquisition process and addresses the problems in the prior art: the scalp EEG wearing is time-consuming, and the gel processing and impedance adjustment are cumbersome; it proposes specific solutions: the earpiece electrode is "plug and play" and automatically initializes upon power-up; lead / impedance self-test (LOFF) and three-state mode (acquisition / impedance / self-test) can be switched with one click; the virtual serial port is plug and play. Engineering mechanism: short-path bipolar and contact quality inspection put "contact quality" forward, significantly reducing the cost of back-end parameter adjustment; mode switching uniformly follows the safe path of "stop acquisition → modify register → resume acquisition".
[0014] (4) The present invention has a high degree of system integration. In response to the problems in the prior art, such as the dispersed front end and numerous connections of traditional systems, which are susceptible to interconnection noise and ground loops, a specific solution is proposed: the SRB / BIAS / anti-aliasing network and the A / D front end are concentrated on a micro acquisition board; the MCU is responsible for register configuration, timing and packaging; the host computer only performs display and basic preprocessing. Engineering mechanism: the analog domain is concentrated and the wiring is short. Star grounding and local decoupling reduce parasitic coupling; the hierarchical functions are clear, which facilitates mass production and maintenance.
[0015] (5) The present invention is highly portable and addresses the problems in the prior art: the headband is bulky and heavy, making it unsuitable for long-term home monitoring. Specific implementation: It adopts in-ear bipolar, short-path simulation; the same hardware supports both USB wired and BLE / Wi-Fi wireless modes. Engineering mechanism: The length and quality of the cable directly affect the micro-motion and power frequency coupling; shortening the cable reduces the electromagnetic coupling area. Attached Figure Description
[0016] Figure 1 This is a schematic diagram of the composition of a portable EEG sleep detection and analysis system according to one embodiment of the present invention.
[0017] Figure 2 This is a schematic diagram of an earplug and electrodes according to one embodiment of the present invention.
[0018] Figure 3 This is a flowchart illustrating the steps of a portable EEG sleep detection and analysis method according to one embodiment of the present invention.
[0019] Figure 4 This is a structural diagram of a sleep staging algorithm according to one embodiment of the present invention.
[0020] Figure 5 This is a block diagram illustrating the working principle of a portable EEG sleep detection and analysis system according to one embodiment of the present invention.
[0021] Figure 6 This is a flowchart illustrating the workflow of a portable EEG sleep detection and analysis system according to one embodiment of the present invention. Detailed Implementation
[0022] The present invention will be further described in detail below with reference to the embodiments, but the implementation of the present invention is not limited thereto.
[0023] Example 1 like Figure 1 As shown, embodiments of the present invention provide a portable EEG sleep detection and analysis system, including... An intra-ear EEG acquisition unit is used to acquire differential EEG signals within the ear canal and convert them into digital data streams for transmission; the EEG acquisition unit further includes an acquisition module and an analog signal processing and transmission circuit board; such as Figure 2 As shown, the acquisition module includes an earpiece 1 and two dry electrodes 2. The dry electrodes are embedded in the earpiece, and during use, their surfaces are in close contact with the upper wall of the ear canal for microvolt-level differential EEG signal acquisition. The analog signal processing and transmission circuit board is connected via an FPC and a dedicated connector to implement anti-aliasing low-pass filtering, common-mode bias, notch filtering, and EMI suppression. It converts the analog EEG signal into a digital data stream through a built-in adjustable gain and high-precision analog-to-digital converter module and transmits it to the central control module. The control module firmware is responsible for power-on self-test and parameter initialization. After acquisition, it sends the raw data byte stream to the USB-TTL conversion module via a standard UART serial port, which automatically processes the USB protocol and receives it on the host computer in the form of a virtual serial port. The system is powered through a TTL-USB interface, directly obtaining power from the USB bus on the host side, without the need for an additional battery or charging management module. The firmware relies on USB 5V power supply and is regulated to the voltage required by the MCU to ensure stable system operation.
[0024] The data processing and computing unit is used to preprocess the digital data stream transmitted by the intraocular EEG acquisition unit; the digital preprocessing includes frequency domain filtering, power frequency interference suppression, separation and removal of noise such as motion artifacts, and baseline stabilization of the EEG stream; the data processing and computing unit can be deployed on a host device (such as a PC, edge terminal, etc.).
[0025] The sleep staging unit is used to input preprocessed data into an event-driven spiking neural network model. This model reads the signal sequence in a sliding window manner, completes the identification and classification of sleep stages, and generates a corresponding sleep quality assessment report.
[0026] The sleep staging unit further includes a data processing module, a feature extraction module, a population encoding module, a spiking neural network (SNN) reservoir module, and a classifier module. The data processing module ensures data validity through quality checks, segments continuous signals into 30-second standard sleep stage time windows, performs T-SMOTE data augmentation, and then performs data standardization based on global mean and standard deviation, batch loading, and sample index tracking. The feature extraction module performs CNN feature extraction on the data processed by the data processing module. The population encoding module performs Gaussian population encoding on the feature-extracted data. The SNN reservoir module dynamically captures time-series information through neuronal spiking and converts dynamic spiking information into static features by accumulating the number of spiking events within the time window. The classifier module uses the static feature data as input to the classifier and ultimately outputs the classification probabilities of multiple sleep stages.
[0027] The data processing module includes a preprocessing module, a T-SMOTE data augmentation module, and a dataset management module. It removes samples containing NaN or with abnormal amplitudes through quality checks to ensure data validity and segments continuous signals into standard 30-second sleep phase time windows. The T-SMOTE data augmentation module generates synthetic samples by performing time interpolation, adding Gaussian noise, and time smoothing on similar samples, dynamically balancing the dataset distribution. The dataset management module supports data standardization based on global mean and standard deviation, batch loading, and sample index tracking, adapting to the PyTorch training process.
[0028] After preprocessing by the data processing module, the data is input into an event-driven temporal classification model. This model reads signal sequences using a sliding window approach, identifies and classifies sleep stages, and generates a corresponding sleep quality assessment report. Compared to traditional temporal networks, this model exhibits lower inference latency, higher energy efficiency, and superior performance at the edge.
[0029] The feature extraction module includes a CNN feature extraction module; the CNN feature extraction module uses a 3-layer 1D convolutional neural network to extract local spatiotemporal features of EEG signals; the population coding module is used to convert the continuous features output by the CNN into a distributed population representation, expanding the low-dimensional CNN features into high-dimensional population coding features, thereby enhancing robustness to noise and feature discriminability.
[0030] The spiking neural reservoir and classifier module includes a fixed-weight spiking reservoir module, a feature integration module, and a multi-layer classifier. The fixed-weight spiking reservoir module is a reservoir for implementing the LIF neuron model based on the SpikingJelly library, receiving population-encoded features through fully connected layers. The fixed-weight spiking reservoir module dynamically captures time-series information through neuronal spiking. The feature integration module is used to convert dynamic spiking information into static features by accumulating the number of spikings by neurons within a time window, which serves as input to the classifier. The multi-layer classifier consists of three fully connected layers, including batch normalization and dropout regularization, and is used to finally output the classification probabilities of the five sleep stages.
[0031] like Figure 3 As shown, this embodiment also provides a portable EEG sleep detection and analysis method, including the following steps: S1 Intra-auricular EEG Acquisition: Differential EEG signals are acquired within the ear canal and converted into digital data streams for transmission; S2 Data Processing and Calculation: Preprocessing the digital data stream transmitted by the intraocular EEG acquisition unit; the data preprocessing includes frequency domain filtering, power frequency interference suppression, separation and removal of noise such as motion artifacts, and baseline stabilization of the EEG stream; S3 Sleep Staging: The preprocessed data is input into an event-driven spiking neural network model. This model reads the signal sequence in a sliding window manner, completes the identification and classification of sleep stages, and generates a corresponding sleep quality assessment report.
[0032] This sleep staging model, based on single-subject electroencephalogram (EEG) data, integrates convolutional neural networks (CNNs), spiking neural networks (SNNs), a reservoir, and population encoding techniques. Its core objective is to achieve high-precision classification of sleep stages (NREM1, NREM2, NREM3, Wake, REM) through multi-level feature extraction and transformation. The model design focuses on single-subject data analysis, reducing computational complexity through a fixed-weight spiking reservoir while retaining the ability to capture the spatiotemporal characteristics of EEG signals, thus balancing classification accuracy and computational efficiency. The algorithm structure is as follows: Figure 4As shown: First, a structure consisting of alternating convolutional layers (Conv1d), batch normalization layers (BatchNormal1d), and ReLU activation function layers is used to extract features from the input data. Next, "Population Encoding" transforms the extracted features into a form suitable for subsequent reservoir computation. Then, the data enters the "Reservoir," where nodes perform complex processing and representation of the input information through internal dynamic connections and state updates. Finally, the data processed in the reservoir is passed to the "Classifier," which performs the final classification task.
[0033] The data processing described in step S3 includes preprocessing, T-SMOTE data augmentation processing, and dataset management; The EEG data loading and preprocessing process involves loading EEG data in EDF format based on the MNE library, automatically identifying and removing non-EEG channels, applying bandpass filtering to remove noise, and removing samples containing NaN or with abnormal amplitudes through quality checks to ensure data validity. Continuous signals are then divided into a standard 30-second sleep phase time window. The T-SMOTE data augmentation process generates synthetic samples by performing time interpolation, adding Gaussian noise, and time smoothing on similar samples, thereby dynamically balancing the distribution of the dataset. The dataset management supports data standardization based on global mean and standard deviation, batch loading, and sample index tracking, adapting to the PyTorch training process.
[0034] To better illustrate the beneficial effects of the present invention, this embodiment selects three existing methods as comparative schemes: Comparative scheme one is the EEGNet convolutional neural network model, which adopts a pure convolutional structure and extracts local spatiotemporal features only through temporal and spatial convolutions; Comparative scheme two is the Convolutional Neural Network – Long Short-Term Memory (CNN-LSTM) model, which connects LSTM recurrent layers after convolutional feature extraction to model long-term temporal dependencies; Comparative scheme three is the Convolutional Neural Network – Reservoir Delta (CNN-Reservoir-Delta model), which connects a continuous value, delta-updated reservoir layer after the convolutional front end. The internal state of the reservoir is updated linearly or nearly linearly, and it does not have the leak-integration-firing spiking neuron dynamics. Unlike the aforementioned comparative schemes, the Convolutional Neural Network–Leaky Integrate-and-Fire Reservoir with Population Coding (CNN-LIF-Reservoir-PC model) proposed in this invention first introduces a population coding module after convolutional feature extraction. This module maps continuous-value EEG features into a population coding form represented collaboratively by a group of neurons, which is then input into a recursive reservoir composed of LIF spiking neurons. Nonlinear temporal coding is achieved through membrane potential integration, leakage, and threshold reset. Only the readout layer parameters are trained, thus structurally distinguishing it from pure convolutional models, convolutional-LSTM models, and continuous-value reservoir models.
[0035] Under the same dataset and training strategy, the overall classification accuracy of the comparison scheme 1, EEGNet convolutional neural network model, is approximately 0.70; the accuracy of the comparison scheme 2, CNN-LSTM model, is approximately 0.74; the accuracy of the comparison scheme 3, CNN-Reservoir-Delta model, is approximately 0.45; while the accuracy of the CNN-LIF-Reservoir-PC model of this invention is approximately 0.80. Therefore, by introducing population encoding and LIF impulse reservoir, the model of this invention, while maintaining a compact model structure, simple training process, and controllable computational cost, achieves significant performance gains by improving the accuracy of the three comparison models by approximately 10 percentage points, 5 percentage points, and 35 percentage points, respectively.
[0036] Example 2 This embodiment provides specific implementation steps for data processing calculations and sleep staging: Step S211 (Training Data Loading and Label Mapping): Batch read offline EEG records and corresponding sleep labels. Load the EEG using mne.io.read_raw_edf or an equivalent method, and extract the sampling rate f. s Synchronously read the tag file (such as MAT / CSV) and map the stage tags to integers: NREM1→0, NREM2→1, NREM3→2, Wake→3, REM→4; complete timing alignment.
[0037] Step S212 (Non-EEG Channel Filtering and Naming Standardization): Remove non-EEG channels containing keywords such as "Event / ECG / EOG / EMG", and retain only EEG channels for training; standardize channel naming (e.g., left / right ear canal refer to unified naming) to ensure consistency in subsequent pipelines.
[0038] Step S213 (Zero-phase preprocessing for bandpass and notch filtering, training-specific parameters): Perform cascaded zero-phase filtering on the EEG signal obtained in step S212: first, bandpass FIR (0.50–45.00 Hz, Firwin linear phase, applied forward and backward to obtain zero-phase output), then power frequency bandstop (50 or 60 Hz and its narrowband, zero-phase implementation), to obtain the preprocessed sequence for training. The specific orders of the bandpass and notch filtering are fixed in the implementation according to the stopband attenuation and transition bandwidth, which can reproduce the experimental conditions.
[0039] Step S214 (Artifact Separation and Rereference): ICA / SSP is used to remove artifact components such as blinking, ECG, and EMG, and the reference is unified to the average reference or the specified ear canal reference. The output is used as a stable baseline for subsequent sample construction.
[0040] Step S311 (30-second sample construction and synchronized labeling): Slice training samples into 30-second windows (number of sample points L). epoch =30× f s In this embodiment, L epoch According to actual f s (Automatically calculated), each segment is assigned a single stage label based on time alignment, forming a (segment, label) sample list.
[0041] Step S312 (Sample-level quality check and rejection rules): Perform numerical and amplitude quality checks on each 30 s segment: If NaN / Inf exists, or the standard deviation of any channel is <1e−6 or >1e4, then the sample is rejected; the sample is retained for subsequent enhancement and modeling.
[0042] Step S313 (Time-Aware Oversampling and Quota Constraints): To alleviate class imbalance, minority class oversampling is performed while maintaining temporal consistency. Let the original number of samples in class c be n. c ( The maximum class count is n max Let the target upper limit coefficient ρ = 0.6, and the enhancement multiplier strategy be {NREM1:4, Wake:2, REM:2}. Let the local upper limit of the c-th class be r. c The number of additional samples required for each category is calculated in m. c =max( 0, min( ⌈ρ·n max ⌉ − n c , ⌈r c ·n c ⌉ ) ) Calculate to ensure that the number of samples in each category after augmentation does not exceed 0.6·n max .
[0043] n max = max c n c m c = max( 0, min( ⌈ρ·n max ⌉ − n c , ⌈r c ·n c ⌉ ) ) n c ≤ ⌈ρ·n max ⌉.
[0044] Step S314 (Synthetic Sample Generation and Temporal Smoothing Details): When the number of original samples of a certain class is n c When the value is less than 2, zero-mean Gaussian noise ε (intensity = 0.01 × standard deviation of the sample) is superimposed on the original sample X. ε ~ 𝒩( 0, (η· ), η = 0.01 Z = X + ε The mean is 0 and the variance is 0. Gaussian distribution; When the number of samples n cWhen the value is ≥2, two segments s1 and s2 of the same type are randomly selected, and linear interpolation α·s1+(1−α)·s2 is performed with α∈(0,1), and the same weak noise is superimposed (the parameter name k_neighbors is reserved as 5 according to the implementation, but in this embodiment, the interpolation of two samples is effective). .
[0045] Subsequently, uniform smoothing is performed on the time axis with a window length of 3 to reduce interpolation spikes without disrupting the power spectrum structure; finally, it is concatenated with the original samples to form an enhanced dataset that satisfies the aforementioned quota constraint m. c . : Sample segments after noise addition / interpolation; Smooth the results:
[0046] Step S315 (Global Normalization and Dataset Encapsulation): Apply the augmentation to all samples... Calculate the global mean across the "samples × time" dimension for each channel. with standard deviation (When σ < 1e−6, replace it with 1.0 to avoid division by zero).
[0047] .
[0048] Execute on each segment Normalization; encapsulation into a training dataset, maintaining index traceability for subsequent evaluation: .
[0049] Step S321 (CNN Local Spatiotemporal Feature Extraction Structure): Extract local spatiotemporal features directly from the original EEG. A three-layer 1D convolution is used (kernel_size=5, stride=2, padding=2, ensuring the time step is halved for each layer), with the number of channels set to: "input→64→64→64"; each layer is followed by BatchNorm1d (batch normalization) and ReLU (activation function), and the output feature time step is L. epoch / 8. For network input; Indicates the first Layer input, convolution output, and post-activation features; Let BN be the affine parameter; The mean / variance within the batch; It is the stability constant; For channel The bias; For the first Layer from input channel To output channel The Each convolutional kernel weight; For learnable affine parameters, It is the numerical stability constant; Acting on elements get .
[0050] y o,t (ℓ) = ∑ i=1 C in ∑ k=0 K−1 w o,i,k (ℓ) · x i, t−s·k (ℓ−1) + b o (ℓ) (ℓ) = ReLU( BN( y (ℓ) ) ).
[0051] Step S322 (Population Encoding: Continuous Features → Multicenter Response): Transform the continuous features of the CNN into distributed impulse inputs. First, use tanh to compress the features to [−1,1] and then linearly map them to [−3,3] to obtain... (where F ∈ R^(64×L'), Let d = 1..64, t = 1..L'). On the interval [-3,3], 20 Gaussian centers are set at equal intervals for each feature dimension d, and the center positions are denoted as . j = 1..20, with a step size of Therefore Core width set to The current magnitude of any feature dimension d. Its response to the j-th center is defined as the amplitude and the response to the center. The Gaussian radial basis function values are specifically: Calculate the similarity / proximity measure between the current scalar feature and the center and concatenate them along the center dimension to obtain a population feature sequence of 64×20=1280 dimensions. The positional encoding information of the "amplitude interval" is retained to enhance separability and noise resistance.
[0052] Step S331 (LIF Pulsating Reservoir and Spectral Radius Scaling): The temporal dynamics of population characteristics are modeled using LIF neuron reservoirs. Input dimensions are 1280, reservoir size n_reservoir (e.g., 512), and time constant. =0.02 s (discrete decay converted according to characteristic time resolution), firing threshold Input feature vector ; Distribution vector , produce This indicates that the neuron at that moment Trigger pulse; Input weight Use Xavier for uniform initialization and freezing. Orthogonal initialization is used; Let the total input current be denoted by ; and let the leakage / memory coefficient be defined. Leakage and accumulation of input;
[0053] s(t) = 1(v(t) ≥ V th ) I in (t) = W in ·x t + W rec ·s(t−1) v(t) = β·(v(t−1) − V th ·s(t−1)) + (1−β)·I in (t), Circular weights Orthogonal initialization Then freeze after scaling to 0.9 by spectral radius. To obtain stable echo dynamics and suppress detonation / destruction.
[0054] Time-step calculation of I in (t) = W in ·x t + W rec ·s(t−1), update the membrane potential and threshold discharge.
[0055] Step S332 (Pulse Statistical Readout and Fixed-Length Characterization): Accumulate the firing rate (or estimate the firing rate) of each neuron within a single 30-second sample to obtain a length of n. reservoir The statistical vector g i It serves as a readout representation for use by the classifier.
[0056] g i = ∑ t=1L p s i (t) ĝ i = g i / L p .
[0057] Step S333 (Classifier Readout and Stage Probability): with g i The input is processed through two fully connected layers (hidden dimensions 64 → 32, both using BatchNorm + ReLU + Dropout 0.5), outputting 5-dimensional logits p. k The probability distribution {NREM1, NREM2, NREM3, Wake, REM} is obtained through softmax, and the largest one is used as the prediction stage for that sample.
[0058] Let the weights and biases of the first / second layer fully connected layers be set. , , ; Set the output layer weights and biases ; h1 = ReLU( W1·g + b1 ) h2 = ReLU( W2·h1+ b2 ) z = W3·h2+ b3 p k = exp( z k ) / ∑ j=1 5 exp( z j ) ŷ = argmax k p k .
[0059] Step S334 (Stratified Partitioning and Sampling Strategy): Use StratifiedShuffleSplit to divide the data into training and test / validation sets according to the category ratio, ensuring that the distribution of each stage is consistent in different subsets; under the premise of the established enhancement strategy, maintain the statistical independence of training / validation.
[0060] Step S335 (Optimizer, Loss Function, and Freezing Policy): Training only updates the learnable readout layers (and optional CNN affine parameters), and the reservoir weights. Freezing does not participate in reverse propagation , The optimizer used is Adam, and the loss function L is cross-entropy; the learning rate is... Hyperparameters are selected based on the validation set. Let the one-shot label of the i-th sample be at the k-th class position. Let the predicted probability of the i-th sample belonging to the k-th class be . Let the gradient of the parameters with respect to L be... Let the set of trainable parameters be... ,have: L = − (1 / N) · ∑ i=1 N ∑ k=1 5 y i,k · log p i,k θ ← θ − η·∇ θ L.
[0061] Step S336 (Training Monitoring, Early Stopping, and Selection of Metrics): Use the validation set Macro-F1 or Cohen'skappa as the primary selection metric and configure early stopping; monitor the burst rate distribution during training to ensure there are no large-scale crashes or saturation phenomena, and if necessary, use... Threshold or normalization fine-tuning brings the distribution back to the healthy range.
[0062] Step S337 (Offline Evaluation and Model Export): Perform offline inference on the validation / test set according to the fixed pipeline (steps S24→S28), outputting the confusion matrix, Macro-F1, and kappa; simultaneously export the model weights and configuration list (number of channels, f...). s Filtering parameters, population coding / reservoir / readout layer hyperparameters, class mapping table, and global normalized statistics (μ / σ) are used to facilitate subsequent deployment and reproduction of experimental conditions.
[0063] Step S338 (Training-side parameter fixed table): Epoch = 30 s; Bandpass FIR: 0.50–45.00 Hz (firwin, zero phase); Power band stop: 50 / 60 Hz (narrowband, zero phase); Quality control thresholds: NaN / Inf removal, STD lower limit 1e−6, upper limit 1e4; Enhancement parameters: ρ = 0.6, magnification {NREM1:4, Wake:2, REM:2}, noise intensity 0.01×STD, time smoothing window 3; Normalization: channel global μ / σ across samples × time (σ<1e−6→1.0); CNN: 3×(k=5, s=2, pad=2), channels 64 / 64 / 64; Population encoding: 20 centers per dimension, range [−3,3]. Reservoir: n reservoir (e.g., 512) Threshold 1.0, spectral radius 0.9 (W) in / W rec (Freeze); Classifier: 64→32→5, Dropout 0.5; Split: StratifiedShuffleSplit; Optimization: Adam + Cross-entropy.
[0064] Example 3 This embodiment provides an example of a portable EEG sleep monitoring and analysis system, the principle block diagram of which is shown below. Figure 5 As shown. The project is as follows. Figure 6 As shown, firstly, in the signal acquisition stage, signals are acquired through differential electrodes inside the ear and reference and bias electrodes. Next, the signal enters the front-end protection and anti-aliasing network for processing, and then is transmitted to the ADS1299 analog-to-digital converter chip for analog-to-digital conversion. The converted digital signal is transmitted to the MCU (Microcontroller Unit) via SPI (Serial Peripheral Interface), where register writing and data transmission operations are performed. Then, the data is sent out through a communication system (supporting serial port, USB, Bluetooth, etc.), and the PC / edge terminal receives and preprocesses the data. The preprocessed data is input into the sleep staging model in the host computer for sleep staging inference, and finally, the staging inference results are displayed.
[0065] The overall system and hardware composition are as follows: a) Electrodes and Connections: Two dry electrodes are embedded in the earpiece, closely attached to the upper wall of the external auditory canal to form a differential pair; the earlobe clip is an optional BIAS / reference. A three-core shielded flexible cable is connected to the acquisition board, and the shielding layer is connected to AGND at a single point on the board end.
[0066] b) Front end and A / D (ADS1299): Each INxP / INxN channel is fitted with a 2 kΩ series resistor and a 100 nF anti-aliasing resistor to ground (current limiting + first-order RC; if 50–150 Hz cutoff is required, R can be adjusted to 12–33 kΩ); AVDD=+5 V, AVSS=−5 V (or single supply 5 V internal bias), with a nearest 100 nF + 1 µF decoupling.
[0067] BIAS topology: BIAS_INV and BIAS are the same node; the BIAS node is connected in parallel with R11=1 MΩ / / C57=1 nF to AGND for loop phase compensation; it is led out from the BIAS node through R2=100 kΩ to RL (earlobe bias electrode).
[0068] SRB Selection: Reserve R9=0 Ω solder joint as a short-circuit switch, and choose between SRB ↔ PGND (solder only one of them) to switch the negative terminal reference of the channel as the SRB bus or the in-board ground.
[0069] c) Interface and Clock: SPI (SCLK / MISO / MOSI / CS) connects to the MCU; control pins include DRDY, START, and PWDN / RESET. The clock uses a built-in or 2.048 / 4.096 MHz external crystal oscillator. d) Power Supply: USB wired configuration: USB 5V → EMI / TVS → V_SYS5 → derived analog ±5V and digital 3.3V; AGND / DGND star connection. Wireless / battery configuration: Lithium battery 3.7V (V_RAW) + protection → TPS63070 buck-boost → V_SYS5 → derived ±5V and 3.3V; grounding and isolation are the same as above.
[0070] In this embodiment, the MCU driver and communication are as follows: Interface and timing: The MCU communicates with the ADS1299 via SPI (Mode1, approximately 1 MHz), and data retrieval is triggered by the falling edge of DRDY; the control pins include START and PWDN / RESET; data is output to the host computer via USB-CDC.
[0071] Power-on configuration: RESET → WAKEUP → SDATAC, writing the following typical registers: CONFIG1=0xD5, CONFIG2=0xC0, CONFIG3=0xEC, CH1–CH8=0x00, BIAS_SENSP=0x0F, BIAS_SENSN=0x00; enable SRB1 as needed. Then START → RDATAC to enter continuous output.
[0072] Work mode: (1) Continuous acquisition: Each time DRDY reads 27 B (STATUS + 8×24 bit), converts it into channel voltage and outputs it via serial port; (2) Lead / impedance measurement: Stop continuous reading, turn on LOFF excitation, resume acquisition and estimate according to Z = V / I; (3) Self-test: Switch internal test signals.
[0073] Mode switching always follows the principle of "stop sampling first, then modify the register, and then resume".
[0074] Data and fault tolerance: 24-bit two's complement extended and converted to full scale; frames can be ASCII lines or fixed-length binary. In case of frame loss / abnormalities, execute STOP → SDATAC → Reconfiguration → START / RDATAC for rapid recovery.
[0075] In the above embodiments, the installation and operation steps are as follows: (1) Select appropriate ear tips, insert earplugs and clamp the earlobe bias electrode; (2) Connect the USB and confirm that the virtual serial port enumeration is successful (115200 bps). (3) Open the serial port and real-time monitoring interface on the host computer to view the contact impedance and the original waveform; (4) Send '1' / '2' / '3' as needed to enter the acquisition / impedance / self-test mode; (5) Start recording and saving: The original ASCII line (CSV) and the standard container format (such as BDF / FIF, converted by the host computer) are written to disk at the same time.
[0076] In the above embodiments, the specific settings for data preprocessing (excluding sleep staging) are as follows: (1) Bandpass: 0.5–30 Hz (FIR or IIR ≤ 6th order).
[0077] (2) Power frequency suppression: 50 / 60 Hz and 2-5th harmonic notch (automatically trimmed by Nyquist).
[0078] (3) Optional: Bipolar heavy reference / ICA baseline steady state, heartbeat template regression and electromyographic energy gating.
[0079] (4) Quality inspection: short window RMS, derivative threshold jump and plateau segment detection; marking of unqualified segments or gentle interpolation.
[0080] The specific implementation of data preprocessing is as follows: Step S11 (Data Acquisition and Bipolar Reference): Using the sampling rate Eight raw EEG signals (Ch1…Ch8) were acquired at 500 Hz, and four sets of bipolar differential leads were constructed: Ch1−Ch2, Ch3−Ch4, Ch5−Ch6, and Ch7−Ch8. These four differential sequences are denoted as x[n] (column vector, input for subsequent processing).
[0081] Step S12 (Series fixed parameter filtering, zero-phase achievement): The x[n] obtained in step S11 is first subjected to bandpass FIR, and then to power frequency FIR bandstop (notch filter). The two are applied in reverse order to obtain a zero-phase output; the bandpass output is denoted as y1[n], and the bandstop output is denoted as y2[n], as follows: Step S121 (Bandpass FIR, 0.50Hz–30.00Hz): Filter length N (bp) = 501 (fixed), coefficients obtained by "ideal bandpass × Hamming window", linear phase. Operations on x[n] yield y1[n], the transfer function and difference equation are:
[0082]
[0083] Coefficient generation: Set a central index Angular frequency ω1=2π·0.50 / f s ω2=2π·30.00 / f s .
[0084] When n≠M: ; When n = M: ; Haiming Window ;final .
[0085] Step S122 (Power frequency FIR bandstop, center 50 Hz, bandwidth ≈ 2 Hz): Power frequency suppression is applied to y1[n], and the filter length is... N (notch) = 251 (fixed), zero phase. Writing the ideal bandstop as "unit impulse - narrow bandpass", we obtain the coefficient c. n ; Perform operations on y1[n] to obtain y2[n]. Let Central Index : When n≠M′: When n = M′: ; ; Haiming Window w′[n] Same as above, ; .
[0086] Step S13 (Fixed Delay and Real-Time Release): Apply "Fixed Delay + Central Stable Region Output" to the y2[n] obtained in step S122 to eliminate the zero-phase edge effect.
[0087] (1) Series equivalent length Point; Total edge duration .
[0088] (2) Set a fixed delay τ = 1.5 s. The processing window length for each operation is... L Take 2.0 seconds as the stable time period (frame length) for publication. F Take 0.5 s, step size H Take 0.25 s (50% overlap). Ensure... (Right now ).
[0089] (3) Implementation method: The most recent L seconds of data is taken by the ring buffer to complete the forward and backward zero phase processing of "bandpass → bandstop", and only the middle F seconds are output to the visualization; the display time is uniformly drawn according to "current time − τ".
[0090] Step S14 (High-amplitude artifact annotation and mild repair): Quality control is performed on the stable segments published in Step S13. The peak threshold is 100 microvolts, and the shortest duration is 0.01 s. The annotated segments are set as missing and repaired by linear interpolation in the corresponding channels. The boundaries are filled "backward → forward" in sequence to obtain the purified EEG sequence and its annotated intervals for subsequent staging.
[0091] Fixed Parameter Table: Sampling Rate f s =500 Hz; Differential leads: Ch1−Ch2, Ch3−Ch4, Ch5−Ch6, Ch7−Ch8; Bandpass FIR: 0.50–12.00 Hz, N bp =501; Power frequency FIR bandstop: 50 Hz, bandwidth ≈ 2 Hz, N notch =251; Series equivalent length N eq =751; Fixed delay τ = 1.5 s; Processing window L = 2.0 s; Frame length F = 0.5 s; Step size H = 0.25 s; Artifact threshold 100 microvolts, minimum 0.01 s.
[0092] In the above embodiments, the parameter range and key process points are as follows: SPI frequency 0.5–4 MHz; sampling rate 250 / 500 SPS; serial port ≥115200 bps (recommended ≥1Mbps); Input ESD / EMI: TVS is used for both USB and electrode interfaces; single-point connection for analog / digital ground; partial shielding inside the housing; Production quality inspection: Automatic lead-in and micro-motion evaluation (derivative threshold + RMS window) 30 seconds after power-on; prompt for re-lead-in if unqualified; save self-inspection log.
[0093] Example 4 This embodiment provides a specific implementation of a USB isolated wired acquisition device (baseline solution): The data acquisition system features impedance self-testing, internal calibration, host computer sleep phases, and data integrity assurance.
[0094] Circuit connections and components: Electrode / interface: ear canal P / N differential + earlobe bias / reference; three-core shielded cable; port parallel TVS (IEC 61000-4-2 8 kV contact).
[0095] Front end and A / D: 8-channel A / D (ADS1299 or equivalent) INxP / INxN series 2 kΩ, each 100 nF to ground (first-order RC, fc≈100 Hz, R / C can be finely adjusted in the range of 50–150 Hz); BIAS_OUT → 100 kΩ → earlobe bias; BIAS_INV with 1 MΩ / / 1 nF compensation; SRB is buffered by OPA376, and INxN can switch SRB / PGND (jump cap / electronic switch).
[0096] Interface and clock: SPI (SCLK / MISO / MOSI / CS), control pins include DRDY, START, PWDN / RESET; internal clock or 2.048 / 4.096 MHz external crystal.
[0097] PCB / EMC: Four-layer board; analog / digital partitioning, single-point star grounding; sensitive differential pins of equal length and ≥10 mm away from clock / USB; single-point grounding with metal shielding shell.
[0098] Power supply and isolation (direct USB power; does not use RAW / TPS63070 / DVDD LDO) V_USB5 → EMI / TVS → Isolator (e.g., ADuM4160) → V_SYS5; AVDD / AVSS (±5 V): V_SYS5 → (magnetic bead / 10 Ω + 10 µF / / 2.2 µF / / 100 nF) → AVDD; V_SYS5 → TPS60401 inverting → −5_raw → (magnetic bead / 10 Ω + 10 µF / / 100 nF / / 10 nF) → AVSS; Ground: AGND / DGND star connection on the isolation side; single-point grounding at the shielding plate end.
[0099] Note: The external MCU only supplies 5V to this board; this board does not supply 3.3V / 5V back to the external MCU.
[0100] Power-on and firmware timing (running on an external MCU): Power-on sequence: Detect DVDD_3V3 → AVDD / AVSS stabilize → Release ADS1299 RESET; Initialization: WAKEUP → SDATAC → Write register (SPS=250 / 500, PGA×12 / ×24, SRB / BIAS / LOFF, internal clock) → START → RDATAC; Data acquisition: DMA read 27 bytes (STATUS + 8 × 24 bits) triggered by the falling edge of DRDY, append timestamp (4 bytes) + sequence number (1 byte) + CRC-16 (2 bytes), and transmit at ≥1 Mbps; Fault tolerance: Frame loss / CRC / DRDY timeout (>2 × cycle) → STOP → Reconfiguration → Recovery; Watchdog timeout 2 s.
[0101] Host computer preprocessing and sleep staging (model and parameters) Preprocessing: Bandpass 0.5–30 Hz (FIR, firwin; expandable to 0.5–45 Hz), power frequency / harmonic notch filtering (50 / 60 / 100 / 120 Hz, Q=25–35), heavy reference (CAR / SRB), optional ICA; Windowing and quality inspection: 30 seconds per window (N=30×f) s ), remove windows containing NaN / Inf and σ<1e-6 or>1e4; Data augmentation: {N1×4, Wake×2, REM×2}; linear interpolation with noise (noise_level=0.01) for similar data ≥2, and temporal smoothing (window 3). Model: CNN (Conv1D×3, kernel=5, stride=2, padding=2, C→64→64→64) + population encoding (20 centers per dimension, σ=0.5, total 1280 dimensions) + LIF reservoir (n_res=512, τ=0.02s, θ=1.0, WinXavier, Wrec orthogonal and spectral radius 0.9) + classifier (64→32→5, BN+ReLU+Dropout=0.5); Training / Inference: Hierarchical partitioning; Adam + cross-entropy; online inference with a 30-second window / 5-second step, and smooth backoff at low confidence levels; Outputs: overnight hypnogram, phase statistics, K-complex / Spindle event axis, PDF report.
[0102] Acceptance criteria (±5 V shape) Noise floor (short circuit): ≤1 µV_rms@0.5–30 Hz; Power frequency rejection (no / with BIAS): ≥65 / ≥80 dB; Crosstalk <−80 dB@10 Hz; Packet error rate <10% in 8 hours 6 AVDD / AVSS ripple <1 mV_rms; ESD contact ±8 kV; casing temperature rise <10 ℃.
[0103] Example 5 This embodiment provides a specific implementation of a battery + wireless acquisition earbud (BLE / ESP32): Objective: To eliminate PC ground loops, enable all-night data collection, and phase sleep cycles for edge / host computers.
[0104] Circuitry and power supply (battery form) Battery: Single-cell lithium battery with 3.7 V+ protection; MCP73831 wired charger (200–500 mA); Step-up / step-down: V_RAW → TPS63070 → V_SYS5=5.0 V; AVDD / AVSS (±5 V): Derived from V_SYS5 (AVDD via ferrite bead, AVSS via TPS60401+ferrite bead); DVDD_3V3: V_SYS5→LDO3V3→3.3 V, supplying the digital domain of this board and ESP32; Low power consumption: MCU deep sleep (STOP2), DRDY / RTC wake-up; ESP32 intermittent broadcast + keep-alive (~300 ms); OLED / backlight off screen; target ≤200 mW, 500 mAh ≥20 h.
[0105] Wireless link and fault-tolerant packetization: timestamp + sequence number + CRC-16; 16 frames / packet; ACK / NAK ≤ 3 times; Time base correction: linear interpolation based on timestamps / packet loss interpolation to maintain timing of 250 / 500 SPS, etc.
[0106] Wearing Quality Control (Startup Guide) Display impedance bars (left / right / channel); >threshold prompts for re-wearing; after passing, proceed to acquisition; frame header carries wearing status bit (OK / loose / fall off).
[0107] Preprocessing and sleep staging (Raspberry Pi / PC inference; ESP32 can upload features) Preprocessing / enhancement / quality control: Same as Example 3; Model: Same as the previous example, supporting INT8 dynamic quantization to reduce edge load; Online inference: 30-second window / 5-second step, total latency <1 second; disconnection caching and breakpoint resumption.
[0108] Battery life and stability: Stable inference throughout the night with no system crashes; packet loss <0.1%; warnings for battery >20%; reports are automatically packaged and uploaded.
[0109] In this embodiment, the implementation of the host computer preprocessing and sleep staging algorithm is as follows: Input: Multi-channel EEG (250 / 500 SPS), with quality control / impedance / event flags.
[0110] Preprocessing: Bandpass: 0.5–30 Hz, FIR linear phase (Kaiser window, stopband >40 dB); Power frequency notch filtering: 50 / 60 / 100 / 120 Hz (second-order IIR cascade, Q=25–35); Heavy reference: bipolar or average reference (SRB / PGND adaptive). Artifact suppression: ECG: Template subtraction (R-peak derivative threshold + adaptive window); Electromyography: >30 Hz energy gating; Body motion: Acceleration threshold linkage shielding; Quality rating: SNR, power frequency margin, short-time amplitude stability → 0–1 grade, low quality segment weighting / re-sampling reminder.
[0111] Features and Models: Features (per 30 s): Δ / θ / α / β energy and ratio, spectral centroid, approximate entropy, K-complex / Spindle density, slow wave proportion; Model: CNN (Conv1D×3, kernel=5, stride=2, padding=2) + population encoding (20 / dimensional, σ=0.5, 1280 dimensions) + LIF reservoir (n_res=512, τ=0.02 s, θ=1.0, Wrec spectral radius 0.9) + classifier (64→32→5, BN+ReLU+Dropout=0.5); Data augmentation: {N1×4, Wake×2, REM×2}, k_neighbors=5 (paired reference, actual interpolation of 2 samples), noise_level=0.01, temporal_smoothing=True (window 3).
[0112] Training and Assessment: Splitting: StratifiedShuffleSplit; Batch size 64; Adam, initial lr 3e-4, Cosine annealing; Metrics: Overall accuracy, κ statistics; Minority class reporting macro average F1; Quantization (optional): INT8 dynamic quantization facilitates inference at the edge.
[0113] Online inference for operation and stability: 30 s window / 5 s step, total latency <1 s; Anomalies: Low-confidence three-point smoothing; automatic compensation for I / O frame drops; continuous low-quality triggering of the "LOW-QUALITY" flag.
[0114] Output report: Sleep structure, efficiency, wakefulness index, K-complex / Spindle density and timeline (PDF / CSV); Log: Sample quality statistics, model version and parameter snapshots: Model B (SNN, optional): IF neurons + spike readout layer, event-driven to reduce power consumption.
[0115] Alternatively, the following methods can be used to match the driver code: Basic registers: CONFIG1=0xD5, CONFIG2=0xC0, CONFIG3=0xEC, CHnSET=0x00 (working) / 0x05 (internal test), BIAS_SENSP=0x0F, BIAS_SENSN=0x00, SRB1 enabled, LOFF=0x0A, LOFF_SENSP=0xFF, LOFF_SENSN=0xFF.
[0116] Execution sequence: RESET→WAKEUP→SDATAC→Write register→START→RDATAC; DRDY interrupt fetches 27 B frames; Serial port prints "Channel:x1..x8".
[0117] Calculation and conversion: 24-bit sign complement → convert to volts according to the reference and gain → applyOffset() to correct the channel offset.
[0118] Example 6 This embodiment provides a specific implementation method for a sleep staging unit: (1) Deployment and Interface Deployment Platform: Host computer (Raspberry Pi / PC). Input is digital EEG stream transmitted from the acquisition board via USB / wireless; output is 30-second phased tags and reports. Data format: EDF / BDF / FIF, etc.; tag file MAT / CSV.
[0119] (2) Channel Selection and Loading: mne.io.read_raw_edf reads the raw EEG and extracts the sampling rate fs. It retains the EEG channel set and filters out channels containing... Event / ECG / EOG / EMG The non-EEG channel.
[0120] (3) Signal preprocessing (i.e. 7.4) (4) Sample construction and quality control windowing: 30 s / window, number of sample points N = 30 × f s ; Quality threshold: Window containing NaN / Inf is excluded; standard deviation σ < 1 × 10⁻ 6 Or σ>1×10 4The window is marked as abnormal and discarded; Tag mapping: {NREM1:0, NREM2:1, NREM3:2, Wake:3, REM:4}.
[0121] Time-aware data augmentation (class balance) strategy: {0:×4, 3:×2, 4:×2}; after augmentation, each class does not exceed 60% of the original largest class.
[0122] Method: When there are ≥ 2 samples of the same type, randomly select 2 windows for linear interpolation s = α·s1 + (1−α)·s2, α ~ U(0,1); when there are less than 2 windows, only noise is added (noise intensity = 0.01 of the sample std).
[0123] Smoothing: Enable time smoothing (Window 3).
[0124] Dataset encapsulation and normalization: Normalization: Calculate global_mean / global_std along the (sample × time) dimension; if std < 1e−6, set it to 1.0 to avoid division by zero; Returns: an EEG tensor of shape (n_ch, N), a label tensor, and a sample index.
[0125] Model structure (CNN → Population encoding → LIF reservoir → Classifier) CNN: 3 layers of 1D convolutions (kernel=5, stride=2, padding=2), channels C → 64 → 64 → 64, each layer followed by BN+ReLU; time step reduced to 1 / 8; population encoding: tanh compression of 64-dimensional features and mapping to [−3, 3], 20 Gaussian centers per dimension (σ = 0.5), concatenated to obtain 1280 dimensions; LIF reservoir: input 1280, scale n_res (e.g., 512), τ = 0.02 s (converted stride τ·f) s Threshold 1.0; W inc Initialized using Xavier, W rec Orthogonalize and scale the spectral radius to 0.9; output pulse count; Classifier: 64 → 32 → 5, fully connected + BN + ReLU + Dropout (0.5).
[0126] (8) Training and reasoning split: StratifiedShuffleSplit maintains the category ratio; Optimizations: Freeze the reservoir, train only the CNN and classifier; Adam + cross-entropy; Inference: Output window by window in 30-second increments, with a 3-point smooth backoff for low confidence levels.
[0127] (9) Output and Reporting Generate overnight hyponograms, stage statistics, K-complex / Spindle event axes, and PDF reports; highlight low-quality segments.
[0128] Example 7 This embodiment provides an online sleep-staged inference implementation between the edge and the FPGA: This embodiment, without changing the network structure and parameter file format trained in Embodiments 5 / 6, provides an online inference implementation of "CNN feature extraction (corresponding to S324) → population encoding (corresponding to S325) → LIF pulse reservoir (corresponding to S326) → classifier readout (corresponding to S333)" on edge hardware (ARM / x86, with optional NPU support) and FPGA accelerated hardware. The acquisition and real-time preprocessing of the input signal follow the processing chain of S11–S14 in Embodiment 1, and maintain the same window / step size / fixed delay configuration to ensure training-deployment consistency.
[0129] I. System Composition and Deployment (Continuing from the data acquisition and preprocessing in Example 4) (1) Data processing and computing unit (edge): Based on an embedded SoC (such as an ARM64 quad-core, memory ≥4 GB) or an industrial PC (x86) as the hardware platform, it runs a lightweight inference service; an external 8–16 TOPS NPU can be optionally connected as a CNN front-end acceleration. Publicly available patents have described wearable / portable devices performing stage labeling on data segmented by time window locally, and can choose to do so locally or in collaboration with a terminal / server depending on the scenario, which is consistent with the edge-side path of this embodiment.
[0130] (2) Acceleration hardware (optional): FPGA board (resource size ≥200 k LUT, external DDR ≥1 GB) is used to accelerate batch vector operations of convolution 1D and RBF population encoding in parallel, and can carry some linear layers; the common practice is to matrix the convolution (im2col / GEMM), cascade each layer with AXI4-Stream, and move the weights to the on-chip cache as needed from external memory. This has been publicly demonstrated in the EEG real-time classification / detection scenario and is suitable as a hardware reference for this embodiment.
[0131] (3) Acquisition and communication: The signal acquisition end outputs a zero-phase stable segment (0.5–45Hz, with artifact mild repair) consistent with S11–S14, which is transmitted to the edge end via wired or BLE / Wi-Fi; the edge end completes online phasing and periodically reports the stage tag and confidence level. This "end-side windowing → feature / classification → window output" mode is consistent with the description of the wearable phasing patent.
[0132] (4) End-to-end collaboration (optional): After training is completed on the host computer / server, the parameter package is ported to a lightweight terminal (mobile phone / Raspberry Pi / wearable SoC) for local operation; only the stage results and quality indicators are reported instead of the original stream, which is a common path of existing edge computing / device-side inference and can be seamlessly connected with this embodiment.
[0133] II. Model and File Organization (Continuing from the training output of Examples 5 / 6) The same parameter package exported from offline training is loaded at the edge, and the file organization and naming remain unchanged to facilitate consistent verification with the PC side: (a) CNN front end (S324): three-layer 1D convolution (kernel=5, stride=2, padding=2, channels 64→64→64), including BN / activation inference parameters; (b) Population encoding (S325): configuration of 20 center positions per feature dimension and kernel width σ; (c) LIF reservoir (S326): input matrix W in Circular matrix W rec (The training side has been frozen and spectral radius scaling has been performed), threshold and time constant and other operating hyperparameters; only the trainable reservoir computing structure has a publicly available system description, which can serve as the theoretical support for edge deployment; (d) Classifier and post-processing (S333): two fully connected layers / BN / Dropout, output layer weights and temporal smoothing strategy; (e) Data normalization statistics: global mean / variance; (f) Deployment metadata: operator compatibility list, quantization / fixed-point configuration (to facilitate consistent FPGA operation).
[0134] III. Online Inference Workflow (Edge End, Reusing the Window / Delay Conventions of S11–S14) Real-time phasing is performed on a sliding window, with the window length and step size following the training settings (e.g., 30 s / 10 s; if used for visualization frames, then 2.0 s / 0.25 s is only for display); each step corresponds one-to-one with the aforementioned number: (1) Reception and buffering (aligned S11–S14): A circular buffer extracts a frame according to the set window length, performs cascaded bandpass / notch zero-phase processing and outputs only the stable segment, and adds a fixed delay consistent with Example 1; this type of end-side process marked by time window (epoch) has been detailed in the wearable phasing patent. (2) CNN feature extraction (S324): The input is a tensor of “channel × time”, three layers of convolution + BN + activation downsampling to 64×L′; if equipped with an NPU, only the convolution / fully connected layers are offloaded to the NPU, and the remaining modules remain on the CPU. (3) Population Encoding (S325): Calculate the Gaussian response relative to 20 centers for each time step of the 64-dimensional continuous features and concatenate them into a 1280-dimensional representation; this step belongs to the sample-by-sample independent vectorized calculation, which can be directly implemented in parallel on NPU / FPGA. (4) LIF Pulse Reservoir (S326): Update the membrane potential and count the releases step by step with the 1280-dimensional input; the reservoir weights are kept frozen, and only the trainable hardware-friendly implementation and end-side inference are read out, which have been publicly described in the reservoir computing system patent. (5) Classifier and Output (S333): Feed the release count into two fully connected layers to obtain 5 classes of logits, output the stage and confidence after softmax; combine the previous frame to perform 3-frame temporal smoothing and write to shared memory / report to UI. Outputting stage labels and probability distributions according to the window belongs to the publicly disclosed device-side implementation paradigm.
[0135] IV. Latency and Resource Constraints (Matching Frame Configuration with Example 4) On an edge platform with ARM64 (≥2.0 GHz, 4 cores) + optional NPU, using the same 30 s window, fixed latency, and stride as training: — CNN front-end: NPU inference <10 ms / frame (mainly convolution / FC); — Population encoding: SIMD or NPU scalar kernel <3 ms / frame (sample-by-sample vectorization, or can be implemented on FPGA using LUT / fixed-point multiply-accumulate); — LIF reservoir (512–1024 nodes): CPU + NEON or NPU small matrix kernel 5–10 ms / frame (weights frozen, read-only); — Classification head: <1 ms / frame; — End-to-end (including preprocessing and smoothing): typically ≤ 30 ms / frame, which can meet the requirements of online staging display with a stride of 0.25–0.5 s; If FPGA is used to parallelize convolution and encoding, the single-frame latency can be further reduced without changing S324–S333. Module boundaries and parameter semantics.
[0136] This invention constructs a complete closed-loop system comprising in-ear dry electrode data acquisition, digital processing, and upper-level timing classification. The system is compact, comfortable to wear, and possesses excellent anti-interference capabilities. Optional implementation methods include: replacing the wireless modulation mode to support long-distance communication; replacing the processing platform to improve processing flexibility; and supporting dual-channel synchronous acquisition to expand data analysis capabilities. Compared to traditional PSG or head-mounted device-based models, this solution significantly improves the response speed and prediction accuracy of sleep staging.
[0137] The above embodiments are preferred embodiments of the present invention, but the embodiments of the present invention are not limited to the embodiments described above. Any changes, modifications, substitutions, combinations, or simplifications made without departing from the spirit and principle of the present invention shall be considered equivalent substitutions and shall be included within the protection scope of the present invention.
Claims
1. A portable electroencephalogram sleep detection analysis system, characterized in that, The application relates to a sleep stage classification method and device based on an ear EEG acquisition unit, a data processing and calculation unit and a sleep stage classification unit. The ear EEG acquisition unit comprises: an acquisition module comprising an earplug suitable for being placed in an ear canal and at least two dry electrodes embedded on the surface of the earplug for acquiring differential EEG signals in the ear canal; a signal processing and transmission module electrically connected with the acquisition module for filtering, amplifying and analog-digital converting the acquired analog EEG signals and outputting a digital data stream.
2. The portable electroencephalic sleep detection and analysis system of claim 1, wherein, The data processing and calculation unit is configured to perform a preprocessing operation on the digital data stream, and the preprocessing operation comprises: frequency domain filtering to extract EEG signals in a target frequency band; power frequency interference suppression; 3. The portable electroencephalic sleep detection and analysis system of claim 1, wherein, motion artifact separation and removal. The sleep stage classification unit comprises: a data processing module for ensuring data validity through quality inspection, segmenting continuous signals into 30-second standard sleep stage time windows, then performing T-SMOTE data enhancement, and then performing data standardization based on global mean and standard deviation, batch loading and sample index tracking; a feature extraction module for extracting local spatiotemporal features of the input EEG signal sequence; 4. The portable electroencephalic sleep detection and analysis system of claim 1, wherein, a population coding module connected to the feature extraction module for converting the extracted continuous features into high-dimensional distributed population coding features; a spiking neural network reservoir module connected to the population coding module for dynamically capturing time series information in the population coding features through neuron spiking and converting the dynamic spiking sequence into a static feature vector; a classifier module connected to the spiking neural network reservoir module for generating classification probabilities of multiple sleep stages according to the static feature vector. The application further relates to a sleep stage classification device based on an ear EEG acquisition unit, a data processing and calculation unit and a sleep stage classification unit. The sleep stage classification comprises the following steps: data processing: ensuring data validity through quality inspection, segmenting continuous signals into 30-second standard sleep stage time windows, then performing T-SMOTE data enhancement, and then performing data standardization based on global mean and standard deviation, batch loading and sample index tracking; 5. A portable electroencephalogram sleep detection analysis method, characterized in that, feature extraction: extracting local spatiotemporal features of the input EEG signal sequence; population coding processing: converting the extracted continuous features into high-dimensional distributed population coding features; spiking neural network reservoir processing: dynamically capturing time series information in the population coding features through neuron spiking and converting the dynamic spiking sequence into a static feature vector; classification processing: generating classification probabilities of multiple sleep stages according to the static feature vector.
6. The portable electroencephalic sleep detection analysis method of claim 5, wherein, 7. The portable electroencephalic sleep detection and analysis method of claim 6, wherein, In the data processing step, the T-SMOTE data enhancement is specifically: time interpolation is performed on the same class samples, Gaussian noise is added, and time smoothing is performed to generate synthetic samples, and the distribution of the data set is dynamically balanced.
8. The portable electroencephalic sleep detection and analysis method of claim 7, wherein, In the data processing step, the time interpolation performed on the same class samples is specifically: Under the premise of maintaining the time structure of each sample, the pre-processed labeled training samples are subjected to the set oversampling and amplitude disturbance enhancement according to the category, and the sample quantity of each sleep stage after enhancement is limited to not more than the preset proportion of the maximum category sample quantity, so that the class imbalance is alleviated without destroying the time consistency. 9.A computer readable storage medium having stored thereon a computer program, which, when executed by a processor, implements the steps of the portable electroencephalogram sleep detection and analysis method according to any one of claims 5-8.
10. A computer program product comprising a computer program, characterized in that, The computer program, when executed by a processor, implements the steps of the portable electroencephalogram sleep detection and analysis method according to any one of claims 5-8.
Citation Information
Patent Citations
Automatic sleep staging method of single-lead electroencephalogram
CN107495962A
In-ear type electroencephalogram acquisition processing system
CN109745043A
Single-channel ear electroencephalogram automatic sleep staging method based on deep transfer learning
CN113303814A
Sleep type classification method and device based on spiking neural network
CN115429293A
Method and system for monitoring and evaluating sleep quality
CN119498778A
Cited By
Sleep stage detection method and device, electronic equipment and storage medium
CN122132931A