-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwavenet.py
881 lines (804 loc) · 37.5 KB
/
wavenet.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
import tensorflow as tf
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import Conv1D, Conv2D, Input, Add
from tensorflow.keras.layers import Activation, Lambda, Dense, Dropout
from tensorflow.keras.layers import BatchNormalization, Flatten
from tensorflow.keras.layers import AveragePooling2D, AveragePooling1D
from tensorflow.keras.layers import SeparableConv2D, Concatenate
from tensorflow.keras.layers import DepthwiseConv2D
from tensorflow.keras.regularizers import l2
from tensorflow import keras
class DilatedBlock(Model):
"""
Creates a single causal dilated convolution layer
|-> [gate] -| |-> 1x1 conv -> skip output
| |-> (*) -|
input -|-> [filter] -| |-> 1x1 conv -|
| |-> (+) -> dense output
|------------------------------------|
"""
def __init__(self, dilation, output_width, residual_channels,
dilation_channels, skip_channels, use_biases, regularizer,
last_layer, **kwargs):
super(DilatedBlock, self).__init__(**kwargs)
self.output_width = output_width
self.conv_filter = Conv1D(dilation_channels,
2,
dilation_rate=dilation,
padding='causal',
activation='tanh',
use_bias=use_biases,
kernel_regularizer=l2(l=regularizer),
bias_regularizer=l2(l=regularizer))
self.conv_gate = Conv1D(dilation_channels,
2,
dilation_rate=dilation,
padding='causal',
activation='sigmoid',
use_bias=use_biases,
kernel_regularizer=l2(l=regularizer),
bias_regularizer=l2(l=regularizer))
self.transformed = Conv1D(residual_channels,
1,
padding='same',
use_bias=use_biases,
kernel_regularizer=l2(l=regularizer),
bias_regularizer=l2(l=regularizer))
self.skip_contribution = Conv1D(skip_channels,
1,
padding='same',
use_bias=use_biases,
kernel_regularizer=l2(l=regularizer),
bias_regularizer=l2(l=regularizer))
self.last_layer = last_layer
def call(self, inputs, training=None):
if self.last_layer:
# [b, sample, residual_channels]
filters = self.conv_filter(inputs)
gates = self.conv_gate(inputs)
out = filters * gates
# The 1x1 conv to produce the skip output
skip_cut = tf.shape(out)[1] - self.output_width
out_skip = tf.slice(out, [0, skip_cut, 0], [-1, -1, -1])
skip_contribution = self.skip_contribution(out_skip)
return skip_contribution
else:
# [b, sample, residual_channels]
filters = self.conv_filter(inputs)
gates = self.conv_gate(inputs)
out = filters * gates
# The 1x1 conv to produce the residual output
transformed = self.transformed(out)
# The 1x1 conv to produce the skip output
skip_cut = tf.shape(out)[1] - self.output_width
out_skip = tf.slice(out, [0, skip_cut, 0], [-1, -1, -1])
skip_contribution = self.skip_contribution(out_skip)
return skip_contribution, inputs + transformed
class WaveNet(Model):
'''Implements the WaveNet network for generative audio.
Usage (with the architecture as in the DeepMind paper):
dilations = [2**i for i in range(N)] * M
filter_width = 2 # Convolutions just use 2 samples.
residual_channels = 16 # Not specified in the paper.
dilation_channels = 32 # Not specified in the paper.
skip_channels = 16 # Not specified in the paper.
'''
def __init__(self, batch_size, dilations, filter_width, signal_length,
residual_channels, dilation_channels, skip_channels,
quantization_channels, use_biases, regularizer):
'''Initializes the WaveNet model.
Args:
batch_size: How many audio files are supplied per batch
(recommended: 1).
dilations: A list with the dilation factor for each layer.
filter_width: The samples that are included in each convolution,
after dilating.
signal_length: The length of input wave.
residual_channels: How many filters to learn for the residual.
dilation_channels: How many filters to learn for the dilated
convolution.
skip_channels: How many filters to learn that contribute to the
quantized softmax output.
quantization_channels: How many amplitude values to use for audio
quantization and the corresponding one-hot encoding.
Default: 256 (8-bit quantization).
use_biases: Whether to add a bias layer to each convolution.
Default: False.
regularizer: Regularzation weight
TODO:
scalar_input: Whether to use the quantized waveform directly as
input to the network instead of one-hot encoding it.
Default: False.
initial_filter_width: The width of the initial filter of the
convolution applied to the scalar input. This is only relevant
if scalar_input=True.
global_condition_channels: Number of channels in (embedding
size) of global conditioning vector. None indicates there is
no global conditioning.
global_condition_cardinality: Number of mutually exclusive
categories to be embedded in global condition embedding. If
not None, then this implies that global_condition tensor
specifies an integer selecting which of the N global condition
categories, where N = global_condition_cardinality. If None,
then the global_condition tensor is regarded as a vector which
must have dimension global_condition_channels.
'''
super(WaveNet, self).__init__()
self.batch_size = batch_size
self.dilations = dilations
self.filter_width = filter_width
self.residual_channels = residual_channels
self.dilation_channels = dilation_channels
self.skip_channels = skip_channels
self.quantization_channels = quantization_channels
self.use_biases = use_biases
self.regularizer = regularizer
self.signal_length = signal_length
self.receptive_field = WaveNet.calculate_receptive_field(
self.filter_width, self.dilations)
self.output_width = WaveNet.calculate_output_width(
self.signal_length, self.receptive_field)
self.pre_block = self._build_preprocess_block()
self.residual_blocks = self._build_residual_blocks()
self.post_block = self._build_postprocess_block()
@staticmethod
def calculate_receptive_field(filter_width, dilations):
return (filter_width - 1) * sum(dilations) + filter_width
@staticmethod
def calculate_output_width(signal_length, receptive_field):
return signal_length - receptive_field + 1
def _build_preprocess_block(self):
pre_block = Sequential()
pre_block.add(
Conv1D(self.residual_channels,
self.filter_width,
padding='causal',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)))
return pre_block
def _build_residual_blocks(self):
outputs = []
# Add all defined dilation layers.
inputs = Input(shape=(self.signal_length, self.residual_channels))
current_layer = inputs
for i, dilation in enumerate(self.dilations):
if i == len(self.dilations) - 1:
output = DilatedBlock(dilation, self.output_width,
self.residual_channels,
self.dilation_channels,
self.skip_channels, self.use_biases,
self.regularizer, True)(current_layer)
else:
output, current_layer = DilatedBlock(
dilation, self.output_width, self.residual_channels,
self.dilation_channels, self.skip_channels,
self.use_biases, self.regularizer, False)(current_layer)
outputs.append(output)
outputs = Add()(outputs)
return Model(inputs, outputs)
def _build_postprocess_block(self):
post_block = Sequential()
post_block.add(Activation('relu'))
post_block.add(
Conv1D(self.skip_channels,
1,
padding='same',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer),
activation='relu'))
post_block.add(
Conv1D(self.quantization_channels,
1,
padding='same',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)))
# post_block.add(Activation('softmax'))
return post_block
def call(self, inputs, training=None):
x = self.pre_block(inputs, training=training)
x = self.residual_blocks(x, training=training)
x = self.post_block(x, training=training)
return x
class EEGWaveNetv1(Model):
'''
Implements the WaveNet network for EEG classification.
The shape of inputs must be [batch_size, signal_length, data_channels, 1].
Set tensorflow data format as channle last
'''
def __init__(self, signal_length, data_channels, dilations, filter_width,
residual_channels, dilation_channels, skip_channels,
use_biases, regularizer):
'''
Initializes the EEGWaveNet model.
Args:
signal_length: How long of raw data.
data_channels: How many channels of raw data.
dilations: A list with the dilation factor for each layer.
filter_width: The samples that are included in each convolution,
after dilating.
residual_channels: How many filters to learn for the residual.
dilation_channels: How many filters to learn for the dilated
convolution.
skip_channels: How many filters to learn that contribute to the
quantized softmax output.
use_biases: Whether to add a bias layer to each convolution.
Default: False.
regularizer: Regularzation weight
'''
super(EEGWaveNetv1, self).__init__()
self.signal_length = signal_length
self.data_channels = data_channels
self.dilations = dilations
self.filter_width = filter_width
self.residual_channels = residual_channels
self.dilation_channels = dilation_channels
self.skip_channels = skip_channels
self.use_biases = use_biases
self.regularizer = regularizer
self.pre_block = self._build_preprocess_block()
self.residual_blocks = self._build_residual_blocks()
self.post_block = self._build_postprocess_block()
def _build_preprocess_block(self):
# [batch_size, data_channels, signal_length, 1]
pre_block = Sequential(
[
Input((self.data_channels, self.signal_length, 1)),
Conv2D(self.residual_channels, (1, self.filter_width),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
# [batch_size, data_channels, signal_length, residual_channels]
Conv2D(self.residual_channels, (self.data_channels, 1),
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(axis=-1),
Activation('elu'),
# [batch_size, 1, signal_length, residual_channels]
Lambda(tf.squeeze, arguments=dict(axis=1))
],
name='preprocess_block')
# [batch_size, signal_length, residual_channels]
return pre_block
def _build_residual_blocks(self):
def single_block(inputs):
# [b, sample, residual_channels]
filters = Conv1D(self.dilation_channels,
self.filter_width,
dilation_rate=dilation,
padding='causal',
activation='tanh',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
gates = Conv1D(self.dilation_channels,
self.filter_width,
dilation_rate=dilation,
padding='causal',
activation='sigmoid',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
out = filters * gates
skip_contribution = Conv1D(
self.skip_channels,
1,
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
if last_layer:
return skip_contribution, None
else:
transformed = Conv1D(
self.residual_channels,
1,
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
return skip_contribution, inputs + transformed
outputs = []
# Add all defined dilation layers.
# [batch_size, signal_length, residual_channels]
inputs = Input(shape=(self.signal_length, self.residual_channels))
current_layer = inputs
for i, dilation in enumerate(self.dilations):
last_layer = (i == (len(self.dilations) - 1))
output, current_layer = single_block(current_layer)
outputs.append(output)
outputs = Add()(outputs)
# [batch_size, signal_length, skip_channels]
return Model(inputs, outputs, name='residual_blocks')
def _build_postprocess_block(self):
post_block = Sequential([
Input((self.signal_length, self.skip_channels)),
BatchNormalization(),
Activation('elu'),
Dropout(0.5),
Conv1D(16,
1,
padding='same',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
Dropout(0.5),
AveragePooling1D(pool_size=4),
Conv1D(8,
3,
padding='valid',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
Dropout(0.5),
AveragePooling1D(pool_size=4),
Conv1D(4,
1,
padding='same',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
Flatten(),
Dense(2,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))
])
return post_block
def call(self, inputs, training=None):
x = self.pre_block(inputs, training=training)
x = self.residual_blocks(x, training=training)
x = self.post_block(x, training=training)
return x
class EEGWaveNetv2(Model):
'''
Implements the WaveNet network for EEG classification.
The shape of inputs must be [batch_size, signal_length, data_channels, 1].
Set tensorflow data format as channle last
'''
def __init__(self, signal_length, data_channels, dilations, filter_width,
residual_channels, dilation_channels, skip_channels,
use_biases, regularizer):
'''
Initializes the EEGWaveNet model.
Args:
signal_length: How long of raw data.
data_channels: How many channels of raw data.
dilations: A list with the dilation factor for each layer.
filter_width: The samples that are included in each convolution,
after dilating.
residual_channels: How many filters to learn for the residual.
dilation_channels: How many filters to learn for the dilated
convolution.
skip_channels: How many filters to learn that contribute to the
quantized softmax output.
use_biases: Whether to add a bias layer to each convolution.
Default: False.
regularizer: Regularzation weight
'''
super(EEGWaveNetv2, self).__init__()
self.signal_length = signal_length
self.data_channels = data_channels
self.dilations = dilations
self.filter_width = filter_width
self.residual_channels = residual_channels
self.dilation_channels = dilation_channels
self.skip_channels = skip_channels
self.use_biases = use_biases
self.regularizer = regularizer
self.pre_block = self._build_preprocess_block()
self.residual_blocks = self._build_residual_blocks()
self.post_block = self._build_postprocess_block()
def _build_preprocess_block(self):
pre_block = Sequential(
[ # [batch_size, data_channels, signal_length, 1]
Input((self.data_channels, self.signal_length, 1)),
Conv2D(self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
# Dropout(0.2),
# [batch_size, data_channels, signal_length, residual_channels]
],
name='preprocess_block')
# [batch_size, signal_length, residual_channels]
return pre_block
def _build_residual_blocks(self):
def single_block(inputs):
# [b, sample, residual_channels]
filters = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='tanh',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
gates = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='sigmoid',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
out = filters * gates
skip_contribution = Conv2D(
self.skip_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
if last_layer:
return skip_contribution, None
else:
transformed = Conv2D(
self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
return skip_contribution, inputs + transformed
outputs = []
# Add all defined dilation layers.
# [batch_size, data_channels, signal_length, residual_channels]
inputs = Input(shape=(self.data_channels, self.signal_length,
self.residual_channels))
current_layer = inputs
for i, dilation in enumerate(self.dilations):
last_layer = (i == (len(self.dilations) - 1))
output, current_layer = single_block(current_layer)
outputs.append(output)
outputs = Add()(outputs)
# [batch_size, data_channels, signal_length, skip_channels * len(dilations)]
return Model(inputs, outputs, name='residual_blocks')
def _build_postprocess_block(self):
post_block = Sequential([
Input(
(self.data_channels, self.signal_length, self.skip_channels)),
BatchNormalization(),
Activation('elu'),
# Dropout(0.2),
Conv2D(self.skip_channels * 2, (1, 1),
padding='same',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
# Dropout(0.2),
AveragePooling2D(pool_size=(1, 8)),
Conv2D(self.skip_channels * 4, (self.data_channels, 3),
padding='valid',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
# Dropout(0.2),
Flatten(),
Dense(200,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
Dropout(0.2),
Dense(2,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))
])
return post_block
def call(self, inputs, training=None):
x = self.pre_block(inputs, training=training)
x = self.residual_blocks(x, training=training)
x = self.post_block(x, training=training)
return x
class EEGWaveNetv3(Model):
'''
Implements the WaveNet network for EEG classification.
The shape of inputs must be [batch_size, signal_length, data_channels, 1].
Set tensorflow data format as channle last
'''
def __init__(self, signal_length, data_channels, dilations, filter_width,
residual_channels, dilation_channels, skip_channels,
use_biases, regularizer):
'''
Initializes the EEGWaveNet model.
Args:
signal_length: How long of raw data.
data_channels: How many channels of raw data.
dilations: A list with the dilation factor for each layer.
filter_width: The samples that are included in each convolution,
after dilating.
residual_channels: How many filters to learn for the residual.
dilation_channels: How many filters to learn for the dilated
convolution.
skip_channels: How many filters to learn that contribute to the
quantized softmax output.
use_biases: Whether to add a bias layer to each convolution.
Default: False.
regularizer: Regularzation weight
'''
super(EEGWaveNetv3, self).__init__()
self.signal_length = signal_length
self.data_channels = data_channels
self.dilations = dilations
self.filter_width = filter_width
self.residual_channels = residual_channels
self.dilation_channels = dilation_channels
self.skip_channels = skip_channels
self.use_biases = use_biases
self.regularizer = regularizer
self.pre_block = self._build_preprocess_block()
self.residual_blocks = self._build_residual_blocks()
self.post_block = self._build_postprocess_block()
def _build_preprocess_block(self):
pre_block = Sequential(
[ # [batch_size, data_channels, signal_length, 1]
Input((self.data_channels, self.signal_length, 1)),
Conv2D(self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
Dropout(0.2),
# [batch_size, data_channels, signal_length, residual_channels]
],
name='preprocess_block')
# [batch_size, signal_length, residual_channels]
return pre_block
def _build_residual_blocks(self):
def single_block(inputs):
# [b, sample, residual_channels]
filters = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='tanh',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
gates = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='sigmoid',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
out = filters * gates
skip_contribution = Conv2D(
self.skip_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
if last_layer:
return skip_contribution, None
else:
transformed = Conv2D(
self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
return skip_contribution, inputs + transformed
outputs = []
# Add all defined dilation layers.
# [batch_size, data_channels, signal_length, residual_channels]
inputs = Input(shape=(self.data_channels, self.signal_length,
self.residual_channels))
current_layer = inputs
for i, dilation in enumerate(self.dilations):
last_layer = (i == (len(self.dilations) - 1))
output, current_layer = single_block(current_layer)
outputs.append(output)
outputs = Concatenate()(outputs)
# [batch_size, data_channels, signal_length, skip_channels * len(dilations)]
return Model(inputs, outputs, name='residual_blocks')
def _build_postprocess_block(self):
post_block = Sequential([
Input((self.data_channels, self.signal_length,
self.skip_channels * len(self.dilations))),
BatchNormalization(),
Activation('elu'),
Dropout(0.2),
DepthwiseConv2D((self.data_channels, 1),
use_bias=self.use_biases,
depthwise_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
AveragePooling2D((1, 4)),
Dropout(0.2),
SeparableConv2D(self.skip_channels * len(self.dilations) * 2,
(1, 3),
padding='valid',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
AveragePooling2D((1, 8)),
Dropout(0.2),
Flatten(),
# Dense(200,
# kernel_regularizer=l2(l=self.regularizer),
# bias_regularizer=l2(l=self.regularizer)),
# BatchNormalization(),
# Activation('elu'),
# Dropout(0.2),
Dense(2,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))
])
return post_block
def call(self, inputs, training=None):
x = self.pre_block(inputs, training=training)
x = self.residual_blocks(x, training=training)
x = self.post_block(x, training=training)
return x
class EEGWaveNetv4(Model):
'''
Implements the WaveNet network for EEG classification.
The shape of inputs must be [batch_size, signal_length, data_channels, 1].
Set tensorflow data format as channle last
'''
def __init__(self, signal_length, data_channels, dilations, filter_width,
residual_channels, dilation_channels, skip_channels,
use_biases, regularizer):
'''
Initializes the EEGWaveNet model.
Args:
signal_length: How long of raw data.
data_channels: How many channels of raw data.
dilations: A list with the dilation factor for each layer.
filter_width: The samples that are included in each convolution,
after dilating.
residual_channels: How many filters to learn for the residual.
dilation_channels: How many filters to learn for the dilated
convolution.
skip_channels: How many filters to learn that contribute to the
quantized softmax output.
use_biases: Whether to add a bias layer to each convolution.
Default: False.
regularizer: Regularzation weight
'''
super(EEGWaveNetv4, self).__init__()
self.signal_length = signal_length
self.data_channels = data_channels
self.dilations = dilations
self.filter_width = filter_width
self.residual_channels = residual_channels
self.dilation_channels = dilation_channels
self.skip_channels = skip_channels
self.use_biases = use_biases
self.regularizer = regularizer
self.pre_block = self._build_preprocess_block()
self.residual_blocks = self._build_residual_blocks()
self.post_block = self._build_postprocess_block()
def _build_preprocess_block(self):
pre_block = Sequential(
[ # [batch_size, data_channels, signal_length, 1]
Input((self.data_channels, self.signal_length, 1)),
Conv2D(self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
Dropout(0.5),
# [batch_size, data_channels, signal_length, residual_channels]
],
name='preprocess_block')
# [batch_size, signal_length, residual_channels]
return pre_block
def _build_residual_blocks(self):
def single_block(inputs):
# [b, sample, residual_channels]
filters = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='tanh',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
gates = Conv2D(self.dilation_channels, (1, self.filter_width),
dilation_rate=dilation,
padding='same',
activation='sigmoid',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(inputs)
out = filters * gates
skip_contribution = Conv2D(
self.skip_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
if last_layer:
return skip_contribution, None
else:
transformed = Conv2D(
self.residual_channels, (1, 1),
padding='same',
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))(out)
return skip_contribution, inputs + transformed
outputs = []
# Add all defined dilation layers.
# [batch_size, data_channels, signal_length, residual_channels]
inputs = Input(shape=(self.data_channels, self.signal_length,
self.residual_channels))
current_layer = inputs
for i, dilation in enumerate(self.dilations):
last_layer = (i == (len(self.dilations) - 1))
output, current_layer = single_block(current_layer)
outputs.append(output)
outputs = Concatenate()(outputs)
# [batch_size, data_channels, signal_length, skip_channels * len(dilations)]
return Model(inputs, outputs, name='residual_blocks')
def _build_postprocess_block(self):
post_block = Sequential([
Input((self.data_channels, self.signal_length,
self.skip_channels * len(self.dilations))),
BatchNormalization(),
Activation('elu'),
Dropout(0.5),
DepthwiseConv2D((self.data_channels, 1),
use_bias=self.use_biases,
depthwise_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
AveragePooling2D((1, 4)),
Dropout(0.5),
SeparableConv2D(self.skip_channels * len(self.dilations) * 2,
(1, 7),
padding='valid',
strides=1,
use_bias=self.use_biases,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer)),
BatchNormalization(),
Activation('elu'),
AveragePooling2D((1, 8)),
Dropout(0.5),
Flatten(),
# Dense(200,
# kernel_regularizer=l2(l=self.regularizer),
# bias_regularizer=l2(l=self.regularizer)),
# BatchNormalization(),
# Activation('elu'),
# Dropout(0.2),
Dense(2,
kernel_regularizer=l2(l=self.regularizer),
bias_regularizer=l2(l=self.regularizer))
])
return post_block
def call(self, inputs, training=None):
x = self.pre_block(inputs, training=training)
x = self.residual_blocks(x, training=training)
x = self.post_block(x, training=training)
return x