-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_run.m
382 lines (285 loc) · 11.1 KB
/
main_run.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
close all
clc
clear
addpath(genpath(pwd))
dataset_dir = 'D:/PHD codes/DataSets/sleepedf20/';
%% load data & preprocessing
sub = 5; % total subjects
dm_common_load;
Fs = 100; % sampling rate
epoch = 30;
len = epoch*3; % each feature is extracted from 90s EEG signal;
boundary = 1;
% 1: avoiding edge effects by considering a much longer signal temporarily
% 0: the edge artifacts may contaminate the part of the feature we are interested in.
num_signal = min(2*sub,39)*2;
Channels = cell((num_signal)/2, 3);
label_org = cell((num_signal)/2, 1);
for caseNo = 1:min(2*sub,39)
sub_id = ceil(caseNo/2);
d_id = 1+(1-rem(caseNo,2));
PSG1 = all_record{sub_id,d_id}(:,1);
PSG2 = all_record{sub_id,d_id}(:,2);
EOG = all_record{sub_id,d_id}(:,3);
STAGE = all_hypnogram{sub_id,d_id};
before = (2+boundary);
after = boundary;
[x1,x2,num_STAGE,~] = truncated_rawPSG_HYP_SC(STAGE,PSG1,PSG2,(60+before),(60+after)); % include only 30 mins before and after sleep
[~,x3,num_STAGE,~] = truncated_rawPSG_HYP_SC(STAGE,PSG1,EOG,(60+before),(60+after)); % include only 30 mins before and after sleep
RR = rem(length(x1),Fs*epoch);
x1 = x1(1:length(x1)-RR);
RR = rem(length(x2),Fs*epoch);
x2 = x2(1:length(x2)-RR);
RR = rem(length(x3),Fs*epoch);
x3 = x3(1:length(x3)-RR);
label_org{caseNo} = num_STAGE;
Channels{caseNo, 1} = x1; % FPZCZ
Channels{caseNo, 2} = x2; % PZOZ
Channels{caseNo, 3} = x3; % EOG
if (length(x1)/100/30~=length(num_STAGE))
error('error');
end
if (length(x2)/100/30~=length(num_STAGE))
error('error');
end
end
clear x1 x2 PSG1 PSG2 num_STAGE
subject_infos.PID = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,...
11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20]'; %
subject_infos.PID = subject_infos.PID(1:min(sub*2,39));
%% extracting features from signals
windowSize = 3000;
for i = 1:size(Channels, 1)
i
[~, vec_eeg_features] = eeg_features_channel(Channels{i, 1} , windowSize , Fs); % FPZCZ
Channels{i, 1} = vec_eeg_features(:,4:end-1);
[~, vec_eeg_features] = eeg_features_channel(Channels{i, 2} , windowSize , Fs);% PZOZ
Channels{i, 2} = vec_eeg_features(:,4:end-1);
[~, vec_eeg_features] = eeg_features_channel(Channels{i, 3} , windowSize , Fs);% EOG
Channels{i, 3} = vec_eeg_features(:,4:end-1);
label{i} = label_org{i}(4:end-1);
if (size(Channels{i, 1},2)~=length(label{i}))
error('error in label alignment');
end
end
Channels_org = Channels;
save('channels.mat','Channels_org','label')
%% organization, labelling and indexing
Channels = Channels_org ;
true_labels = cell(size(Channels, 1), 1);
subjectId = cell(size(subject_infos.PID));
for i = 1:size(Channels, 1)
id = find(label{i} > 0);
if length(id)<length(label{i})
disp('remove')
end
for j = 1:size(Channels, 2)
Channels{i, j} = Channels{i, j}(:,id); % removing the features corresponding to MOVEMENT
end
true_labels{i} = full(ind2vec(double(label{i}(id)')))';
subjectId{i} = repelem(subject_infos.PID(i), length(true_labels{i}))';
end
[X,Y,Z] = my_cell2mat3(Channels,1);
% concatenation
feature_sets{1,1} = X';
feature_sets{2,1} = Y';
feature_sets{3,1} = Z';
save('fe_channels.mat','feature_sets','true_labels','subjectId')
%% dimension reduction & visulization
feature_sets_mat = [feature_sets{1,1},feature_sets{2,1},feature_sets{3,1}];
feature_sets_mat = zscore(feature_sets_mat);
dim = 2;
num_classes = 5;
train_data = feature_sets_mat;
[~, train_label] = max(cell2mat(true_labels), [], 2);
[para_lda, Z_lda] = lda_sldr(train_data, train_label, dim); % Linear discriminant analysis (LDA)
% [para_hlda, Z_hlda] = plsda_sldr(train_data, train_label, dim); % Heteroscedastic extension of LDA
[coeff, Z_hlda, ~, ~, ~, mu] = pca(train_data,'NumComponents',dim);
sz = 5;
figure
subplot(2,1,1)
gscatter(Z_hlda(:,1),Z_hlda(:,2),train_label)
title('PCA')
grid on
subplot(2,1,2)
gscatter(Z_lda(:,1),Z_lda(:,2),train_label)
title('LDA')
grid on
figure
tsne_features = tsne(feature_sets_mat);
gscatter(tsne_features(:,1),tsne_features(:,2),train_label);
grid on
save('tsne_features.mat','tsne_features','true_labels','subjectId')
%% 5-fold cross validation
y = cell2mat(true_labels);
[~, response] = max(y, [], 2);
cv_groups = cvpartition(response,'KFold',5);
temp_train = cv_groups.training(1);
temp_test = cv_groups.test(1);
%% leave-one-out cross validation
y = cell2mat(true_labels);
[~, response] = max(y, [], 2);
% create leave-one-out cross validation partition
cvp = struct;
cvp.NumObservations = size(response, 1);
cvp.testSize = zeros(1, sub);
cvp.trainSize = zeros(1, sub);
cvp.testStore = cell(1, sub);
cvp.trainStore = cell(1, sub);
for i = 1:sub
cvp.testStore{i} = cell2mat(subjectId) == i;
cvp.testSize(i) = sum(cvp.testStore{i});
cvp.trainSize(i) = cvp.NumObservations - cvp.testSize(i);
cvp.trainStore{i} = ~cvp.testStore{i};
end
%% 5-class (SVM & KNN & NN) One-vs-One
close all
classfier_type = 'svm';% svm knn nn
feature_sets_mat = [feature_sets{1,1},feature_sets{2,1},feature_sets{3,1}];
feature_sets_mat = zscore(feature_sets_mat);
predictors = feature_sets_mat;
y = cell2mat(true_labels);
[~, response] = max(y, [], 2);
prediction = cell(sub, 1);
test_labels= cell(sub, 1);
prediction_score= cell(sub, 1);
for i = 1:sub
disp(['fold: ',num2str(i)])
predictors_this = predictors;
num_features = size(predictors_this,2);
if strcmp(classfier_type,'svm')||strcmp(classfier_type,'knn')
if strcmp(classfier_type,'knn')
template = templateKNN('NumNeighbors',20,'Standardize',1);
else
template = templateSVM('KernelFunction', 'linear', ...
'PolynomialOrder', [], 'KernelScale', [], ...
'BoxConstraint', 0.3, 'Standardize', true);
end
Mdl = fitcecoc(predictors_this(cvp.trainStore{i}, :), response(cvp.trainStore{i}, :), ...
'Learners', template, ...
'Coding', 'onevsone');
[~, validationScores] = predict(Mdl, predictors_this(cvp.testStore{i}, :));
else
X = predictors_this(cvp.trainStore{i}, :);
T = cell2mat(true_labels);
T = T(cvp.trainStore{i}, :);
net = feedforwardnet([8,4]);
net = train(net,X',T','useGPU','yes');
validationScores = net(predictors_this(cvp.testStore{i}, :)')';
validationScores = validationScores-mean(validationScores);
end
[~, prediction{i}] = max(validationScores, [], 2);
test_labels{i} = response(cvp.testStore{i});
prediction_score{i} = validationScores(:,2);
end
acc = sum(cell2mat(test_labels)==cell2mat(prediction))/length(cell2mat(prediction));
disp(['Accuracy is: ',num2str(100*acc)])
%plot confusion matrix
test_labels_mat = cell2mat(test_labels);
output_label_mat = cell2mat(prediction);
plotconfusion( categorical(test_labels_mat),categorical(output_label_mat));
%% lda & pca & 5-class (SVM & KNN & NN) One-vs-One
close all
%common settings
classfier_type = 'nn';% svm knn nn
dim = 2;
lda_flag = 0;
nn_structure = [8,4];
y = cell2mat(true_labels);
[~, response] = max(y, [], 2);
feature_sets_mat = [feature_sets{1,1},feature_sets{2,1},feature_sets{3,1}];
feature_sets_mat = zscore(feature_sets_mat);
predictors = feature_sets_mat;
prediction = cell(sub, 1);
test_labels = cell(sub, 1);
prediction_score= cell(sub, 1);
for i = 1:sub
disp(['fold: ',num2str(i)])
train_data = predictors(cvp.trainStore{i},:);
train_label = response(cvp.trainStore{i});
if lda_flag==1
[para_lda, Z_lda] = lda_sldr(train_data, train_label, dim); % Linear discriminant analysis (LDA)
predictors_this = test_sldr(predictors, para_lda);
else
warning("off")
[coeff, predictors_this, ~, ~, ~, mu] = pca(predictors,'NumComponents',dim);
warning("on")
end
num_features = size(predictors_this,2);
if strcmp(classfier_type,'svm')||strcmp(classfier_type,'knn')
if strcmp(classfier_type,'knn')
template = templateKNN('NumNeighbors',20,'Standardize',1);
else
template = templateSVM('KernelFunction', 'linear', ...
'PolynomialOrder', [], 'KernelScale', [], ...
'BoxConstraint', 0.3, 'Standardize', true);
end
Mdl = fitcecoc(predictors_this(cvp.trainStore{i}, :), response(cvp.trainStore{i}, :), ...
'Learners', template, ...
'Coding', 'onevsone');
[~, validationScores] = predict(Mdl, predictors_this(cvp.testStore{i}, :));
else
X = predictors_this(cvp.trainStore{i}, :);
T = cell2mat(true_labels);
T = T(cvp.trainStore{i}, :);
net = feedforwardnet(nn_structure);
net = train(net,X',T','useGPU','yes');
validationScores = net(predictors_this(cvp.testStore{i}, :)')';
validationScores = validationScores-mean(validationScores);
end
[~, prediction{i}] = max(validationScores, [], 2);
test_labels{i} = response(cvp.testStore{i});
prediction_score{i} = validationScores(:,2);
end
acc = sum(cell2mat(test_labels)==cell2mat(prediction))/length(cell2mat(prediction));
disp(['Accuracy is: ',num2str(100*acc)])
%plot confusion matrix
test_labels_mat = cell2mat(test_labels);
output_label_mat = cell2mat(prediction);
plotconfusion( categorical(test_labels_mat),categorical(output_label_mat));
%% TSNE & 5-class (SVM & KNN & NN) One-vs-One
close all
%common settings
classfier_type = 'knn';% svm knn nn
nn_structure = [20,8,4];
predictors = tsne_features;
y = cell2mat(true_labels);
[~, response] = max(y, [], 2);
prediction = cell(sub, 1);
test_labels= cell(sub, 1);
prediction_score= cell(sub, 1);
for i = 1:sub
disp(['fold: ',num2str(i)])
predictors_this = predictors;
num_features = size(predictors_this,2);
if strcmp(classfier_type,'svm')||strcmp(classfier_type,'knn')
if strcmp(classfier_type,'knn')
template = templateKNN('NumNeighbors',20,'Standardize',1);
else
template = templateSVM('KernelFunction', 'linear', ...
'PolynomialOrder', [], 'KernelScale', [], ...
'BoxConstraint', 0.3, 'Standardize', true);
end
Mdl = fitcecoc(predictors_this(cvp.trainStore{i}, :), response(cvp.trainStore{i}, :), ...
'Learners', template, ...
'Coding', 'onevsone');
[~, validationScores] = predict(Mdl, predictors_this(cvp.testStore{i}, :));
else
X = predictors_this(cvp.trainStore{i}, :);
T = cell2mat(true_labels);
T = T(cvp.trainStore{i}, :);
net = feedforwardnet(nn_structure);
net = train(net,X',T','useGPU','yes');
validationScores = net(predictors_this(cvp.testStore{i}, :)')';
validationScores = validationScores-mean(validationScores);
end
[~, prediction{i}] = max(validationScores, [], 2);
test_labels{i} = response(cvp.testStore{i});
prediction_score{i} = validationScores(:,2);
end
acc = sum(cell2mat(test_labels)==cell2mat(prediction))/length(cell2mat(prediction));
disp(['Accuracy is: ',num2str(100*acc)])
%plot confusion matrix
test_labels_mat = cell2mat(test_labels);
output_label_mat = cell2mat(prediction);
plotconfusion( categorical(test_labels_mat),categorical(output_label_mat));