A Smart Detection Method of Sleep Quality Using EEG Signal and Long Short-Term Memory Model

Sleep is the most important physiological process related to human health. The development of society has accelerated the pace of people’s lives and has also increased people’s life pressure. As a result, more and more people suffer from reduced sleep quality, and the resulting diseases are also increasing. In response to this problem, this study proposes a sleep quality detection and management method based on electroencephalogram (EEG). The detection of sleep quality is mainly achieved by staging sleep EEG signals. First, wavelet packet decomposition (WPD) preprocesses the collected original EEG to extract the four rhythm waves of EEG. Second, the relative energy characteristics and nonlinear characteristics of each rhythm wave are extracted. The multisample entropy (MSE) values of different scales are calculated as the main features, and the rest are auxiliary features. Finally, the long short-term memory (LSTM) model is applied to classify the extracted sleep features, and the final result is obtained. Experiments were conducted in the MIT-BIH public database. The experimental results show that the method used in this article has a high accuracy rate for sleep quality detection. For the detected sleep quality data, the data are managed in combination with the mobile terminal software. Management is mainly embodied in two aspects. One is to query and display historical sleep quality data. The second is that when there are periodic abnormalities in the detected sleep quality data, the user will be reminded so that the user can respond in time to ensure physical fitness.


Introduction
Sleep is an indispensable physiological process in people's daily life. Every day, most people spend about 30% of their time sleeping. After a day of study and work, the body and brain are in a state of fatigue. e ability to respond to nerves and the functioning of organs slow down during sleep. Heartbeat, blood pressure, and metabolic rate decrease, and muscle tissue becomes loose. At this time, sleep is the best way to eliminate fatigue from the body [1]. Good sleep helps to improve work efficiency and mental outlook. Inferior sleep can cause endocrine disorders, increase the risk of amnesia and other diseases, and cause inattention, which affects normal working and living conditions. erefore, having good quality sleep is very important to people's lives. Studies have shown that in addition to poor physical conditions, people with insufficient sleep will age 4 to 5 times higher than those with healthy sleep. People who are affected by sleep for a long time will also decrease in intelligence, thus affecting normal life. Adequate sleep is one of the internationally recognized sleep health standards. In order to make people pay more attention to issues related to sleep quality, the International Mental Health and Neuroscience Fund in 2001 set the "World Sleep Day" as March 21, and launched a global sleep and health plan [2]. Nowadays, people all over the world have difficulty falling asleep or even insomnia. It is becoming more and more common, and there are more and more diseases derived from sleep problems. e problem of sleep quality is gradually getting people's attention, and the scientific inquiry related to sleep diseases has also received more attention from medical experts and scientists. e main indicator for judging the quality of human sleep is whether the human brain is awake or not after waking up. erefore, it is the best starting point to study sleep by studying the brain activity. EEG can accurately and quickly reflect the physiological changes of the human body; it belongs to an advanced biological signal. It provides important analytical reference information for neurology, medicine, and other disciplines. It can accurately reflect the activity of the brain, and its application in sleep research is gradually becoming common. Each person has different characteristics and amplitudes of EEG signals in different sleep states, which reflects the different and complex functions of the brain at different stages. People's sleep cycle can be roughly divided into three periods, namely, rapid eye movement (REM), nonrapid eye movement (NREM), and wake (W). According to a certain rule of classification of the characteristics of each stage, such a process is called sleep staging. If the result of sleep stage is similar to that of standard sleep classification, it means that the quality of sleep is good. Otherwise, the sleep effect is not good. e results of sleep stages can be used as the basis for judging sleep quality. erefore, the higher the accuracy of sleep staging, the more accurate the feedback of sleep quality. Sleep staging has important clinical significance and broad application prospects for the treatment of sleep disorders.
In the 1820s, the German psychiatrist Berger discovered that the brain electrical activity of a person is different in the two states of waking and sleep. Since then, the study of sleep EEG has started. In the 1860s, Dumermuth et al. used fast Fourier transform to process EEG, which promoted its development in frequency domain analysis [3]. e American Academy of Sleep Medicine (AASM) formulated the current general AASM standard, which divided the sleep process into 5 stages [4]. When experts perform artificial sleep staging according to general staging standards, they need to observe sleep signals for a long time, which is timeconsuming, heavy workload, and subjectively affected. erefore, the automatic sleep staging method was born. At present, various statistics and pattern recognition methods [5][6][7][8][9][10][11][12][13][14][15][16][17][18] have been applied to sleep staging. e existing sleep staging methods have their own advantages and disadvantages. Considering that EEG data are time series data in order to establish a sleep quality detection model with high accuracy and fast calculation speed, this research proposes a detection method with higher accuracy and timeliness. e contributions of this research are summarized as follows: (1) A more efficient sleep quality detection framework is used. e detection frame first performs denoising preprocessing and feature extraction on the raw data, inputs the extracted features into the classifier, and uses LSTM to classify sleep EEG signals. Experiments verify that the detection framework used has a higher detection accuracy for sleep quality. (2) According to the results of sleep quality testing, a sleep quality monitoring system was designed. First of all, the system can collect sleep EEG signals and store the collected raw datasets on the cloud platform. Second, the used detection framework is used as the sleep quality detection module to classify and recognize the input original sleep EEG to obtain the final recognition result. e recognition result is stored in the cloud platform. ird, terminal devices such as mobile phones and tablet computers can access the cloud platform to obtain data and display the data on the terminal application. Users can view and query data through the application.
(3) e sleep detection cloud platform used in this article can collect sleep data of multiple users. ese sleep data can provide data support for medical institutions and sleep-related enterprises. In addition to basic sleep data, the cloud platform can also collect the user's sleep quality diagnostic information. ese diagnostic information can assist related companies to develop more accurate products for users.

Introduction to EEG Signal and Sleep
Quality. e brain is mainly responsible for controlling and regulating the thinking and consciousness activities of the human body. EEG is a random signal that reflects the electrical activity of brain tissue. e cerebral cortex is the highest center of the nervous system that regulates physical movement, responsible for the cognitive and emotional functions of the brain, and is also the most important part of the brain. Various activities and sensations of the human body can find corresponding areas in the cerebral cortex, and each area has its own specific role and function. e neuronal cells of the cerebral cortex are the reason why human beings have complex activities as advanced organisms. e condition that can produce complex activities is that each neuron cell can communicate through the connection of dendrites, making human activities have countless possibilities. e birth of EEG comes from the activity of neurons in the cerebral cortex. e signals generated by the potential activity of nerve cells can be obtained by adding electrodes on the scalp to obtain an EEG. e amplitude, frequency, and phase of the waveform contained in the EEG have certain characteristics. e bandwidth of EEG is 0.5∼100 Hz, and only 0.5∼30 Hz part of spontaneous EEG is considered in clinical medicine. According to frequency characteristics, it can be divided into four basic rhythm waves and nonbasic waves. During sleep, the rhythm waves appear regularly, and the irregular waves are nonfundamental waves. Figure 1 shows the basic characteristic wave of the EEG signal.

Sleep Staging.
During sleep, the depth of sleep will cause changes in EEG. erefore, as long as the sleep EEG numbers of people in different periods are grasped, it is possible to compare whether the EEG changes of the samples to be tested follow the standard change law. If the standard change rule is not followed, the sleep quality of the sample to be tested is determined to be poor. According to this principle, it can be analyzed that to detect a person's sleep quality, it is necessary to perform a staged test of his sleep EEG. e most widely used sleep staging standard is the AASM standard, which is shown in Figure 2.
In different sleep states, EEG signals are different. e characteristics of EEG in various states are as follows: W Period. e awake period is the preparation period for sleep. At this stage, the brain is in a conscious state that responds quickly to changes in the surrounding environment. At this time α wave and β wave are the main part. e alpha wave accounts for more than 50% to judge whether it is the awake period. is period is mostly awake, accompanied by blinking and rapid eye movements, and there will be a short W period during sleep. S1 Stage.
is period is the transitional stage from waking state to sleep state. At this stage, the eyeball moves slowly and with the appearance of spikes, the external environment hardly affects the sleep state. e proportion of alpha waves fell below 50%, with low amplitude theta waves dominating. S2 Period. is period sleeps deeper than S1 period. At this stage, the amplitude of the EEG signal increases, and eye movement basically stops. Brain waves are dominated by low-amplitude and mixed-frequency spindle waves and K-complex waves, and delta waves account for less than 20%. If the duration of two consecutive spindle waves and K-complex waves is less than 3 minutes, it is judged as S2, and if the duration is longer than 3 minutes, it is judged as S1. S3 Stage. is stage is a deep sleep state, also known as slow wave sleep. Low-frequency delta waves are the main signal, accounting for more than 20%. Generally, if the peak value exceeds 75 μV, a complex wave of spindle and K may appear, but it is mainly a delta waveform. ere will be no large fluctuations in the amplitude of the brain waves, and the eyeballs and muscles will stop. REM Period. is stage is accompanied by the rapid and autonomous rotation of the eyeball. Except that the spike wave is not obvious, everything else is the same as the waveform of the S1 period. REM is a lighter sleep process, during which people who wake up are sensitive to the surroundings. e proportion during sleep will gradually decrease with age. REM sleep function is higher, and the correlation between emotion regulation and memory function is higher.

Sleep Quality Management.
Sleep quality management is mainly realized through the sleep quality management system. e architecture of the system is shown in Figure 3. First, collect the sleep EEG signal through a collector such as a worn watch, and send the collected data to a cloud platform for storage through a network such as WiFi. Second, the sleep quality detection module in the server obtains data from cloud platform and performs detection and identification to obtain sleep quality detection results. e server then sends the detection result to the cloud platform for storage.
ird, use mobile phones, tablet personal computers, and other terminals to get sleep detection results and display them on the cloud platform. Fourth, the application on the terminal can not only display sleep detection data but also query and prompt the data.
is article focuses on the design of sleep quality management application. Sleep quality management application can detect human sleep data in real time, display sleep data for a certain period of time, and give sleep quality scores. is sleep quality score is obtained using the sleep quality test method in Section 3. e user can set the score threshold on the setting interface and promptly remind the user when the sleep quality score is lower than the set threshold. After the user receives the reminder, he can adjust the mechanical energy in time for his work and rest. In addition to the above basic functions, the following functions will be added to the APP designed in this study:    (1) Hypnotic Music. When the user cannot sleep, the APP will combine sleep science and original sleep aid music to let the user fall asleep quickly. APP can intelligently recognize falling asleep and automatically stop the music after detecting that the user is asleep.

Sleep Quality Inspection
Process. e detection of sleep quality is mainly realized by automatically staging sleep EEG signals. First, WPD is used [19,20] to preprocess the collected original EEG to extract the four rhythm waves of EEG. Second, the relative energy characteristics and nonlinear characteristics of each rhythm wave are extracted, and the MSE values [21,22] of different scales are calculated as the main characteristics, and the rest are auxiliary characteristics. ird, the sleep features after dimensionality reduction are sent to the LSTM model to return the final results. Figure 4 shows the sleep quality detection process.

Preprocessing of Sleep EEG Signals.
Since the EEG signal is weak and noisy, it needs to be preprocessed. is study mainly uses wavelet threshold denoising. e wavelet threshold method is mainly divided into two types: soft threshold and hard threshold. According to the actual signal and requirements, choose one of the methods to filter out the Gaussian white noise in the noisy signal. e process of wavelet threshold denoising is shown in Figure 5. e main steps of using the wavelet threshold method to preprocess EEG signals are as follows: (1) Determine the optimal wavelet basis and the optimal decomposition layer, and iteratively select the optimal tree under the standard entropy, and then decompose the EEG signal in n layers. (2) e decomposed coefficients are processed by using an appropriate threshold function. Each level of decomposition corresponds to a threshold, and the high-frequency coefficients are also thresholded. (3) e discrete wavelet transform reconstructs the nonzero coefficient signal after processing in step (2), thus completing the threshold denoising process of EEG.

Feature Extraction of
M j represents the energy value after the signal g(t) is repurchased. j represents different rhythm waves, and i represents the number of sampling points of signal samples, i � 0, . . . , m. x i represents the amplitude corresponding to the sampling point of the reconstructed signal. e total energy expression of each characteristic wave of sleep EEG is as follows: (2) e relative energy expression is   [25,26]. e difference between LSTM and general RNN is the way to update the status in the middle. It is characterized by a time cycle structure, which can well describe the sequence data with spatiotemporal correlation, including time series data, text, events, and so on. LSTM can be simply understood as an autoregressive model based on neural network. Suppose RNN is used to predict a text. When the interval between the relevant information and the current predicted position increases, RNN will lose the ability to learn the remote information. In theory, RNN can definitely deal with the problem of "long-term dependence." One can carefully select parameters to solve the most elementary form of such problems. However, in practice, RNN will not be able to learn these knowledge successfully. Based on this background, the LSTM model was proposed. Figure 6 gives the structure of the LSTM model. In the figure, the large rounded rectangular block diagram represents a cell, the small right-angled rectangular block diagram represents a neural network layer, and the small circle represents dot multiplication. e cell state in the figure can be understood as a conveyor belt, which is the memory space of the entire model, which will change over time. e conveyor belt itself cannot control which information is memorized, but three control doors play a controlling role. e three gates are input gate, output gate, and memory gate. e core idea of the LSTM model is to replace each hidden unit in the RNN with a cell with a memory function (as shown in Figure 7), and the other structures are the same as the RNN. In Figure 7, g c represents input node, which has the same function as the RNN model. i c represents input gate, which can control the input information. s c represents internal state node, f c represents forgetting gate, and o c represents output gate.

Classification of Sleep EEG Signals. LSTM [23, 24] is a version of RNN
Several cells form an LSTM layer, and the calculation formula of the LSTM layer is as follows:

Experimental Data Analysis
e data used in this study are selected from the Sleep-EDF dataset in the MIT-BIH sleep database, which contains two files, SC and ST. e SC file contains the sleep data of 20 men and women with healthy sleep, and the ST file contains the sleep data of 22 men and women with different degrees of sleep disorders. In this study, the data of 4 subjects were selected from SC and ST for experiments. e 4 subjects with normal sleep were coded as SC01-SC04, and the 4 subjects with sleep disorders were coded as ST01-ST04. ere were 800 pieces of sleep data for each participant, totaling 6,400 pieces of data. Select the data of SC01, SC02, ST01, and ST02 as the training set, and SC03, SC04, ST03, and ST04 as the test set. e training set samples are trained many times to avoid the chance of results. In this study, the model with the best training results was selected to classify the test set samples. e experimental software is Matlab2017. Since the manually marked staging results in the database use the R&K  Mathematical Problems in Engineering staging standard, this study uses the AASM standard, so S4 is counted as S3 when the manual staging results are counted. e staging results marked by experts are shown in Table 1. Table 2 shows the results of the method proposed in this paper to perform sleep staging on the test set. e data in Table 2 show that the accuracy of sleep staging for selected normal sleep samples and sleep disorder samples is higher than 86%. e accuracy of 5 different sleep periods is different, among which the accuracy of Wake period classification is higher and the accuracy of REM period is lower. e reason may be that there are eye movements during the rapid eye movement period. e EOG signal is more obvious than the EEG signal, so this period cannot be accurately divided. Table 3 shows the results and accuracy of sleep staging for the test dataset. e experimental data in Table 3 demonstrate that the classification accuracy of the method used in this paper is lower than the training data, and the classification accuracy of the normal sleepers is not much different from the training data. e accuracy of sleep staging of the method used in this paper is slightly less than 90% and is generally between 85% and 89%. e accuracy rate in the awake period is higher, and it is lower in the REM period. e light sleep period is compared with the deep sleep period because the brain nerve activity is active in the light sleep period, and the characteristics are not obvious, and the deep sleep period enters the deep sleep stage, and the brain nerve cell activity is reduced, and the characteristics are obvious, so the classification accuracy rate of the light sleep period is less than deep sleep period.
In order to further verify the robustness of the method used in this paper, Gaussian noise with a mean value of 0 and a variance of 0.1, 0.2, 0.3, 0.4, and 0.5 was added to the abovementioned test dataset. e results of automatic sleep staging of the test samples are shown in Table 4. e experimental data in Table 4 show that with the increase in noise, the accuracy of sleep staging is gradually decreasing.
is is consistent with the theory. On the whole, the sleep staging accuracy obtained by the 4 test samples is greater than 80%. is shows that even if there is a little noise, the sleep staging method of this paper is effective and feasible.

Conclusion
is article mainly studies from two aspects of sleep quality detection and management. For the detection of sleep quality, this article proposes a method of sleep staging detection. First, WPD preprocesses the collected original EEG to extract the four rhythm waves of EEG. Second, the relative energy characteristics and nonlinear characteristics of each rhythm wave are extracted. e MSE values of different scales are calculated as the main features, and the rest are auxiliary features. Finally, the sleep features use the LSTM model for classification, and the final result is obtained. is article uses the AASM standard to stage sleep. e experimental results demonstrate that the detection efficiency of this method is above 86%, which can meet the clinical detection requirements. For the management of sleep quality, this paper develops a piece of software based on the results of sleep detection. e software is used to display the results of sleep detection and remind users in time when the detection results are abnormal. is research has good practical value, and the feasibility of this research is further explained based on the test results. However, the accuracy of sleep detection in this study needs to be further improved. Subsequent research will focus on improving the classification algorithm, hoping to increase the classification accuracy to more than 90%. e sleep quality detection method based on EEG signal in this paper has been verified and can be applied in real life. Because sleep is an extremely complex process, it is difficult to achieve high accuracy in sleep staging. erefore, this study can also consider the influence of other physiological parameters. As the sleep process is very complicated, physiological parameters such as ECG, EMG, EOG, and respiration have a certain influence on sleep. More physiological parameters should be introduced to study the sleep state to improve the accuracy of sleep quality detection.

Data Availability
e labeled dataset used to support the findings of this study are available from the corresponding author upon request.

Conflicts of Interest
e authors declare that they have no conflicts of interest. Mathematical Problems in Engineering 7