-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathlayers.py
81 lines (54 loc) · 2.27 KB
/
layers.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
# A Wavenet For Source Separation - Francesc Lluis - 25.10.2018
# Layers.py
import keras
class AddSingletonDepth(keras.layers.Layer):
def call(self, x, mask=None):
x = keras.backend.expand_dims(x, -1) # add a dimension of the right
if keras.backend.ndim(x) == 4:
return keras.backend.permute_dimensions(x, (0, 3, 1, 2))
else:
return x
def compute_output_shape(self, input_shape):
if len(input_shape) == 3:
return input_shape[0], 1, input_shape[1], input_shape[2]
else:
return input_shape[0], input_shape[1], 1
class Subtract(keras.layers.Layer):
def __init__(self, **kwargs):
super(Subtract, self).__init__(**kwargs)
def call(self, x, mask=None):
return x[0] - x[1]
def compute_output_shape(self, input_shape):
return input_shape[0]
class Add(keras.layers.Layer):
def __init__(self, **kwargs):
super(Add, self).__init__(**kwargs)
def call(self, x, mask=None):
output = x[0]
for i in range(1, len(x)):
output += x[i]
return output
def compute_output_shape(self, input_shape):
return input_shape[0]
class Slice(keras.layers.Layer):
def __init__(self, selector, output_shape, **kwargs):
self.selector = selector
self.desired_output_shape = output_shape
super(Slice, self).__init__(**kwargs)
def call(self, x, mask=None):
selector = self.selector
if len(self.selector) == 2 and not type(self.selector[1]) is slice and not type(self.selector[1]) is int:
x = keras.backend.permute_dimensions(x, [0, 2, 1])
selector = (self.selector[1], self.selector[0])
y = x[selector]
if len(self.selector) == 2 and not type(self.selector[1]) is slice and not type(self.selector[1]) is int:
y = keras.backend.permute_dimensions(y, [0, 2, 1])
return y
def compute_output_shape(self, input_shape):
output_shape = (None,)
for i, dim_length in enumerate(self.desired_output_shape):
if dim_length == Ellipsis:
output_shape = output_shape + (input_shape[i+1],)
else:
output_shape = output_shape + (dim_length,)
return output_shape