[Project] Sleep state detection based on matlab HMM algorithm [Contains Matlab source code 610]

1. Introduction

Hidden Markov model (Hidden Markov model, HMM) is a dynamic Bayesian network generation model with the simplest structure, and it is also a well-known directed graph model. It is a typical statistical machine learning model for processing labeling in natural language. This article will focus on this classic machine learning model.
1 Introduction

Suppose there are three different dice (6 sides, 4 sides, 8 sides), each time you choose one of the three dice, the probability of each dice being selected is 1/3, as shown in the figure below, repeat the above process to get one String value [1,6,3,5,2,7]. These observable variables form a chain of observable states. At the same time, there is a hidden state chain composed of hidden variables in the hidden Markov model, in this case the sequence of dice. For example, the sequence to get this string of digital dice may be [D6, D8, D8, D6, D4, D8].
Insert picture description here
The Hidden Markov-type schematic diagram is as follows: In the
Insert picture description here
figure, the arrows indicate the dependencies between variables. The description of each arrow in the figure is as follows:
Insert picture description here
at any time, the observed variable (die) only depends on the state variable (what kind of die), and the state qt at time t depends only on the state qt-1 at time t-1. This is the Markov chain, that is, the next moment of the system is determined only by the current state (no memory), that is, the "homogeneous Markov hypothesis".
2 Definition of the hidden Markov model
According to the above example, here is a hidden Markov model. Definition of Kofu. Hidden Markov model is a probabilistic model about time series. It describes the process of randomly generating an unobservable random sequence of unobservable states from a hidden Markov chain, and then generating an observable random sequence from each state. The hidden Markov chain The randomly generated state sequence is called the state sequence (that is, D6, D8, etc. in the above example); each state generates an observation, and the resulting random sequence of observations is called the observation sequence (that is, the observation sequence in the above example). 1, 6, etc.). Each position in the sequence can be regarded as a moment.

The hidden Markov model is determined by the initial probability distribution, state transition probability distribution, and observation probability distribution. The specific form is as follows, where Q is the set of all possible states, and V is the set of all possible observations, namely:
Insert picture description here
Insert picture description here
Insert picture description here
3
Insert picture description here
Insert picture description here
For the initial step of the forward algorithm , it is the state i1 = q1 at the initial moment and the observation o1 Joint probability. Step (2) is the recursive formula of the forward probability, calculating the forward probability that the partial observation sequence at time t+1 is o1, o2,...,ot,ot+1 and is in the state qi at time t+1. As shown in the figure above, since at(j) is the forward probability of qj when o1, o2,...,ot is observed at time t and is in the state at time t, then at(j)aji is to observe o1, o2 at time t ,...,Ot is the joint probability of being in the qj state at time t and reaching the qi state at time t+1. The sum of all possible N states of this product at time t, the result is the joint probability of the observations as o1, o2,...,ot at time t and the state qi at time t+1. Finally, the third step is to calculate the result of P(O|lamda).

Of course, here is only one of many algorithms, and the similar is the backward algorithm (you can read related books for understanding). For dynamic programming to solve the hidden Markov model prediction problem, the most widely used is the Viterbi algorithm.

Second, the source code

function varargout = SleepStatus(varargin)
% SLEEPSTATUS MATLAB code for SleepStatus.fig
%      SLEEPSTATUS, by itself, creates a new SLEEPSTATUS or raises the existing
%      singleton*.
%
%      H = SLEEPSTATUS returns the handle to a new SLEEPSTATUS or the handle to
%      the existing singleton*.
%
%      SLEEPSTATUS('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SLEEPSTATUS.M with the given input arguments.
%
%      SLEEPSTATUS('Property','Value',...) creates a new SLEEPSTATUS or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before SleepStatus_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to SleepStatus_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help SleepStatus

% Last Modified by GUIDE v2.5 21-Oct-2020 17:16:55

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @SleepStatus_OpeningFcn, ...
                   'gui_OutputFcn',  @SleepStatus_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{
    
    1})
    gui_State.gui_Callback = str2func(varargin{
    
    1});
end

if nargout
    [varargout{
    
    1:nargout}] = gui_mainfcn(gui_State, varargin{
    
    :});
else
    gui_mainfcn(gui_State, varargin{
    
    :});
end
% End initialization code - DO NOT EDIT


% --- Executes just before SleepStatus is made visible.
function SleepStatus_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to SleepStatus (see VARARGIN)

% Choose default command line output for SleepStatus
handles.output = hObject;

set(handles.text2,'string','Sleep status detector','foregroundcolor','b','fontsize',20);

set(handles.pushbutton1,'String','打开文件');
set(handles.pushbutton2,'String','播放且判断');
set(handles.pushbutton3,'String','停止');

set(handles.edit1,'String','实时判断结果');
set(handles.edit2,'String','过往判断结果');
set(handles.edit2,'Max',10);
set(handles.edit2,'Min',0);

cla(handles.axes1);
cla(handles.axes2);

global player timer_counter accurate_time n_last n_last1 all_result num
player=[];
timer_counter =0;
accurate_time = 0;
n_last =2;
n_last1 =2;
num =1;
all_result={
    
    };
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes SleepStatus wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = SleepStatus_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{
    
    1} = handles.output;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global wavfilename timer_counter all_result num
[FileName,PathName] = uigetfile('*.wav','Select the wav-file');
if FileName==0 
    wavfilename =[];
    return
end
wavfilename = [PathName,FileName];
[x,fs] = audioread(wavfilename);
x = mean(x,2);
axes(handles.axes1);
plot(x);
ylim([-1 1]);
timer_counter = 0;
accurate_time  =0;
all_result={
    
    };
set(handles.edit2,'string','');
num = 1;

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global wavfilename tAxis player myStruct start_minute start_seconds
if isempty(wavfilename)
    return
end
%default

durT = 30*60; %seconds
fs = 32000;
durS = fs*durT; %samples

[x,fs] = audioread(wavfilename);
x = mean(x,2);
durT = size(x,1)/fs;
durS = size(x,1);

dt = 1/fs;
tAxis = dt:dt:durT;

frameRate = 25; %fps
frameT = 1/frameRate;

mag = 1;

axes(handles.axes1);
cla(handles.axes1);
plot(tAxis, x);
ylim([-mag mag])
xlim([0 durT])
xlabel('Time [s]')

playHeadLoc = 0;
% hold on; 
ax = plot([0 playHeadLoc], [-mag mag], 'r', 'LineWidth', 2);

player = audioplayer(x, fs);
myStruct.playHeadLoc = playHeadLoc;
myStruct.frameT = frameT;
myStruct.ax1 = handles.axes1;
myStruct.ax2 = handles.axes2;
myStruct.edit1 = handles.edit1;
myStruct.edit2 = handles.edit2;
tmr1 = timer('ExecutionMode', 'FixedRate', ...
    'Period', 0.5, ...
    'TimerFcn', {
    
    @timerCallback});
% tmr2 = timer('ExecutionMode', 'FixedRate', ...
%     'Period', 0.1, ...
%     'TimerFcn', {
    
    @timerCallback2});
handles.timer1 = tmr1;
% handles.timer2 = tmr2;

guidata(hObject, handles);

start_time = clock();
start_seconds = start_time(6);
start_minute = start_time(5);

start(tmr1);
% start(tmr2);

playblocking(player);
% play(player);
if ~isplaying(player)   
    stop(handles.timer1);
%     stop(handles.timer2);
end

% function timerCallback2(hObj, eventdata)
%     global accurate_time
%     accurate_time = accurate_time + 0.1;


function timerCallback(hObj, eventdata)
 global wavfilename myStruct tAxis timer_counter accurate_time start_minute start_seconds n_last n_last1 all_result num
[x1,fs] = audioread(wavfilename);
x1= mean(x1,2);
length_max = length(x1);

% timer_counter = accurate_time;

start_time = clock();
seconds = start_time(6);
minute = start_time(5);

timer_counter = (minute*60+seconds)-(start_minute*60+start_seconds);
% disp(timer_counter)
axes(myStruct.ax1);
plot(tAxis,x1);
line([timer_counter timer_counter],[-1 1],'color','r');

axis([tAxis(1) tAxis(end)  -1 1]);

time1 = timer_counter;
time2 = time1 + 1;%1s

idx1 = fix(fs*time1);
idx2 = fix(fs*time2);
if (idx1<1)
    idx1 = 1;
end
if(idx1>=length_max)
    idx1 = length_max;
end
if(idx2>=length_max)
    idx2 = length_max;
end
if(idx1>=idx2)
    return
end

Three, running results

Insert picture description here
Insert picture description here
Insert picture description here

Four, remarks

Complete code or write on behalf of adding QQ 1564658423

Guess you like

Origin blog.csdn.net/TIQCmatlab/article/details/115139019