-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnn.py
More file actions
359 lines (288 loc) · 9.7 KB
/
nn.py
File metadata and controls
359 lines (288 loc) · 9.7 KB
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
import sys
from copy import deepcopy
from typing import Union
import numpy as np
import numpy.lib.stride_tricks as st
import matplotlib.pyplot as plt
import util
activations = {
'sigmoid': lambda x: 1.0 / (1.0 + np.exp(-x)),
'linear': lambda x: x,
'relu': lambda x: np.maximum(0.0, x),
'tanh': lambda x: np.tanh(x)
}
def convolve_2d(imgs: np.ndarray, k: np.ndarray, stride: int=1):
"""
a: (num, channel, y, x) \\
k: (filter, channel, y, x)
"""
# print()
# print(imgs.shape)
# print(k.shape)
# print(stride)
sa = imgs[0].shape
sk = k.shape
s = stride
so = ((sa[1]-sk[2])//s+1, (sa[2]-sk[3])//s+1)
c_list = np.empty((len(imgs), sk[0], *so))
for num in range(len(imgs)):
a = imgs[num]
sa = a.shape
sta = a.strides
sk = k.shape
so = ((sa[1]-sk[2])//s+1, (sa[2]-sk[3])//s+1)
# print(so)
stride = (sta[1]*s, sta[2]*s, sta[0], sta[1], sta[2])
b = st.as_strided(a, (so[0], so[1], sa[0], sk[2], sk[3]), stride)
# print('b', b.shape)
c = c_list[num]
# print('c', c.shape)
for i in range(len(k)):
ci = np.tensordot(b, k[i], axes=3)
# print(i, ci.shape)
c[i] = np.reshape(ci, (1, *so))
return c_list
def max_pool_2d(a: np.ndarray):
"""
a: (num, channel, y, x)
"""
a00 = a[:,:,0::2,0::2]
a01 = a[:,:,0::2,1::2]
a10 = a[:,:,1::2,0::2]
a11 = a[:,:,1::2,1::2]
out = np.empty((a00.shape))
max_out = out[:,:,:a11.shape[2],:a11.shape[3]]
max_out[:] = np.maximum(
np.maximum(
a00[:,:,:a11.shape[2],:a11.shape[3]],
a01[:,:,:a11.shape[2],:a11.shape[3]]
),
np.maximum(
a10[:,:,:a11.shape[2],:a11.shape[3]],
a11[:,:,:a11.shape[2],:a11.shape[3]]
)
)
if a00.shape[2] == a11.shape[2]:
if a00.shape[3] == a11.shape[3]: # all dimensions good
pass
else: # (y good, x bad)
out[:,:,:,-1] = np.maximum(a00[:,:,:,-1], a10[:,:,:,-1])
else:
if a00.shape[3] == a11.shape[3]: # (y bad, x good)
out[:,:,-1,:] = np.maximum(a00[:,:,-1,:], a01[:,:,-1,:])
else: # (y bad, x bad)
out[:,:,-1,:-1] = np.maximum(a00[:,:,-1,:-1], a01[:,:,-1,:])
out[:,:,:-1,-1] = np.maximum(a00[:,:,:-1,-1], a10[:,:,:,-1])
out[:,:,-1, -1] = a00[:,:,-1,-1]
pass
return out
class Input:
def __init__(self, output_shape: tuple):
self.output_shape = output_shape
self.output = None
class Layer:
def __init__(self):
self._Layer__created = False
self.output = None
def __call__(self, x: Union['Layer', Input, np.ndarray]):
if hasattr(self, '_Layer__created') and self._Layer__created:
self.output = self.eval(x)
return self.output
else:
out = deepcopy(self)
out._Layer__created = True
out.output_shape = out.build(x.output_shape)
out.input = x
return out
def get_config(self):
raise NotImplementedError
def get_weights(self):
raise NotImplementedError
def set_weights(self):
raise NotImplementedError
def build(self, in_shape: tuple):
raise NotImplementedError
def eval(self, x):
raise NotImplementedError
class Dense(Layer):
def __init__(self, nodes: int, activation: str='sigmoid'):
super(Dense, self).__init__()
self.nodes = nodes
self.activation = activation
def build(self, in_shape: tuple):
if len(in_shape) != 1:
raise Exception('Expected input shape to be 1 dimension')
self.W = np.full((in_shape[0], self.nodes), 0, dtype=np.float)
self.b = np.full(self.nodes, 0.0, dtype=np.float)
self.a = activations[self.activation]
return (self.nodes,)
def eval(self, x):
# print("Eval: {}".format(x))
return self.a(np.dot(x, self.W) + self.b)
def get_weights(self):
return [np.copy(self.W), np.copy(self.b)]
def set_weights(self, weights):
self.W[:] = weights[0]
self.b[:] = weights[1]
def get_config(self):
return {
'nodes': self.nodes,
'activation': self.activation
}
class Conv2D(Layer):
def __init__(self, filters: int, size: int, padding: str='same', stride: int=1, activation: str='linear'):
super(Conv2D, self).__init__()
self.filters = filters
self.size = size
self.padding = padding
self.stride = stride
self.activation = activation
if padding == 'same' and stride > 1:
raise Exception("Same padding and stride > 1 is not currently supported")
def build(self, in_shape: tuple):
if len(in_shape) != 3:
raise Exception('Expected input shape to be 2 dimensions')
self.W = np.full((self.filters, in_shape[0], self.size, self.size), 0, dtype=np.float)
self.a = activations[self.activation]
out_shape = None
if self.padding == 'same':
out_shape = (
self.filters,
in_shape[1],
in_shape[2]
)
else:
out_shape = (
self.filters,
(in_shape[1] - self.size) // self.stride + 1,
(in_shape[2] - self.size) // self.stride + 1,
)
self.out_shape = out_shape
# print(self.out_shape)
return out_shape
def eval(self, x):
# return signal.convolve2d(x[0,0,:,:], self.W[0,0,:,:])
# st.as_strided()
if self.padding == 'same':
pass
else:
return self.a(convolve_2d(x, self.W, self.stride))
def get_weights(self):
return [np.copy(self.W)]
def set_weights(self, weights):
self.W[:] = weights[0]
def get_config(self):
return {
'filters': self.filters,
'size': self.size,
'padding': self.padding,
'stride': self.stride,
'activation': self.activation
}
class MaxPool2D(Layer):
def __init__(self):
super(MaxPool2D, self).__init__()
def build(self, in_shape: tuple):
if len(in_shape) != 3:
raise Exception('Expected input shape to be 3 dimension')
return (in_shape[0], int(np.ceil(in_shape[1] / 2)), int(np.ceil(in_shape[2] / 2)))
def eval(self, x):
return max_pool_2d(x)
def get_weights(self):
return []
def set_weights(self, weights):
pass
def get_config(self):
return {}
class Flatten(Layer):
def __init__(self):
super(Flatten, self).__init__()
def build(self, in_shape: tuple):
out_n = 1
for x in in_shape:
out_n *= x
self.out_n = out_n
return (out_n,)
def eval(self, x):
return np.reshape(x, (-1, self.out_n))
def get_weights(self):
return []
def set_weights(self, weights):
pass
def get_config(self):
return {}
def get_all_layers(layer: Layer, out: list=None):
if out is None:
out = []
out.append(layer)
if hasattr(layer, 'input') and not isinstance(layer.input, Input):
get_all_layers(layer.input, out)
return out[::-1]
class Model:
layer_types = {
'Dense': Dense,
'Flatten': Flatten,
'Conv2D': Conv2D,
'MaxPool2D': MaxPool2D
}
def __init__(self, input: Input, output: Layer):
self.__input = input
self.__output = output
self.input_shape = self.__input.output_shape
self.output_shape = self.__output.output_shape
self.layers = get_all_layers(output)
@staticmethod
def from_config(cfg: dict):
i = Input(cfg['input_shape'])
cur = i
for layer, c in cfg['layers']:
cur = Model.layer_types[layer](**c)(cur)
return Model(i, cur)
def predict(self, x: np.ndarray):
if len(x.shape) != len(self.__input.output_shape) + 1:
raise Exception("Expected input shape of {} but got {}".format((None, *self.__input.output_shape), x.shape))
self.__input.output = x
# print('input', x.shape)
for layer in self.layers:
x = layer(layer.input.output)
# print(layer, x.shape)
return x
def get_config(self):
return {
'input_shape': self.__input.output_shape,
'output_shape': self.__output.output_shape,
'layers': [
(type(layer).__name__, layer.get_config()) for layer in self.layers
]
}
def get_weights(self):
return [
layer.get_weights() for layer in self.layers
]
def set_weights(self, weights):
for i in range(len(self.layers)):
self.layers[i].set_weights(weights[i])
def get_vectorized_weights(model: Model):
weights = model.get_weights()
outs = []
outw = []
for layer in weights:
shapes = []
for w in layer:
shapes.append(w.shape)
outw.append(w.flatten())
outs.append(shapes)
return np.concatenate(outw), outs
def set_vectorized_weights(model: Model, outw, outs):
weights = []
i = 0
for layer in outs:
shapes = []
for s in layer:
size = util.shape_size(s)
shapes.append(
outw[i:i+size].reshape(s)
)
i += size
weights.append(shapes)
model.set_weights(weights)