forked from google/telluride_decoding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecoding_test.py
1160 lines (1038 loc) · 52.4 KB
/
decoding_test.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
# Lint as: python2, python3
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the decoding part of the library.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
import shutil
from absl import flags
from absl.testing import absltest
from absl.testing import flagsaver
from telluride_decoding import decoding
import numpy as np
import numpy.matlib
import scipy
from six.moves import range
import tensorflow as tf
class DecodingTest(absltest.TestCase):
def setUp(self):
super(DecodingTest, self).setUp()
self._test_data = os.path.join(
flags.FLAGS.test_srcdir,
'google3/third_party/py/telluride_decoding/test_data/')
def clear_model(self):
model_dir = '/tmp/tf'
try:
# Clear out the model directory, if it exists, because the TF save model
# code wants an empty directory.
shutil.rmtree(model_dir)
except OSError:
pass
################## Linear data for testing ################################
# Just a list of consecutive integers, to make it easier to debug batching
# issues and the like.
def create_linear_dataset(self, dataset, mode='test'):
def transform(input_data):
return input_data + 3000
assert isinstance(dataset, decoding.BrainData)
num_samples = 1000
input_data = np.arange(num_samples).reshape((num_samples, 1))
input_data = np.concatenate((input_data, num_samples + input_data), axis=1)
output_data = transform(input_data[:, 0:1])
dataset.preserve_test_data(input_data, output_data)
return dataset.create_dataset(mode=mode)
@flagsaver.flagsaver
def test_linear_batching(self):
"""Test the batching (pre and post context).
This is key to the decoding datasets. Make sure the resulting dataset
object is returning the right data. Test with linearly increasing data, so
we know to expect, especially as we add context.
"""
print('********** test_linear_batching **************')
batch_size = 999 # Big batch to minimize chance of random alignment.
# No shift
def create_test_dataset(pre_context, post_context, mode):
test_dataset = decoding.BrainData('input', 'output',
final_batch_size=batch_size,
pre_context=pre_context,
post_context=post_context,
repeat_count=10)
next_iterator, _ = self.create_linear_dataset(test_dataset, mode)
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
print('Input_data.shape', input_data.shape)
self.assertLen(input_data.shape, 2)
self.assertGreater(input_data.shape[0], 0)
self.assertGreater(input_data.shape[1], 0)
print('test_linear_batch input:', input_data[0:3, :])
print('test_linear_batch output:', output[0:3, :])
return input_data, output, test_dataset
def all_in_order(data):
return np.all(data[1:, :] > data[0:-1, :])
# First test without context, using test data so there is no shuffling.
pre_context = 0
post_context = 0
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
mode='test')
num_input_channels = test_dataset.num_input_channels
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(input_data.shape[1], 2)
# pylint: disable=bad-whitespace
self.assertTrue(np.all(np.equal(input_data[0:3, :], [[0, 1000],
[1, 1001],
[2, 1002]])))
self.assertTrue(np.all(np.equal(output[0:3, :], [[3000],
[3001],
[3002]])))
self.assertEqual(test_dataset.input_fields_width(),
num_input_channels*(pre_context+1+post_context))
self.assertTrue(all_in_order(input_data))
self.assertTrue(all_in_order(output))
# Now test with training data, to make sure batches are randomized.
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
'train')
self.assertFalse(all_in_order(input_data))
self.assertFalse(all_in_order(output))
self.assertTrue(np.all((input_data[:, 0] + 3000) == output[:, 0]))
# Now test with just two samples of pre context
pre_context = 2
post_context = 0
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
mode='test')
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(input_data.shape[1], 6)
# Last row of input and output should match, with extra context before.
self.assertTrue(np.all(np.equal(input_data[0:3, :],
[[0, 0, 0, 0, 0, 1000],
[0, 0, 0, 1000, 1, 1001],
[0, 1000, 1, 1001, 2, 1002]])))
self.assertTrue(np.all(np.equal(output[0:3, :],
[[3000],
[3001],
[3002]])))
self.assertEqual(test_dataset.input_fields_width(),
num_input_channels*(pre_context+1+post_context))
self.assertTrue(all_in_order(input_data[2:, :]))
self.assertTrue(all_in_order(output))
# Now test with just two samples of post context
pre_context = 0
post_context = 2
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
mode='test')
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(input_data.shape[1], 6)
# First row of input and output should match, with extra context before.
self.assertTrue(np.all(np.equal(input_data[0:3, :],
[[0, 1000, 1, 1001, 2, 1002],
[1, 1001, 2, 1002, 3, 1003],
[2, 1002, 3, 1003, 4, 1004]])))
self.assertTrue(np.all(np.equal(output[0:3, :],
[[3000],
[3001],
[3002]])))
self.assertEqual(test_dataset.input_fields_width(),
num_input_channels*(pre_context+1+post_context))
self.assertTrue(all_in_order(input_data[:-2, :]))
self.assertTrue(all_in_order(output))
# Now test with the data mixed up.
flags.FLAGS.random_mixup_batch = True
pre_context = 0
post_context = 0
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
'train')
self.assertFalse(all_in_order(input_data))
self.assertFalse(all_in_order(output))
matches = np.sum((input_data[:, 0] + 3000) == output[:, 0])
print('Found %d matches in %d frames.' % (matches, input_data.shape[0]))
self.assertLess(matches, input_data.shape[0]/64)
# pylint: enable=bad-whitespace
@flagsaver.flagsaver
def test_linear_batching_both_sides(self):
"""Test the batching (pre and post context) for input *and* output.
"""
print('********** test_linear_batching_both_sides **************')
batch_size = 999 # Big batch to minimize chance of random alignment.
# No shift
def create_test_dataset(pre_context, post_context,
output_pre_context, output_post_context, mode):
test_dataset = decoding.BrainData('input', 'output',
final_batch_size=batch_size,
pre_context=pre_context,
post_context=post_context,
output_pre_context=output_pre_context,
output_post_context=output_post_context,
repeat_count=10)
next_iterator, _ = self.create_linear_dataset(test_dataset, mode)
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
print('Input_data.shape', input_data.shape)
self.assertLen(input_data.shape, 2)
self.assertGreater(input_data.shape[0], 0)
self.assertGreater(input_data.shape[1], 0)
print('test_linear_batch input:', input_data[0:3, :])
print('test_linear_batch output:', output[0:3, :])
return input_data, output, test_dataset
def all_in_order(data):
return np.all(data[1:, :] > data[0:-1, :])
# Now test with just two samples of output pre context
pre_context = 0
post_context = 0
output_pre_context = 2
output_post_context = 0
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
output_pre_context,
output_post_context,
mode='test')
num_input_channels = test_dataset.num_input_channels
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(input_data.shape[1], 2)
# Last row of input and output should match, with extra context before.
# pylint: disable=bad-whitespace
self.assertTrue(np.all(np.equal(input_data[0:3, :],
[[0, 1000],
[1, 1001],
[2, 1002]])))
self.assertTrue(np.all(np.equal(output[0:3, :],
[[ 0, 0, 3000],
[ 0, 3000, 3001],
[3000, 3001, 3002]])))
self.assertEqual(test_dataset.input_fields_width(),
num_input_channels*(pre_context+1+post_context))
self.assertTrue(all_in_order(input_data))
self.assertTrue(all_in_order(output[2:, :]))
# Now test with just two samples of post context.
pre_context = 0
post_context = 0
output_pre_context = 0
output_post_context = 2
input_data, output, test_dataset = create_test_dataset(pre_context,
post_context,
output_pre_context,
output_post_context,
mode='test')
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(input_data.shape[1], 2)
self.assertEqual(output.shape[1], 3)
# First row of input and output should match, with extra context before.
self.assertTrue(np.all(np.equal(input_data[0:3, :],
[[0, 1000],
[1, 1001],
[2, 1002]])))
self.assertTrue(np.all(np.equal(output[0:3, :],
[[3000, 3001, 3002],
[3001, 3002, 3003],
[3002, 3003, 3004]])))
self.assertTrue(all_in_order(input_data))
self.assertTrue(all_in_order(output[:-2, :]))
# pylint: enable=bad-whitespace
################## Simply scaled data ################################
# Simple data for testing the machine learning. Output is a simple transform
# of the input data (sin in this case.) Use this data to test simple
# regression, and data offsets.
def simply_scaled_transform(self, input_data):
"""Transform to apply to the data.
Kept as a separate function for easier testing. In this case, just the sin
of the first column.
Args:
input_data: the input data
Returns:
the input_data transformed by this function.
"""
assert len(input_data.shape) == 2
return np.sin(input_data[:, 0:1] * 2 * np.pi)
def create_simply_scaled_dataset(self, dataset, data_offset=0,
num_input_channels=2, mode='test'):
"""A dataset where the output is a simple scalar function of the input."""
assert isinstance(dataset, decoding.BrainData)
num_samples = 100000
input_data = np.random.randn(num_samples + 2*abs(data_offset),
num_input_channels).astype(np.float32)
output_data = self.simply_scaled_transform(input_data)
if data_offset >= 0:
input_data = input_data[0:num_samples, :]
output_data = output_data[data_offset:data_offset + num_samples, :]
else:
input_data = input_data[-data_offset:
-data_offset + num_samples, :]
output_data = output_data[0:num_samples, :]
dataset.preserve_test_data(input_data, output_data)
return dataset.create_dataset(mode=mode)
@flagsaver.flagsaver
def test_simple_shift(self):
"""Test the batching as we shift the data.
Make sure that the testdata is properly formatted and that the output
is computed from the correct column, as we shift the context around.
"""
batch_size = 128
print('********** test_testdata **************')
pre_context = 2
post_context = 2
def create_shifted_test(data_offset):
test_dataset = decoding.BrainData('input', 'output',
repeat_count=10,
final_batch_size=batch_size,
pre_context=pre_context,
post_context=post_context)
next_iterator, _ = self.create_simply_scaled_dataset(test_dataset,
data_offset)
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
# Select the right column of the shifted input data to compute the
# expect output.
num_channels = test_dataset.num_input_channels
index = num_channels * (pre_context + data_offset)
expected_output = self.simply_scaled_transform(
input_data[:, index:index+num_channels])
if data_offset < 0:
# Can't predict what we can't see, so force the first few samples to be
# equal.
expected_output[0:-data_offset, :] = output[0:-data_offset, :]
return input_data, output, expected_output, test_dataset
input_data, output, expected_output, test_dataset = create_shifted_test(0)
num_channels = test_dataset.num_input_channels
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
(pre_context + 1 + post_context)*num_channels)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(output.shape[1], 1)
self.assertEqual(expected_output.shape[0], batch_size)
self.assertEqual(expected_output.shape[1], 1)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
input_data, output, expected_output, test_dataset = create_shifted_test(2)
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
(pre_context + 1 + post_context)*num_channels)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(output.shape[1], 1)
self.assertEqual(expected_output.shape[0], batch_size)
self.assertEqual(expected_output.shape[1], 1)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
input_data, output, expected_output, test_dataset = create_shifted_test(-2)
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
(pre_context + 1 + post_context)*num_channels)
self.assertEqual(output.shape[0], batch_size)
self.assertEqual(output.shape[1], 1)
self.assertEqual(expected_output.shape[0], batch_size)
self.assertEqual(expected_output.shape[1], 1)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
@flagsaver.flagsaver
def test_data_count(self):
print('********** test_data_count **************')
repeat_count_request = 3
batch_size_request = 128
test_dataset = decoding.BrainData('input', 'output',
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
next_iterator, _ = self.create_linear_dataset(test_dataset, mode='train')
with tf.compat.v1.Session() as sess:
batch_count = 0
try:
while True:
(eeg, envelope) = sess.run(next_iterator)
batch_count += 1
print('Test dataset returned %d items of size:' % batch_count,
eeg['x'].shape,
envelope.shape)
except tf.errors.OutOfRangeError:
pass
print('batch_count is %d.' % batch_count)
print('Impulse dataset returned %d items of size:' % batch_count,
eeg['x'].shape,
envelope.shape)
self.assertEqual(eeg['x'].shape, (batch_size_request,
test_dataset.num_input_channels))
self.assertEqual(envelope.shape, (batch_size_request, 1))
self.assertEqual(batch_count,
(repeat_count_request * 1000)//batch_size_request)
@flagsaver.flagsaver
def test_regression_tf(self):
"""Test simple (no temporal shift) regression."""
print('\n\n**********test_regression_tf starting... *******')
self.clear_model()
repeat_count_request = 500
batch_size_request = 128
flags.FLAGS.dnn_regressor = 'tf'
test_dataset = decoding.BrainData('input', 'output',
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
self.create_simply_scaled_dataset(test_dataset, mode='train')
model, results = decoding.create_train_estimator(
test_dataset, hidden_units=[40, 20], steps=4000)
print('test_regression_tf.create_train_estimator results:', results)
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['average_loss']
print('Test_regression produced an error of', rms_error)
self.assertLess(rms_error, 0.2)
@flagsaver.flagsaver
def test_regression_fullyconnected(self):
"""Test simple (no temporal shift) regression."""
print('\n\n**********test_regression_fullyconnected starting... *******')
self.clear_model()
repeat_count_request = 300
batch_size_request = 128
flags.FLAGS.dnn_regressor = 'fullyconnected'
test_dataset = decoding.BrainData('input', 'output',
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
self.create_simply_scaled_dataset(test_dataset)
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[100, 40, 20], steps=1000)
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation']
print('Test_regression produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r, .8)
self.assertLess(rms_error, 0.2)
@flagsaver.flagsaver
def test_offset_shifts(self):
"""Simple tests to make sure we can shift the output in time."""
def create_shifted_test(data_offset):
test_dataset = decoding.BrainData('input', 'output',
repeat_count=1,
pre_context=max(-data_offset, 0),
post_context=max(data_offset, 0))
# next_iterator, _ = test_dataset.create_dataset('train')
next_iterator, _ = self.create_simply_scaled_dataset(test_dataset,
data_offset)
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
if data_offset == 0:
expected_output = self.simply_scaled_transform(input_data)
output = output[:, 0]
elif data_offset > 0:
expected_output = self.simply_scaled_transform(
input_data[data_offset:, :])
output = output[0:-data_offset, 0]
else:
expected_output = self.simply_scaled_transform(
input_data[0:data_offset, :])
expected_output = expected_output[-data_offset:, :]
output = output[-data_offset:data_offset, 0]
expected_output = expected_output[:, 0]
print('output:', output.shape, output[0:12])
print('expected_output:', expected_output.shape, expected_output[0:12])
return output, expected_output
print('\n\n**********test_offset_shifts starting... *******')
output, expected_output = create_shifted_test(0)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
output, expected_output = create_shifted_test(2)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
output, expected_output = create_shifted_test(-2)
self.assertLess(np.amax(np.abs(output - expected_output)), 1e-7)
@flagsaver.flagsaver
def test_offset_regression_positive(self):
print('\n\n**********test_offset_regression_positive starting... *******')
self.clear_model()
pre_context = 1 # Limit the number of variables to permit convergence
post_context = 1
print('test_offset_regression_positive contexts:',
pre_context, post_context)
repeat_count_request = 500
batch_size_request = 128
data_offset = 1
flags.FLAGS.dnn_regressor = 'fullyconnected'
num_channels = 1
test_dataset = decoding.BrainData('input', 'output',
repeat_count=repeat_count_request,
final_batch_size=batch_size_request,
pre_context=pre_context,
post_context=post_context)
self.create_simply_scaled_dataset(test_dataset, data_offset=data_offset,
num_input_channels=num_channels)
# Check the size of the dataset outputs.
next_iterator, _ = test_dataset.create_dataset('train')
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
self.assertEqual(input_data.shape[0], batch_size_request)
self.assertEqual(input_data.shape[1],
num_channels*(pre_context + 1 + post_context))
self.assertEqual(output.shape[0], batch_size_request)
self.assertEqual(output.shape[1], 1)
# Check to see if the correct answer (as computed from the input data
# is in the output at the right spot.
print('Input:', input_data[0:6, :])
print('Output:', output[0:6, :])
index = num_channels*pre_context + data_offset
expected_output = self.simply_scaled_transform(
input_data[:, index:index + 1])
print('Expected Output:', expected_output[0:6, :])
difference = output != expected_output
self.assertEqual(difference.shape[1], 1)
# Some frames are bad because they are at the beginning or end of the batch.
# We look for 0.0 since the frames are shuffled, and we have no other way
# of finding them.
good_frames = np.nonzero(expected_output[:, 0] != 0.0)
np.testing.assert_equal(output[good_frames, 0],
expected_output[good_frames, 0])
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[50, 20, 20], steps=2000)
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation']
print('Test_offset_regression_positive produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r, .70)
@flagsaver.flagsaver
def test_offset_regression_negative(self):
print('\n\n**********test_offset_regression_positive starting... *******')
self.clear_model()
pre_context = 1 # Limit the number of variables to permit convergence
post_context = 1
print('test_offset_regression_negative contexts:',
pre_context, post_context)
repeat_count_request = 500
batch_size_request = 128
data_offset = -1
flags.FLAGS.dnn_regressor = 'fullyconnected'
num_channels = 1
test_dataset = decoding.BrainData('input', 'output',
repeat_count=repeat_count_request,
final_batch_size=batch_size_request,
pre_context=pre_context,
post_context=post_context)
self.create_simply_scaled_dataset(test_dataset, data_offset=data_offset,
num_input_channels=num_channels)
# Check the size of the dataset inputs and outputs.
next_iterator, _ = test_dataset.create_dataset('train')
with tf.compat.v1.Session() as sess:
(input_data, output) = sess.run(next_iterator)
input_data = input_data['x']
self.assertEqual(input_data.shape[0], batch_size_request)
self.assertEqual(input_data.shape[1],
num_channels*(pre_context + 1 + post_context))
self.assertEqual(output.shape[0], batch_size_request)
self.assertEqual(output.shape[1], 1)
# Check to see if the correct answer (as computed from the input data
# is in the output at the right spot.
print('Input:', input_data[0:6, :])
print('Output:', output[0:6, :])
index = num_channels*pre_context + data_offset
expected_output = self.simply_scaled_transform(
input_data[:, index:index + 1])
print('Expected Output:', expected_output[0:6, :])
difference = output != expected_output
self.assertEqual(difference.shape[1], 1)
# Some frames are bad because they are at the beginning or end of the batch.
# We look for 0.0 since the frames are shuffled, and we have no other way
# of finding them.
good_frames = np.nonzero(expected_output[:, 0] != 0.0)
np.testing.assert_equal(output[good_frames, 0],
expected_output[good_frames, 0])
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[50, 20, 20], steps=2000)
metrics = decoding.evaluate_performance(test_dataset, model)
print('The returned metrics are:', metrics)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation']
print('Test_offset_regression_negative produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r, .70)
########################## Simple IIR Dataset ############################
def create_simple_iir_dataset(self, dataset, num_input_channels=1,
mode='test'):
"""Given a pre-created generic dataset, load it with IIR data."""
num_samples = 1000000
input_data = np.random.randn(num_samples + 1,
num_input_channels).astype(np.float32)
output_data = 0.4 * input_data[0:-1,] + 0.6 * input_data[1:, :]
dataset.preserve_test_data(input_data[1:num_samples + 1, :], output_data)
return dataset.create_dataset(mode=mode)
@flagsaver.flagsaver
def test_simple_iir_regression32(self):
"""Test simple (two time impulse response) regression."""
print('\n\n**********test_simple_regression32 starting... *******')
self.clear_model()
repeat_count_request = 300
batch_size_request = 128
flags.FLAGS.dnn_regressor = 'fullyconnected'
test_dataset = decoding.BrainData('input', 'output',
pre_context=32,
post_context=0,
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
self.create_simple_iir_dataset(test_dataset, num_input_channels=1)
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[100, 40, 20], steps=400)
print('test_simple_regression32: evaluating the regressor.')
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation']
print('Test_regression produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r, .90)
self.assertLess(rms_error, 0.025)
@flagsaver.flagsaver
def test_simple_iir_regression0(self):
"""Test simple (two time impulse response) regression.
Shouldn't do as well as the regression32 above, as there is not enough
context.
"""
print('\n\n**********test_simple_regression0 starting... *******')
self.clear_model()
repeat_count_request = 300
batch_size_request = 128
flags.FLAGS.dnn_regressor = 'fullyconnected'
test_dataset = decoding.BrainData('input', 'output',
pre_context=0,
post_context=0,
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
self.create_simple_iir_dataset(test_dataset, num_input_channels=1)
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[100, 40, 20], steps=400)
print('test_simple_regression0: finished training the regressor.')
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation']
print('Test_regression produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r, .80)
################## Simulated EEG Data ################################
# Simulated EEG data, similar to the one in the Telluride Decoding Toolbox.
# Single random speech envelope, and then a simulated EEG
# response different for each channel, is convolved with the speech envelope.
# No noise so should be perfect reconstruction.
def create_simulated_impulse_responses(self, num_input_channels,
simulated_unattended_gain=0.10):
"""Create the basic impulse responses for this dataset.
Generate random responses, one for the attended signal and the other for
the unattended signal. Give them a realistic overall shape over 250ms.
Do this once for a dataset (so we can generate multiple examples later
using the same impulse responses).
Args:
num_input_channels: How many input channels to synthesize
simulated_unattended_gain: How much lower is the unattended channel?
Creates:
attended_impulse_response, unattended_impulse_response:
Two 0.25s x num_input_channel arrays representing the impulse response
from the input sound (i.e. speech) to the system (i.e. EEG/meg)
response.
"""
self.impulse_length = .25 # Length of the TRF
self.impulse_times = np.arange(self.impulse_length*self.fs) / self.fs
self.envelope = 30*self.impulse_times * np.exp(-self.impulse_times*30,
dtype=np.float32)
self.envelope_all_chans = numpy.matlib.repmat(np.reshape(self.envelope,
(-1, 1)),
1, num_input_channels)
self.attended_impulse_response = np.random.randn(
self.impulse_times.shape[0],
num_input_channels) * self.envelope_all_chans
self.unattended_impulse_response = np.random.randn(
self.impulse_times.shape[0],
num_input_channels) * self.envelope_all_chans
# Cut the magnitude of the unattended inpulse response so as noise it will
# have a smaller or bigger effect.
print('SimulatedData:initialize_dataset: Setting unattended gain to',
simulated_unattended_gain)
self.unattended_impulse_response *= simulated_unattended_gain
def create_simulated_speech_signals(self):
"""Create the source signals for our experiment, attended and unattended.
Now we create the "speech" signal, which will convolved with the EEG
responses to create the data for this trial. Create speaker 1 and 2 signals.
Creates:
audio_signals: the N x 2 array of attended and unattended "speech"
signals.
"""
if self.use_sinusoids:
self.audio_subj_1 = np.reshape(np.sin(self.recording_times*2*np.pi*5),
(-1, 1))
self.audio_subj_2 = np.reshape(np.sin(self.recording_times*2*np.pi*7),
(-1, 1))
self.audio_signals = np.concatenate((self.audio_subj_1,
self.audio_subj_2),
axis=1)
else:
# Create the signal with noise, and then linearly upsample so the result
# is more low pass.
num_output_channels = 2
self.audio_low_freq = np.random.randn(math.ceil(len(self.recording_times)/
10.0),
num_output_channels)
self.audio_signals = scipy.signal.resample(self.audio_low_freq,
len(self.recording_times))
print('SimulatedData: audio signals shape:', self.audio_signals.shape)
def create_simulated_eeg_data(self, dataset, num_input_channels,
mode, simulated_noise_level=0.3):
"""Create one trial's worth of data.
We have precomputed impulse responses
so generate a "speech" signal, and convolve the EEG impulse responses with
it.
Args:
dataset: The BrainData dataset for which to create data
num_input_channels: How many input channels to generate
mode: Mostly ignored unless you ask for "demo" when then generates a
signal which oscillates between the two speakers.
simulated_noise_level: How much noise to add for simulation.
Returns:
A TF dataset with the input and output data.
"""
assert isinstance(dataset, decoding.BrainData)
assert num_input_channels > 0
self.signal_length = 1000 # Seconds
self.fs = 100 # Audio and EEG sample rate in Hz
self.use_sinusoids = 1 # Random or sinusoidal driving signal
self.create_simulated_impulse_responses(num_input_channels)
self.recording_times = np.arange(self.signal_length*self.fs)/float(self.fs)
self.create_simulated_speech_signals()
if mode.startswith('demo'):
# Create the attention signal, switching every attention_duration seconds
self.attention_duration = 25 # Time in seconds listening to each signal
self.attention_signal = np.mod(
np.floor(self.recording_times / self.attention_duration), 2)
# This signal flips between 0 and 1, every attentionuration seconds
a = np.reshape(self.attention_signal, (-1, 1))
else:
# Attention signal is constant, appropriate for testing.
a = np.ones((self.recording_times.shape[0], 1), dtype=np.float32)
self.attention_matrix = np.concatenate((1-a, a), axis=1)
# Create the signals that correspond to the attended and unattended audio,
# under control of the deterministic attention_signal created above.
self.attended_audio = np.sum(self.attention_matrix * self.audio_signals,
axis=1).astype(np.float32)
self.unattended_audio = np.sum((1 - self.attention_matrix) *
self.audio_signals,
axis=1).astype(np.float32)
# Now convolve the attended and unattended audio with the two different
# impulse responses to create the simulated EEG signals.
print('Creating an example of the SimulatedData....')
response = np.zeros((self.attended_audio.shape[0] +
self.attended_impulse_response.shape[0] - 1,
num_input_channels), dtype=np.float32)
for c in range(num_input_channels):
attended_response = np.convolve(self.attended_audio,
self.attended_impulse_response[:, c],
mode='full')
unattended_response = np.convolve(self.unattended_audio,
self.unattended_impulse_response[:, c],
mode='full')
# Sum up the attended and unattended response, and then add noise.
response[:, c] = (
attended_response + unattended_response +
simulated_noise_level * np.random.randn(attended_response.shape[0]))
print('Attended shapes:', self.attended_audio.shape,
self.unattended_audio.shape)
both_audio_channels = np.concatenate((np.reshape(self.attended_audio,
(-1, 1)),
np.reshape(self.unattended_audio,
(-1, 1))),
axis=1)
print('Both_audio_channels shape:', both_audio_channels.shape)
dataset.preserve_test_data(response[0:self.attended_audio.shape[0],
0:num_input_channels],
both_audio_channels)
return dataset.create_dataset(mode=mode)
@flagsaver.flagsaver
def test_simulated_regression(self):
"""Test simulated eeg regression.
This test starts with both attended and unattended audio, so we test the
reconstruction accuracy of both signals.
"""
print('\n\n**********test_simulated_regression starting... *******')
self.clear_model()
repeat_count_request = 500
batch_size_request = 128
flags.FLAGS.dnn_regressor = 'fullyconnected'
num_input_channels = 32
test_dataset = decoding.BrainData('input', 'output',
pre_context=32,
post_context=0,
repeat_count=repeat_count_request,
final_batch_size=batch_size_request)
self.create_simulated_eeg_data(test_dataset, num_input_channels,
mode='train')
model, _ = decoding.create_train_estimator(
test_dataset, hidden_units=[40, 20], steps=4000)
metrics = decoding.evaluate_performance(test_dataset, model)
rms_error = metrics['test/mse']
r = metrics['test/pearson_correlation_matrix']
print('Test_simualted_regression produced an error of', rms_error,
'and a correlation of', r)
self.assertGreater(r[0, 2], 0.90) # Attended reconstruction
self.assertGreater(r[1, 3], 0.00) # Unattended reconstruction
self.assertGreater(r[0, 2], r[1, 3]) # Attended better than unattended
@flagsaver.flagsaver
def test_generic_read(self):
"""Test to see if we can parse a specific TFRecord data file."""
self.longMessage = True # For the asserts pylint: disable=invalid-name
all_files = []
for (path, _, files) in tf.io.gfile.walk(self._test_data):
all_files += [path + '/' + f for f in files if f.endswith('.tfrecords')]
self.assertNotEmpty(all_files)
mandatory_feature_sizes = {'envelope': (1, tf.float32),
'phonetic_features': (19, tf.float32),
'phonemes': (38, tf.float32),
'meg': (148, tf.float32),
'mel_spectrogram': (64, tf.float32),
}
features = decoding.discover_feature_shapes(all_files[0])
for k in mandatory_feature_sizes:
expected_size, expected_type = mandatory_feature_sizes[k]
self.assertIn(k, features, 'looking for feature ' + k)
self.assertEqual(expected_size, features[k].shape[0],
'testing size of feature ' + k)
self.assertEqual(expected_type, features[k].dtype,
'testing type of feature ' + k)
@flagsaver.flagsaver
def test_generic_processing(self):
"""Test reading the Generic TFRecord data. Duplicates Rotman test.
"""
print('********** test_generic_processing **************')
batch_size = 128
pre_context = 0
post_context = 0
flags.FLAGS.tfexample_dir = self._test_data
def get_one_element(input_feature, output_feature):
test_dataset = decoding.TFExampleData(input_feature, output_feature,
final_batch_size=batch_size,
pre_context=pre_context,
post_context=post_context,
repeat_count=10)
next_iterator, _ = test_dataset.create_dataset('test') # No shuffling
with tf.compat.v1.Session() as sess:
(input_data, output_data) = sess.run(next_iterator)
input_data = input_data['x']
return test_dataset, input_data, output_data
input_feature = 'mel_spectrogram'
output_feature = 'envelope'
test_dataset, input_data, output_data = get_one_element(input_feature,
output_feature)
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
test_dataset.features[input_feature].shape[0])
self.assertTrue(np.all(input_data >= 0.0))
self.assertEqual(output_data.shape[0], batch_size)
self.assertEqual(output_data.shape[1],
test_dataset.features[output_feature].shape[0])
self.assertTrue(np.all(output_data >= 0.0))
input_feature = 'phonemes'
output_feature = 'phonetic_features'
test_dataset, input_data, output_data = get_one_element(input_feature,
output_feature)
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
test_dataset.features[input_feature].shape[0])
# Make sure input data (phonemes) is binary
self.assertTrue(np.all(np.logical_or(input_data == 0, input_data == 1)))
self.assertEqual(output_data.shape[0], batch_size)
self.assertEqual(output_data.shape[1],
test_dataset.features[output_feature].shape[0])
# Make sure output data (phonetic features) is binary
self.assertTrue(np.all(np.logical_or(output_data == 0, output_data == 1)))
input_feature = 'meg'
output_feature = 'envelope'
test_dataset, input_data, output_data = get_one_element(input_feature,
output_feature)
self.assertEqual(input_data.shape[0], batch_size)
self.assertEqual(input_data.shape[1],
test_dataset.features[input_feature].shape[0])
# Already checked envelope, so we don't need to do it again.
@flagsaver.flagsaver
def test_linear_regression(self):
# First test the basic linear regressor parameters using fixed weight and
# bias vectors.
desired_sample_count = 1000
w_true = [[1, 3], [2, 4]]
b_true = [[5, 6]]
x_train = np.random.rand(desired_sample_count, 2).astype(np.float32)
y_train = np.matmul(x_train, np.array(w_true)) + np.array(b_true)
dataset = tf.data.Dataset.from_tensor_slices(({'x': x_train},
y_train))
dataset = dataset.batch(100).repeat(count=1)
(w_estimate,
b_estimate,
_, _) = decoding.calculate_regressor_parameters_from_dataset(
dataset, lamb=0.0, use_offset=True)
print('Estimated w:', w_estimate)
print('Estimated b:', b_estimate)
self.assertTrue(np.allclose(w_true, w_estimate, atol=1e-05))
self.assertTrue(np.allclose(b_true, b_estimate, atol=1e-05))
(average_error,
_,
_,
num_samples) = decoding.evaluate_regressor_from_dataset(
w_estimate, b_estimate, dataset)
self.assertLess(average_error, 1e-10)
self.assertEqual(num_samples, desired_sample_count)
# Now redo the test without the offset, and make sure the error is large.
(w_estimate,
b_estimate,
_, _) = decoding.calculate_regressor_parameters_from_dataset(
dataset, lamb=0.0, use_offset=False)
print('Estimated w:', w_estimate)
print('Estimated b:', b_estimate)
# w will be different because the model no longer fits.
# self.assertTrue(np.allclose(w_true, w_estimate, atol=1e-05))
self.assertTrue(np.allclose(0.0, b_estimate, atol=1e-05))