-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1_nn_lib.py
707 lines (563 loc) · 25.1 KB
/
part1_nn_lib.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
import numpy as np
import pickle
def xavier_init(size, gain = 1.0):
"""
Xavier initialization of network weights.
Arguments:
- size {tuple} -- size of the network to initialise.
- gain {float} -- gain for the Xavier initialisation.
Returns:
{np.ndarray} -- values of the weights.
"""
low = -gain * np.sqrt(6.0 / np.sum(size))
high = gain * np.sqrt(6.0 / np.sum(size))
return np.random.uniform(low=low, high=high, size=size)
class Layer:
"""
Abstract layer class.
"""
def __init__(self, *args, **kwargs):
raise NotImplementedError()
def forward(self, *args, **kwargs):
raise NotImplementedError()
def __call__(self, *args, **kwargs):
return self.forward(*args, **kwargs)
def backward(self, *args, **kwargs):
raise NotImplementedError()
def update_params(self, *args, **kwargs):
pass
class MSELossLayer(Layer):
"""
MSELossLayer: Computes mean-squared error between y_pred and y_target.
"""
def __init__(self):
self._cache_current = None
@staticmethod
def _mse(y_pred, y_target):
return np.mean((y_pred - y_target) ** 2)
@staticmethod
def _mse_grad(y_pred, y_target):
return 2 * (y_pred - y_target) / len(y_pred)
def forward(self, y_pred, y_target):
self._cache_current = y_pred, y_target
return self._mse(y_pred, y_target)
def backward(self):
return self._mse_grad(*self._cache_current)
class CrossEntropyLossLayer(Layer):
"""
CrossEntropyLossLayer: Computes the softmax followed by the negative
log-likelihood loss.
"""
def __init__(self):
self._cache_current = None
@staticmethod
def softmax(x):
numer = np.exp(x - x.max(axis=1, keepdims=True))
denom = numer.sum(axis=1, keepdims=True)
return numer / denom
def forward(self, inputs, y_target):
assert len(inputs) == len(y_target)
n_obs = len(y_target)
probs = self.softmax(inputs)
self._cache_current = y_target, probs
out = -1 / n_obs * np.sum(y_target * np.log(probs))
return out
def backward(self):
y_target, probs = self._cache_current
n_obs = len(y_target)
return -1 / n_obs * (y_target - probs)
class SigmoidLayer(Layer):
"""
SigmoidLayer: Applies sigmoid function elementwise.
"""
def __init__(self):
"""
Constructor of the Sigmoid layer.
"""
self._cache_current = None
def forward(self, x):
"""
Performs forward pass through the Sigmoid layer.
Logs information needed to compute gradient at a later stage in
`_cache_current`.
Arguments:
x {np.ndarray} -- Input array of shape (batch_size, n_in).
Returns:
{np.ndarray} -- Output array of shape (batch_size, n_out)
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._cache_current = 1./(1+np.exp(-x))
return self._cache_current
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def backward(self, grad_z):
"""
Given `grad_z`, the gradient of some scalar (e.g. loss) with respect to
the output of this layer, performs back pass through the layer (i.e.
computes gradients of loss with respect to parameters of layer and
inputs of layer).
Arguments:
grad_z {np.ndarray} -- Gradient array of shape (batch_size, n_out).
Returns:
{np.ndarray} -- Array containing gradient with repect to layer
input, of shape (batch_size, n_in).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
return self._cache_current * (1. - self._cache_current) * grad_z
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
class ReluLayer(Layer):
"""
ReluLayer: Applies Relu function elementwise.
"""
def __init__(self):
"""
Constructor of the Relu layer.
"""
self._cache_current = None
def forward(self, x):
"""
Performs forward pass through the Relu layer.
Logs information needed to compute gradient at a later stage in
`_cache_current`.
Arguments:
x {np.ndarray} -- Input array of shape (batch_size, n_in).
Returns:
{np.ndarray} -- Output array of shape (batch_size, n_out)
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._cache_current = np.maximum(x,0)
return self._cache_current
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def backward(self, grad_z):
"""
Given `grad_z`, the gradient of some scalar (e.g. loss) with respect to
the output of this layer, performs back pass through the layer (i.e.
computes gradients of loss with respect to parameters of layer and
inputs of layer).
Arguments:
grad_z {np.ndarray} -- Gradient array of shape (batch_size, n_out).
Returns:
{np.ndarray} -- Array containing gradient with repect to layer
input, of shape (batch_size, n_in).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
#res = np.copy(self._cache_current)
#res[res>0] = 1
#return res*grad_z #NOTE : DIMENSION ISSUE
dX = grad_z.copy()
dX[self._cache_current == 0] = 0
return dX
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
class LinearLayer(Layer):
"""
LinearLayer: Performs affine transformation of input.
"""
def __init__(self, n_in, n_out):
"""
Constructor of the linear layer.
Arguments:
- n_in {int} -- Number (or dimension) of inputs.
- n_out {int} -- Number (or dimension) of outputs.
"""
self.n_in = n_in
self.n_out = n_out
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._W = xavier_init((n_in,n_out))
self._b = xavier_init((1,n_out))
self._cache_current = None
self._grad_W_current = None
self._grad_b_current = None
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def forward(self, x):
"""
Performs forward pass through the layer (i.e. returns Wx + b).
Logs information needed to compute gradient at a later stage in
`_cache_current`.
Arguments:
x {np.ndarray} -- Input array of shape (batch_size, n_in).
Returns:
{np.ndarray} -- Output array of shape (batch_size, n_out)
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._cache_current = x
#batch_size = np.shape(x)[0]
#B = np.concatenate((self._b.T,)*batch_size)
#B = np.reshape(B,(batch_size,self.n_out))
#return x@self._W + B
return x.dot(self._W) + self._b
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def backward(self, grad_z):
"""
Given `grad_z`, the gradient of some scalar (e.g. loss) with respect to
the output of this layer, performs back pass through the layer (i.e.
computes gradients of loss with respect to parameters of layer and
inputs of layer).
Arguments:
grad_z {np.ndarray} -- Gradient array of shape (batch_size, n_out).
Returns:
{np.ndarray} -- Array containing gradient with repect to layer
input, of shape (batch_size, n_in).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
x = self._cache_current
#self._grad_b_current = grad_z
self._grad_b_current = np.sum(grad_z, axis=0)
self._grad_W_current = x.T@grad_z
return grad_z@self._W.T
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def update_params(self, learning_rate):
"""
Performs one step of gradient descent with given learning rate on the
layer's parameters using currently stored gradients.
Arguments:
learning_rate {float} -- Learning rate of update step.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._W -= learning_rate*self._grad_W_current
self._b -= learning_rate*self._grad_b_current
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
class MultiLayerNetwork(object):
"""
MultiLayerNetwork: A network consisting of stacked linear layers and
activation functions.
"""
def __init__(self, input_dim, neurons, activations):
"""
Constructor of the multi layer network.
Arguments:
- input_dim {int} -- Number of features in the input (excluding
the batch dimension).
- neurons {list} -- Number of neurons in each linear layer
represented as a list. The length of the list determines the
number of linear layers.
- activations {list} -- List of the activation functions to apply
to the output of each linear layer.
"""
self.input_dim = input_dim
self.neurons = neurons
self.activations = activations
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self._layers = []
prev=input_dim
for i in range(len(neurons)):
layer = LinearLayer(prev,neurons[i])
if activations[i]=="relu":
activation_function = ReluLayer()
elif activations[i]=='sigmoid':
activation_function = SigmoidLayer()
elif activations[i]=='identity':
activation_function = "identity"
else:
raise Exception("Activation function ", activations[i], " is invalid")
self._layers.append((layer, activation_function))
prev = neurons[i]
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def forward(self, x):
"""
Performs forward pass through the network.
Arguments:
x {np.ndarray} -- Input array of shape (batch_size, input_dim).
Returns:
{np.ndarray} -- Output array of shape (batch_size,
#_neurons_in_final_layer)
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
interm = x
for (lay, act) in self._layers:
interm = lay.forward(interm)
if act != "identity":
interm = act.forward(interm)
return interm
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def __call__(self, x):
return self.forward(x)
def backward(self, grad_z):
"""
Performs backward pass through the network.
Arguments:
grad_z {np.ndarray} -- Gradient array of shape (1,
#_neurons_in_final_layer).
Returns:
{np.ndarray} -- Array containing gradient with repect to layer
input, of shape (batch_size, input_dim).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
interm = grad_z
for (lay, act) in reversed(self._layers):
if act != "identity":
interm = act.backward(interm)
interm = lay.backward(interm)
return interm
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def update_params(self, learning_rate):
"""
Performs one step of gradient descent with given learning rate on the
parameters of all layers using currently stored gradients.
Arguments:
learning_rate {float} -- Learning rate of update step.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
for (lay, act) in self._layers:
lay.update_params(learning_rate)
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def save_network(network, fpath):
"""
Utility function to pickle `network` at file path `fpath`.
"""
with open(fpath, "wb") as f:
pickle.dump(network, f)
def load_network(fpath):
"""
Utility function to load network found at file path `fpath`.
"""
with open(fpath, "rb") as f:
network = pickle.load(f)
return network
class Trainer(object):
"""
Trainer: Object that manages the training of a neural network.
"""
def __init__(
self,
network,
batch_size,
nb_epoch,
learning_rate,
loss_fun,
shuffle_flag,
):
"""
Constructor of the Trainer.
Arguments:
- network {MultiLayerNetwork} -- MultiLayerNetwork to be trained.
- batch_size {int} -- Training batch size.
- nb_epoch {int} -- Number of training epochs.
- learning_rate {float} -- SGD learning rate to be used in training.
- loss_fun {str} -- Loss function to be used. Possible values: mse,
bce.
- shuffle_flag {bool} -- If True, training data is shuffled before
training.
"""
self.network = network
self.batch_size = batch_size
self.nb_epoch = nb_epoch
self.learning_rate = learning_rate
self.loss_fun = loss_fun
self.shuffle_flag = shuffle_flag
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
if loss_fun=="mse":
self._loss_layer = MSELossLayer()
elif loss_fun == 'cross_entropy':
self._loss_layer = CrossEntropyLossLayer()
else:
raise Exception("Loss function ", loss_fun, " is invalid")
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
@staticmethod
def shuffle(input_dataset, target_dataset):
"""
Returns shuffled versions of the inputs.
Arguments:
- input_dataset {np.ndarray} -- Array of input features, of shape
(#_data_points, n_features).
- target_dataset {np.ndarray} -- Array of corresponding targets, of
shape (#_data_points, #output_neurons).
Returns:
- {np.ndarray} -- shuffled inputs.
- {np.ndarray} -- shuffled_targets.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
shuffled = np.random.permutation(np.arange(len(input_dataset)))
return (input_dataset[shuffled], target_dataset[shuffled])
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def train(self, input_dataset, target_dataset):
"""
Main training loop. Performs the following steps `nb_epoch` times:
- Shuffles the input data (if `shuffle` is True)
- Splits the dataset into batches of size `batch_size`.
- For each batch:
- Performs forward pass through the network given the current
batch of inputs.
- Computes loss.
- Performs backward pass to compute gradients of loss with
respect to parameters of network.
- Performs one step of gradient descent on the network
parameters.
Arguments:
- input_dataset {np.ndarray} -- Array of input features, of shape
(#_training_data_points, n_features).
- target_dataset {np.ndarray} -- Array of corresponding targets, of
shape (#_training_data_points, #output_neurons).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
for epoch in range(0, self.nb_epoch):
if self.shuffle_flag:
Trainer.shuffle(input_dataset, target_dataset)
n_batches = int(len(input_dataset) / self.batch_size)
data = np.array_split(input_dataset, n_batches)
target = np.array_split(target_dataset, n_batches)
for i in range(n_batches):
output = self.network.forward(data[i])
self._loss_layer.forward(output, target[i])
self.network.backward(self._loss_layer.backward())
self.network.update_params(self.learning_rate)
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def eval_loss(self, input_dataset, target_dataset):
"""
Function that evaluate the loss function for given data.
Arguments:
- input_dataset {np.ndarray} -- Array of input features, of shape
(#_evaluation_data_points, n_features).
- target_dataset {np.ndarray} -- Array of corresponding targets, of
shape (#_evaluation_data_points, #output_neurons).
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
return self._loss_layer.forward(self.network.forward(input_dataset), target_dataset)
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
class Preprocessor(object):
"""
Preprocessor: Object used to apply "preprocessing" operation to datasets.
The object can also be used to revert the changes.
"""
def __init__(self, data):
"""
Initializes the Preprocessor according to the provided dataset.
(Does not modify the dataset.)
Arguments:
data {np.ndarray} dataset used to determine the parameters for
the normalization.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
self.data_max = np.max(data,axis=0)
self.data_min = np.min(data,axis=0)
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def apply(self, data):
"""
Apply the pre-processing operations to the provided dataset.
Arguments:
data {np.ndarray} dataset to be normalized.
Returns:
{np.ndarray} normalized dataset.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
return (data-self.data_min) / (self.data_max -self.data_min)
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def revert(self, data):
"""
Revert the pre-processing operations to retreive the original dataset.
Arguments:
data {np.ndarray} dataset for which to revert normalization.
Returns:
{np.ndarray} reverted dataset.
"""
#######################################################################
# ** START OF YOUR CODE **
#######################################################################
return data *(self.data_max -self.data_min) + self.data_min
#######################################################################
# ** END OF YOUR CODE **
#######################################################################
def example_main():
input_dim = 4
neurons = [16, 3]
activations = ["relu", "identity"]
net = MultiLayerNetwork(input_dim, neurons, activations)
dat = np.loadtxt("iris.dat")
np.random.shuffle(dat)
x = dat[:, :4]
y = dat[:, 4:]
split_idx = int(0.8 * len(x))
x_train = x[:split_idx]
y_train = y[:split_idx]
x_val = x[split_idx:]
y_val = y[split_idx:]
prep_input = Preprocessor(x_train)
x_train_pre = prep_input.apply(x_train)
x_val_pre = prep_input.apply(x_val)
trainer = Trainer(
network=net,
batch_size=8,
nb_epoch=1000,
learning_rate=0.01,
loss_fun="cross_entropy",
shuffle_flag=True,
)
trainer.train(x_train_pre, y_train)
print("Train loss = ", trainer.eval_loss(x_train_pre, y_train))
print("Validation loss = ", trainer.eval_loss(x_val_pre, y_val))
preds = net(x_val_pre).argmax(axis=1).squeeze()
targets = y_val.argmax(axis=1).squeeze()
accuracy = (preds == targets).mean()
print("Validation accuracy: {}".format(accuracy))
if __name__ == "__main__":
example_main()