-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheeg_decoder.py
1543 lines (1266 loc) · 58.8 KB
/
eeg_decoder.py
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
import scipy.io as sio
import numpy as np
import pandas as pd
import pickle
import os
import matplotlib.pyplot as plt
import seaborn as sns
import time
from copy import deepcopy
import scipy.stats as sista
from sklearn.model_selection import StratifiedShuffleSplit, train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from statsmodels.stats.multitest import multipletests
class Experiment:
def __init__(
self, experiment_name, data_dir, info_from_file=True, dev=False,
info_variable_names=['unique_id', 'chan_labels', 'chan_x', 'chan_y', 'chan_z', 'sampling_rate', 'times'],
trim_timepoints = None
):
"""Organizes and loads in EEG, trial labels, behavior, eyetracking, and session data.
Keyword arguments:
experiment_name -- name of experiment
data_dir -- directory of data files
info_from_file -- pull info from 0th info file in data_dir (default True)
dev -- development mode: only use first 3 subjects' data (default False)
info_variable_names -- names of variables to pull from info file
trim_timepoints -- trims info.times and all loaded EEG data
"""
self.experiment_name = experiment_name
self.data_dir = Path(data_dir)
self.trim_idx = None
self.xdata_files = sorted(list(self.data_dir.glob('*xdata*.mat')))
self.ydata_files = sorted(list(self.data_dir.glob('*ydata*.mat')))
if dev:
self.xdata_files = self.xdata_files[0:3]
self.ydata_files = self.ydata_files[0:3]
self.nsub = len(self.xdata_files)
self.behavior_files = None
self.artifact_idx_files = None
self.info_files = None
if info_from_file:
self.info = self.load_info(0, info_variable_names)
self.info.pop('unique_id')
if trim_timepoints:
self.trim_idx = (self.info['times']>=trim_timepoints[0])&(self.info['times']<=trim_timepoints[1])
self.info['original_times'] = self.info['times']
self.info['times'] = self.info['times'][self.trim_idx]
def load_eeg(self, isub):
"""
loads xdata (eeg data) and ydata (trial labels) from .mat
Keyword arguments:
isub -- index of subject to load
"""
subj_mat = sio.loadmat(
self.xdata_files[isub], variable_names=['xdata'])
xdata = np.moveaxis(subj_mat['xdata'], [0, 1, 2], [1, 2, 0])
if self.trim_idx is not None:
xdata = xdata[:,:,self.trim_idx]
ydata = self.load_ydata(isub)
return xdata, ydata
def load_ydata(self, isub):
"""
loads ydata (trial labels) from .mat
Keyword arguments:
isub -- index of subject to load
"""
subj_mat = sio.loadmat(
self.ydata_files[isub], variable_names=['ydata'])
ydata = np.squeeze(subj_mat['ydata'])
return ydata
def load_behavior(self, isub, remove_artifact_trials=True):
"""
returns behavior from csv as dictionary
Keyword arguments:
isub -- index of subject to load
remove_artifact_trials -- remove all behavior trials that were excluded from EEG data due to artifacts
"""
if not self.behavior_files:
self.behavior_files = sorted(list(self.data_dir.glob('*.csv')))
behavior = pd.read_csv(self.behavior_files[isub]).to_dict('list')
if remove_artifact_trials:
artifact_idx = self.load_artifact_idx(isub)
for k in behavior.keys():
behavior[k] = np.array(behavior[k])[artifact_idx]
else:
for k in behavior.keys():
behavior[k] = np.array(behavior[k])
return behavior
def load_artifact_idx(self, isub):
"""
returns artifact index from EEG artifact rejection. useful for removing behavior trials not included in EEG data.
Keyword arguments:
isub -- index of subject to load
"""
if not self.artifact_idx_files:
self.artifact_idx_files = sorted(list(
self.data_dir.glob('*artifact_idx*.mat')))
artifact_idx = np.squeeze(sio.loadmat(
self.artifact_idx_files[isub])['artifact_idx'] == 1)
return artifact_idx
def load_info(self, isub, variable_names=['unique_id', 'chan_labels', 'chan_x', 'chan_y', 'chan_z', 'sampling_rate', 'times']):
"""
loads info file that contains data about EEG file and subject
Keyword arguments:
isub -- index of subject to load
variable_names -- names of variables to pull from info file
"""
if not self.info_files:
self.info_files = sorted(list(self.data_dir.glob('*info*.mat')))
info_file = sio.loadmat(
self.info_files[isub], variable_names=variable_names)
info = {k: np.squeeze(info_file[k]) for k in variable_names}
return info
class Experiment_Syncer:
def __init__(
self,
experiments,
wrangler,
train_group,
get_matched_data=True
):
'''
Synchronizes subject data across multiple experiments.
Keyword variables:
experiments -- Experiments objects to be synced
wrangler -- Wrangler object to be used
train_group -- which experiments to be used in the training set
get_matched_data -- only use subjects who appear in both experiments (default True)
'''
self.experiments = experiments
self.wrangler = wrangler
self.train_group = train_group
self.experiment_names = []
for i in range(len(experiments)):
self.experiment_names.append(experiments[i].experiment_name)
self._load_unique_ids()
if get_matched_data:
self._find_matched_ids()
else:
self._find_all_ids()
def _load_unique_ids(self):
'''
Loads all IDs in all experiments
'''
self.all_ids = []
for exp in self.experiments:
exp.unique_ids = []
for isub in range(exp.nsub):
exp.unique_ids.append(int(exp.load_info(isub)['unique_id']))
self.all_ids.extend(exp.unique_ids)
self.all_ids = np.unique(self.all_ids)
self.matched_ids = []
for i in self.all_ids:
check = 0
for exp in self.experiments:
if i in exp.unique_ids:
check += 1
if check == len(self.experiments):
self.matched_ids.append(i)
def _find_matched_ids(self):
'''
Finds only IDs that are in all experiments
'''
self.id_dict = dict.fromkeys(self.matched_ids)
for k in self.id_dict.keys():
self.id_dict[k] = dict.fromkeys(self.experiment_names)
for exp in self.experiments:
for m in self.matched_ids:
try:
self.id_dict[m][exp.experiment_name] = exp.unique_ids.index(
m)
except ValueError:
pass
self.nsub = len(self.matched_ids)
def _find_all_ids(self):
'''
Finds IDs in all experiments. Used for loading all data across experiments.
'''
self.id_dict = dict.fromkeys(self.all_ids)
for k in self.id_dict.keys():
self.id_dict[k] = dict.fromkeys(self.experiment_names)
for exp in self.experiments:
for m in self.all_ids:
try:
self.id_dict[m][exp.experiment_name] = exp.unique_ids.index(
m)
except ValueError:
pass
self.nsub = len(self.all_ids)
def load_eeg(self, sub):
"""
loads xdata (eeg data) and ydata (trial labels) of every experiment from .mat
Keyword arguments:
sub -- unique ID of subject to load
"""
xdata = dict.fromkeys(self.experiment_names)
ydata = dict.fromkeys(self.experiment_names)
for exp in self.experiments:
if self.id_dict[sub][exp.experiment_name] is not None:
xdata[exp.experiment_name], ydata[exp.experiment_name] = exp.load_eeg(
self.id_dict[sub][exp.experiment_name])
else:
xdata.pop(exp.experiment_name)
ydata.pop(exp.experiment_name)
return xdata, ydata
def load_behavior(self, sub):
"""
returns behavior from csv as dictionary
Keyword arguments:
sub -- unique ID of subject to load
"""
beh = dict.fromkeys(self.experiment_names)
for exp in self.experiments:
if self.id_dict[sub][exp.experiment_name] is not None:
beh[exp.experiment_name] = exp.load_behavior(
self.id_dict[sub][exp.experiment_name])
else:
beh.pop(exp.experiment_name)
return beh
def select_labels(self, xdata, ydata):
"""
includes labels only wanted for decoding. returns xdata and ydata with unwanted labels removed.
Keyword arguments:
xdata: eeg data, shape[electrodes,timepoints,trials]
ydata: labels, shape[trials]
"""
for exp_name in xdata.keys():
xdata[exp_name], ydata[exp_name] = self.wrangler.select_labels(
xdata[exp_name], ydata[exp_name])
return xdata, ydata
def group_labels(self, xdata, ydata):
'''
groups classes based on group_dict, removes not-included classes
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
'''
for exp_name in xdata.keys():
xdata[exp_name], ydata[exp_name] = self.wrangler.group_labels(
xdata[exp_name], ydata[exp_name])
return xdata, ydata
def balance_labels(self, xdata, ydata):
'''
balances number of class instances
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
'''
for exp_name in xdata.keys():
xdata[exp_name], ydata[exp_name] = self.wrangler.balance_labels(
xdata[exp_name], ydata[exp_name])
return xdata, ydata
def bin_trials(self, xdata, ydata):
'''
bins trials based on trial_bin_size
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
'''
for exp_name in xdata.keys():
xdata[exp_name], ydata[exp_name] = self.wrangler.average_trials(
xdata[exp_name], ydata[exp_name])
return xdata, ydata
def setup_data(self, xdata, ydata, labels=False, group_dict=False):
'''
does basic data manipulation using other functions. Deprecated.
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
labels -- use select_labels function (default False)
group_dict -- use group.labels function (default False)
'''
if labels:
xdata, ydata = self.select_labels(xdata, ydata)
if group_dict:
xdata, ydata = self.group_labels(xdata, ydata)
xdata, ydata = self.balance_labels(xdata, ydata)
xdata, ydata = self.bin_trials(xdata, ydata)
return xdata, ydata
def pairwise(self, xdata_all, ydata_all):
'''
When using group_dict_list (e.g. 1vs2 then 2vs4), yields data with only those classes.
Keyword arguments:
xdata_all -- eeg data, shape[electrodes,timepoints,trials]
ydata_all -- labels, shape[trials]
'''
for self.wrangler.iss, ss in enumerate(self.wrangler.group_dict_list):
xdata, ydata = deepcopy(xdata_all), deepcopy(ydata_all)
self.wrangler.group_dict = ss
for exp_name in xdata.keys():
xdata[exp_name], ydata[exp_name] = self.wrangler.group_labels(
xdata[exp_name], ydata[exp_name])
yield xdata, ydata
def group_data(self, xdata, ydata):
'''
groups data into train and test groups based on self.train_group
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
'''
xdata_train, xdata_test = None, None
for exp_name in xdata.keys():
if np.isin(exp_name, self.train_group):
if xdata_train is not None:
xdata_train = np.append(xdata_train, xdata[exp_name], 0)
ydata_train = np.append(ydata_train, ydata[exp_name], 0)
elif xdata_train is None:
xdata_train = xdata[exp_name]
ydata_train = ydata[exp_name]
else:
if xdata_test is not None:
xdata_test = np.append(xdata_test, xdata[exp_name], 0)
ydata_test = np.append(ydata_test, ydata[exp_name], 0)
elif xdata_test == None:
xdata_test = xdata[exp_name]
ydata_test = ydata[exp_name]
if xdata_test is None: # if both groups are in train_group, function combines and returns as one
return xdata_train, ydata_train
else:
return xdata_train, xdata_test, ydata_train, ydata_test
class Wrangler:
def __init__(self,
samples,
time_window, time_step,
trial_bin_size,
n_splits,
group_dict=None,
group_dict_list=None,
train_labels=None,
test_size = .1,
labels=None,
electrodes=None,
electrode_subset_list=None):
"""
Handles data processing and cross-validation.
Keyword arguments:
samples -- timepoints (in ms) of EEG epochs
time_window -- window size for averaging
time_step -- window step for averaging
trial_bin_size -- number of trials per trial bin
n_splits -- number of folds in cross-validation procedure
group_dict -- trial labels to be grouped together (default None)
group_dict_list -- list of group_dict for pairwise decoding (default None)
train_labels -- list of labels to include in training (default None)
test_size -- percent of trials to test (default 0.1)
labels -- labels to be included in decoding (default None)
electrodes -- names of electrodes in EEG data (default None)
electrode_subset_list -- which electrodes to include in decoding (default None)
"""
self.samples = samples
self.sample_step = samples[1]-samples[0]
self.time_window = time_window
self.time_step = time_step
self.trial_bin_size = trial_bin_size
self.n_splits = n_splits
self.test_size = test_size
self.group_dict = group_dict
self.group_dict_list = group_dict_list
self.train_labels = train_labels
self.labels = labels
self.electrodes = electrodes
self.electrode_subset_list = electrode_subset_list
if self.group_dict_list:
self.labels = []
self.label_dict = []
self.num_labels = []
for group_dict in group_dict_list:
labels = list(group_dict)
self.labels.append(labels)
label_dict = {}
for i, key in enumerate(group_dict.keys()):
label_dict[key] = i
self.label_dict.append(label_dict)
self.num_labels.append(len(labels))
else:
if self.group_dict:
self.labels = list(self.group_dict.keys())
self.label_dict = {}
for i, key in enumerate(group_dict.keys()):
self.label_dict[key] = i
if self.labels:
self.num_labels = len(self.labels)
else:
self.num_labels = None
self.t = samples[0:samples.shape[0] - int(time_window/self.sample_step)+1:int(time_step/self.sample_step)]
def select_labels(self, xdata, ydata, labels=None, return_idx=False):
"""
includes labels only wanted for decoding. returns xdata and ydata with unwanted labels removed.
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
labels -- list of labels to include
return_idx -- return index of trials selected
"""
if labels is None:
labels = self.labels
label_idx = np.isin(ydata, labels)
xdata = xdata[label_idx, :, :]
ydata = ydata[label_idx]
if return_idx:
return xdata, ydata, label_idx
else:
return xdata, ydata
def group_labels(self, xdata, ydata, empty_val=9999):
"""
groups classes based on group dict. Also excludes classes not included in group_dict.
If one of your class labels is 9999, change empty_val to something your class label isn't.
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
empty_val -- pre-allocate empty array with this value.
"""
xdata_new = np.ones(xdata.shape)*empty_val
ydata_new = np.ones(ydata.shape)*empty_val
for i,k in enumerate(self.group_dict.values()):
trial_idx = np.arange(ydata.shape[0])[np.isin(ydata, k)]
xdata_new[trial_idx] = xdata[trial_idx]
ydata_new[trial_idx] = i
trial_idx = ydata_new == empty_val
return xdata_new[~trial_idx], ydata_new[~trial_idx]
def pairwise(self, xdata_all, ydata_all):
'''
When using group_dict_list (e.g. 1vs2 then 2vs4), yields data with only those classes.
Keyword arguments:
xdata_all -- eeg data, shape[electrodes,timepoints,trials]
ydata_all -- labels, shape[trials]
'''
for self.iss, ss in enumerate(self.group_dict_list):
xdata, ydata = deepcopy(xdata_all), deepcopy(ydata_all)
self.group_dict = ss
yield self.group_labels(xdata, ydata)
def balance_labels(self, xdata, ydata, downsamp=None):
'''
balances number of class instances
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
downsamp -- number of trials to downsample to (default None). If None, downsamples to lowest count.
'''
unique_labels, counts_labels = np.unique(ydata, return_counts=True)
if downsamp is None:
downsamp = min(counts_labels)
label_idx = []
for label in unique_labels:
label_idx = np.append(label_idx, np.random.choice(
np.arange(len(ydata))[ydata == label], downsamp, replace=False))
xdata = xdata[label_idx.astype(int), :, :]
ydata = ydata[label_idx.astype(int)]
return xdata, ydata
def bin_trials(self, xdata, ydata, permute_trials = True):
'''
bins trials based on trial_bin_size
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
permute_trials -- shuffle trials before binning to get unique bins each call
'''
if self.trial_bin_size:
if permute_trials:
p = np.random.permutation(len(ydata))
xdata, ydata = xdata[p], ydata[p]
# get labels and counts
unique_labels, label_counts = np.unique(ydata, return_counts=True)
# determine number of bins per label
n_bins = label_counts//self.trial_bin_size
n_trials = n_bins * self.trial_bin_size
xdata_bin = []
ydata_bin = []
# loop through labels
for ilabel,label in enumerate(unique_labels):
# assign each trial of label to bin
label_bins = np.tile(np.arange(n_bins[ilabel]),n_trials[ilabel]//n_bins[ilabel])
# create label index
label_idx = ydata == label
# grab data
label_data = xdata[label_idx][:n_trials[ilabel]]
# preallocate
bin_average_data = np.empty((n_bins[ilabel],label_data.shape[1],label_data.shape[2]))
# loop though bins
for ibin, bin in enumerate(np.unique(label_bins)):
# make bin idx
bin_idx = label_bins == bin
# average over data
bin_average_data[ibin] = np.mean(label_data[bin_idx],0)
xdata_bin.append(bin_average_data)
ydata_bin += [label]*n_bins[ilabel]
xdata_bin = np.concatenate(xdata_bin)
ydata_bin = np.array(ydata_bin)
return xdata_bin, ydata_bin
else:
return xdata, ydata
def bin_data(self, X_train_all, X_test_all, y_train, y_test):
'''
helper function than does trial binning
Keyword arguments:
X_train_all -- EEG data to be used for training
X_test_all -- EEG data to be used for testing
y_train -- trial labels for training data
y_test -- trial labels for testing data
'''
X_train_all, y_train = self.bin_trials(X_train_all, y_train)
X_test_all, y_test = self.bin_trials(X_test_all, y_test)
return X_train_all, X_test_all, y_train, y_test
def balance_data(self, X_train_all, X_test_all, y_train, y_test):
'''
helper function than does trial binning and balances data
Keyword arguments:
X_train_all -- EEG data to be used for training
X_test_all -- EEG data to be used for testing
y_train -- trial labels for training data
y_test -- trial labels for testing data
'''
X_train_all, y_train = self.balance_labels(X_train_all, y_train)
X_test_all, y_test = self.balance_labels(X_test_all, y_test)
return X_train_all, X_test_all, y_train, y_test
def bin_and_balance_data(self, X_train_all, X_test_all, y_train, y_test):
'''
helper function than does trial binning and balances data
Keyword arguments:
X_train_all -- EEG data to be used for training
X_test_all -- EEG data to be used for testing
y_train -- trial labels for training data
y_test -- trial labels for testing data
'''
X_train_all, X_test_all, y_train, y_test = self.bin_data(X_train_all, X_test_all, y_train, y_test)
X_train_all, X_test_all, y_train, y_test = self.balance_data(X_train_all, X_test_all, y_train, y_test)
return X_train_all, X_test_all, y_train, y_test
def select_training_data(self, X_train_all, y_train):
'''
select training data based on self.train_labels
Keyword arguments:
X_train_all -- EEG data to be used for training
y_train -- trial labels for training data
'''
# create index for labels from train_labels
labels = []
[labels.append(self.label_dict[k]) for k in self.train_labels]
return self.select_labels(X_train_all, y_train, labels)
def select_electrodes(self, xdata, electrode_subset=None):
'''
removes electrodes not included in electrode_subset.
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
electrode_subset -- electrode subset to select for use in classification (default None)
'''
if electrode_subset is not None:
# Create index for electrodes to include in plot
electrode_labels = [el for n, el in enumerate(
self.electrodes) if el.startswith(electrode_subset)]
electrode_idx = np.in1d(self.electrodes, electrode_labels)
xdata = xdata[:, electrode_idx]
return xdata
def roll_over_electrodes(self, xdata_all, ydata_all):
'''
yields data with electrodes not in electrode subset, iterating over electrode_subset_list.
Keyword arguments:
xdata_all -- eeg data, shape[electrodes,timepoints,trials]
ydata_all -- labels, shape[trials]
'''
for self.ielec, electrode_subset in enumerate(self.electrode_subset_list):
yield self.select_electrodes(xdata_all, electrode_subset), ydata_all
def bin_and_split_data(self, xdata, ydata):
"""
returns xtrain and xtest data and labels, binned
Keyword arguments:
xdata -- eeg data, shape[electrodes,timepoints,trials]
ydata -- labels, shape[trials]
return_idx -- return index used to select test data (default False)
"""
for self.ifold in range(self.n_splits):
xdata_binned, ydata_binned = self.bin_trials(xdata, ydata)
X_train_all, X_test_all, y_train, y_test = train_test_split(xdata_binned,ydata_binned,stratify=ydata_binned)
yield X_train_all, X_test_all, y_train, y_test
def roll_over_time(self, X_train_all, X_test_all=None):
"""
returns one timepoint of EEG trial at a time
Keyword arguments:
X_train_all -- all EEG data for training
X_test_all -- all EEG data for testing (default None)
"""
for self.itime, time in enumerate(self.t):
time_window_idx = (self.samples >= time) & (
self.samples < time + self.time_window)
# Data for this time bin
X_train = np.mean(X_train_all[..., time_window_idx], 2)
if X_test_all is not None:
X_test = np.mean(X_test_all[..., time_window_idx], 2)
yield X_train, X_test
else:
yield X_train
def roll_over_time_temp_gen(self, X_train_all, X_test_all):
'''
yield every other timepoint for each timepoint. Used for temporal generalizability plots.
Keyword arguments:
X_train_all -- all EEG data for training
X_test_all -- all EEG data for testing (default None)
'''
for self.itime1, time1 in enumerate(self.t):
for self.itime2, time2 in enumerate(self.t):
time_window_idx1 = (self.samples >= time1) & (
self.samples < time1 + self.time_window)
time_window_idx2 = (self.samples >= time2) & (
self.samples < time2 + self.time_window)
# Data for this time bin
X_train = np.mean(X_train_all[..., time_window_idx1], 2)
X_test = np.mean(X_test_all[..., time_window_idx2], 2)
yield X_train, X_test
def bin_and_custom_split(self, xdata_train, xdata_test, ydata_train, ydata_test, test_size=.1):
'''
Takes in train and test data and yields portion of each for purposes of cross-validation.
Useful if you want data to always be in train, and other data to always be in test.
e.g. train on color and test on orientation data.
Keyword arguments:
xdata_train -- all EEG data for training
xdata_test -- all EEG data for testing
ydata_train -- trial labels for training data
ydata_test -- trial labels for test data
'''
self.ifold = 0
for self.ifold in range(self.n_splits):
xdata_train_binned, ydata_train_binned = self.bin_trials(xdata_train, ydata_train)
xdata_test_binned, ydata_test_binned = self.bin_trials(xdata_test, ydata_test)
X_train_all, _, y_train, _ = train_test_split(xdata_train_binned,ydata_train_binned,stratify=ydata_train_binned)
_, X_test_all, _, y_test = train_test_split(xdata_test_binned,ydata_test_binned,stratify=ydata_test_binned,test_size=test_size)
yield X_train_all, X_test_all, y_train, y_test
class Classification:
def __init__(self, wrangl, nsub, num_labels=None, classifier=None):
"""
Classification and storing of classification outputs.
Keyword arguments:
wrangl -- Wrangler object that was used with data
nsub -- number of subjects in decoding
num_labels -- number of unique trial labels (default None)
classifier -- classifier object for decoding (default None). If none, defaults to sklearn's Logistic Regression.
"""
self.wrangl = wrangl
self.n_splits = wrangl.n_splits
self.t = wrangl.t
if wrangl.num_labels:
self.num_labels = wrangl.num_labels
if num_labels:
self.num_labels = num_labels
if self.num_labels is None:
raise Exception(
'Must provide number of num_labels to Classification')
self.nsub = nsub
if classifier:
self.classifier = classifier
else:
self.classifier = LogisticRegression()
self.scaler = StandardScaler()
self.acc = np.zeros((self.nsub, np.size(self.t), self.n_splits))*np.nan
self.acc_shuff = np.zeros(
(self.nsub, np.size(self.t), self.n_splits))*np.nan
self.conf_mat = np.zeros((self.nsub, np.size(
self.t), self.n_splits, self.num_labels, self.num_labels))*np.nan
self.confidence_scores = np.empty((self.nsub,len(self.t),self.n_splits,self.num_labels))*np.nan
def standardize(self, X_train, X_test):
"""
z-score each electrode across trials at this time point. returns standardized train and test data.
Note: this fits and transforms train data, then transforms test data with mean and std of train data!!!
Keyword arguments:
X_train -- time slice of EEG data for training
X_test -- time slice of EEG data for testing
"""
# Fit scaler to X_train and transform X_train
X_train = self.scaler.fit_transform(X_train)
X_test = self.scaler.transform(X_test)
return X_train, X_test
def decode(self, X_train, X_test, y_train, y_test, y_test_shuffle, isub):
'''
does actual training and testing of classifier after standardizing the data. Also does shuffled testing, confusion matrix, and confidence scores.
Keyword arguments:
X_train -- time slice of EEG data for training
X_test -- time slice of EEG data for testing
y_train -- trial labels for training data
y_test -- trial labels for test data
y_test_shuffle -- shuffled trial labels for shuffle test check
isub -- index of subject being trained/tested
'''
ifold = self.wrangl.ifold
itime = self.wrangl.itime
X_train, X_test = self.standardize(X_train, X_test)
self.classifier.fit(X_train, y_train)
self.acc[isub, itime, ifold] = self.classifier.score(X_test, y_test)
self.acc_shuff[isub, itime, ifold] = self.classifier.score(
X_test, y_test_shuffle)
self.conf_mat[isub, itime, ifold] = confusion_matrix(
y_test, y_pred=self.classifier.predict(X_test))
confidence_scores = self.classifier.decision_function(X_test)
for i,ss in enumerate(set(y_test)):
self.confidence_scores[isub,itime,ifold,i] = np.mean(confidence_scores[y_test==ss])
def decode_pairwise(self, X_train, X_test, y_train, y_test, y_test_shuffle, isub):
'''
Same functionality as decode. But results matrices are different shape.
Used when using group_dict_list and rolling over multiple sets of classes (e.g. 1vs2 and 2vs4)
Keyword arguments:
X_train -- time slice of EEG data for training
X_test -- time slice of EEG data for testing
y_train -- trial labels for training data
y_test -- trial labels for test data
y_test_shuffle -- shuffled trial labels for shuffle test check
isub -- index of subject being trained/tested
'''
ifold = self.wrangl.ifold
itime = self.wrangl.itime
iss = self.wrangl.iss
X_train, X_test = self.standardize(X_train, X_test)
self.classifier.fit(X_train, y_train)
self.acc[isub, iss, itime, ifold] = self.classifier.score(
X_test, y_test)
self.acc_shuff[isub, iss, itime, ifold] = self.classifier.score(
X_test, y_test_shuffle)
self.conf_mat[isub, iss, itime, ifold] = confusion_matrix(
y_test, y_pred=self.classifier.predict(X_test))
def decode_temp_gen(self, X_train, X_test, y_train, y_test, isub):
'''
Same functionality as decode. But results matrices are different shape.
Keyword arguments:
X_train -- time slice of EEG data for training
X_test -- time slice of EEG data for testing
y_train -- trial labels for training data
y_test -- trial labels for test data
isub -- index of subject being trained/tested
'''
ifold = self.wrangl.ifold
itime1 = self.wrangl.itime1
itime2 = self.wrangl.itime2
X_train, X_test = self.standardize(X_train, X_test)
self.classifier.fit(X_train, y_train)
self.acc[isub, itime1, itime2,
ifold] = self.classifier.score(X_test, y_test)
self.acc_shuff[isub, itime1, itime2, ifold] = self.classifier.score(
X_test, np.random.permutation(y_test))
self.conf_mat[isub, itime1, itime2, ifold] = confusion_matrix(
y_test, y_pred=self.classifier.predict(X_test))
def decode_electrode_subset(self, X_train, X_test, y_train, y_test, isub):
'''
Same functionality as decode. But results matrices are different shape.
Keyword arguments:
X_train -- time slice of EEG data for training
X_test -- time slice of EEG data for testing
y_train -- trial labels for training data
y_test -- trial labels for test data
isub -- index of subject being trained/tested
'''
ifold = self.wrangl.ifold
itime = self.wrangl.itime
ielec = self.wrangl.ielec
X_train, X_test = self.standardize(X_train, X_test)
self.classifier.fit(X_train, y_train)
self.acc[isub, ielec, itime, ifold] = self.classifier.score(
X_test, y_test)
self.acc_shuff[isub, ielec, itime, ifold] = self.classifier.score(
X_test, np.random.permutation(y_test))
self.conf_mat[isub, ielec, itime, ifold] = confusion_matrix(
y_test, y_pred=self.classifier.predict(X_test))
class Interpreter:
def __init__(
self,
clfr=None,
subtitle='',
output_dir=None,
experiment_name=''):
"""
Visualization and statistical testing.
Keyword arguments:
clfr -- Classification object to be interpreted
subtitle -- subtitle for saving classification results
output_dir -- directory to output saved results
experiment_name -- name of experiment
"""
if clfr is not None:
self.clfr = clfr
self.t = clfr.wrangl.t
self.time_window = clfr.wrangl.time_window
self.time_step = clfr.wrangl.time_step
self.trial_bin_size = clfr.wrangl.trial_bin_size
self.n_splits = clfr.wrangl.n_splits
self.labels = list(clfr.wrangl.labels)
self.electrodes = clfr.wrangl.electrodes
self.acc = clfr.acc
self.acc_shuff = clfr.acc_shuff
self.conf_mat = clfr.conf_mat
self.confidence_scores = clfr.confidence_scores
import matplotlib
matplotlib.rcParams['font.sans-serif'] = "Arial"
matplotlib.rcParams['font.family'] = "sans-serif"
self.colors = ['royalblue', 'firebrick', 'forestgreen', 'orange', 'purple']
self.timestr = time.strftime("%Y%m%d_%H%M")
self.subtitle = subtitle
self.experiment_name = experiment_name
if output_dir:
self.output_dir = output_dir
else:
self.output_dir = Path('./output')
self.fig_dir = self.output_dir / 'figures'
def save_results(self, filename=None, additional_values=None):
"""
Saves results of classification.
Keyword arguments:
filename -- name of file to store results
additional_values -- additional variables to save
"""
values = ['t', 'time_window', 'time_step', 'trial_bin_size',
'n_splits', 'labels', 'electrodes', 'acc', 'acc_shuff', 'conf_mat', 'confidence_scores']
if additional_values:
for val in additional_values:
values.append(val)
results_dict = {}
for value in values:
results_dict[value] = self.__dict__[value]
if filename is None:
filename = self.subtitle + '_' + self.timestr + '.pickle'
else:
filename = filename + '.pickle'
file_to_save = self.output_dir / filename