forked from MehmetAlicanNoyan/FP_AI_Bootcamp_Session_5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNN Challenge.py
674 lines (397 loc) · 10.1 KB
/
NN Challenge.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
#!/usr/bin/env python
# coding: utf-8
# # Teaser
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
# ### Dataset
# In[2]:
# Download the dataset
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# In[3]:
# View example digit
index = np.random.randint(0, 60000)
plt.imshow(x_train[index])
print(y_train[index])
# In[4]:
x_train.shape, y_train.shape
# In[5]:
# Flatten
x_train = x_train.reshape(-1,784)
x_test = x_test.reshape(-1,784)
# Convert labels to one-vs-all
from keras.utils import to_categorical
y_test = to_categorical(y_test)
y_train = to_categorical(y_train)
# In[6]:
# Proper shape for our NN
x_train.shape, y_train.shape
# ### Building the NN
# In[7]:
# Call the DL library
from keras.models import Sequential
from keras.layers import Dense, Activation
# <img src=https://i.imgur.com/OFNAslJ.png width="500">
# In[8]:
# Build the architecture
model = Sequential()
model.add(Dense(30, input_dim=784))
model.add(Activation('relu'))
model.add(Dense(30))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
# In[9]:
# Learning algorithm, Loss
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
# In[10]:
# Train and test
H = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test))
# # Challenge
# In[11]:
from sklearn.datasets import make_circles
# In[12]:
# Generate a dataset
X, y = make_circles(n_samples=100, noise=0.05, factor=0.5, random_state=0)
plt.figure(dpi=200)
plt.scatter(X[:, 0][y == 0], X[:, 1][y == 0], label=0)
plt.scatter(X[:, 0][y == 1], X[:, 1][y == 1], label=1)
plt.xlabel('feature 0')
plt.ylabel('feature 1')
plt.legend()
# # 1. Build NN
# <img src=https://i.imgur.com/BMcpMsH.png width="800">
# In[13]:
# Challenge 1
def nn_parameter_maker(size):
'''
Given
- the number of layers
- the number of nodes in each layer
initializes network parameters (w and b)
Arguments
size: a list of integers
length of the list is the number of layers
each item in the list specifies
the number of neurons in that layer
Returns
biases: list of numpy arrays
biases
for all layers except the input layer
weights: list of numpy arrays
weights
in between all layers
'''
return weights, biases
# In[14]:
y = y.reshape(-1, 1)
X.shape, y.shape
# In[15]:
w, b = nn_parameter_maker([2, 3, 1])
# In[16]:
b[0], b[0].shape
# In[17]:
b[1], b[1].shape
# In[18]:
w[0], w[0].shape
# In[19]:
w[1], w[1].shape
# In[20]:
# Challenge 2
def sigmoid(z):
'''
Calculates the sigmoid of any input
Arguments
z: np.array() of real numbers
Returns
np.array() of real numbers between 0 and 1
'''
return
# In[21]:
plt.figure(dpi=100)
plt.plot(np.arange(-10, 10), sigmoid(np.arange(-10, 10)))
# In[22]:
# Challenge 3
def forward_pass(inp, w, b):
'''
Given an input and NN parameters
calculates the output
Arguments
inp: np.array() shape
(#input_dim, #datapoints)
w: list of np arrays
b: list of np arrays
Returns
out: np.array() shape
(#output_dim, #datapoints)
'''
return
# # 2. Get predictions from an untrained NN
# In[23]:
# Implemented
def predict(X, w, b):
'''
X.shape is (#datapoints, #input_dim)
so we need to transpose before doing a forward pass
and transpose the output as well to get
y_pred.shape with (#datapoints, #output_dim)
Arguments
X: np.array() of inputs
shape (#datapoints, #input_dim)
w: list of np arrays
b: list of np arrays
Returns
y_pred: np.array() of predictions
shape (#datapoints, #output_dim)
'''
X_t = np.transpose(X)
y_pred_t = forward_pass(X_t, w, b)
y_pred = np.transpose(y_pred_t)
return y_pred
# In[24]:
y_pred = predict(X, w, b)
# In[25]:
X.shape, y_pred.shape
# In[26]:
plt.figure(dpi=100)
plt.plot(y_pred, label='random predictions')
plt.plot(y, label='labels')
plt.legend()
plt.xlabel('Datapoints')
plt.ylabel('Output')
# In[27]:
# convert to binary
y_pred = 1*(y_pred > 0.5)
# In[28]:
# Implemented
def accuracy(y_pred, y):
'''
Given
-binary predictions
-labels
calculates accuracy
'''
return sum(y_pred == y)/len(y)
# In[29]:
# Accuracy of an untrained network
accuracy(y_pred, y)
# # 3. Train a neural network
# In[30]:
# Implemented
def cost_function(X, y, w, b):
'''
Given
- input
- network parameters
- labels
calculates the mse
'''
y_pred = predict(X, w, b)
m = y.shape[0]
cost = np.sum((y_pred-y)**2)/m # mse
return cost
# In[31]:
cost_function(X, y, w, b)
# In[32]:
# Implemented
def w_update(w, layer_id, i, j, new_param):
'''
Given a single weight defined by (layer_id, i, j)
updates it with a new parameter (new_param)
Arguments
w: list of np.arrays()
layer_id: integer
i: integer
j: integer
new_param: float
Return
new_w: list of np.arrays()
where only a single value is changed
'''
new_w = w.copy()
layer_w = w[layer_id]
new_layer_w = layer_w.copy()
new_layer_w[i, j] = new_param
new_w[layer_id] = new_layer_w
return new_w
# In[33]:
# Implemented
def b_update(b, layer_id, i, j, new_param):
'''
Given a single bias defined by (layer_id, i, j)
updates it with a new parameter (new_param)
Arguments
b: list of np.arrays()
layer_id: integer
i: integer
j: integer
new_param: float
Return
new_b: list of np.arrays()
where only a single value is changed
'''
new_b = b.copy()
layer_b = b[layer_id]
new_layer_b = layer_b.copy()
new_layer_b[i, j] = new_param
new_b[layer_id] = new_layer_b
return new_b
# In[34]:
# Challenge 4
def gradient_estimator(X, y, w, b):
'''
GD update rule is
wij = wij - lr * ∂(cost)/∂(wij)
bij = bij - lr * ∂(cost)/∂(bij)
This function estimates the partial derivates
∂(cost)/∂(wij) and ∂(cost)/∂(bij) using:
∂(cost)/∂(wij)
can be estimated by
[(cost with wij+epsilon) - (cost with wij)]/epsilon
likewise
∂(cost)/∂(bij)
can be estimated by
[(cost with bij+epsilon) - (cost with bij)]/epsilon
For each parameter in w and b, the function will calculate
∂(cost)/∂(w) and ∂(cost)/∂(b) and return a list of np.arrays()
called w_pds and b_pds, respectively.
Arguments
X: input data
y: labels
w: list of np arrays, weights of NN
b: list of np arrays, biases of NN
Returns
w_pds: list of np arrays, same dimensions with w
b_pds: list of np arrays, same dimensions with b
'''
eps = 1e-4
cost_val = cost_function(X, y, w, b)
# partial derivatives for weights
w_pds = []
...
# partial derivatives for biases
b_pds = []
...
return w_pds, b_pds
# In[35]:
w_pds, b_pds = gradient_estimator(X, y, w, b)
# In[36]:
w
# In[37]:
w_pds
# In[38]:
b
# In[39]:
b_pds
# In[40]:
# Challenge 5
def one_step_gd(X, y, w, b, lr):
'''
This function executes one step of GD and updates w and b
First estimate the gradient using gradient estimator
Then update params by
w = w - lr * w_pds
b = b - lr * b_pds
Arguments
X: input data
y: labels
w: NN weights
b: NN biases
lr: learning rate, a float
Returns
new_w: updated weights, same size as w
new_b: updated biases, same size as b
'''
w_pds, b_pds = gradient_estimator(X, y, w, b)
new_w = []
...
new_b = []
...
return new_w, new_b
# In[41]:
# Cost of random predictions
cost_function(X, y, w, b)
# In[42]:
new_w, new_b = one_step_gd(X, y, w, b, lr = 0.01)
# In[43]:
# Cost after one step of GD
cost_function(X, y, new_w, new_b)
# In[44]:
# Implemented
def GD(X, y, w, b, epoch, lr):
'''
Repeats GD one step for a number of epochs
Saves and plots the error at each epoch
Arguments
X: input data
y: labels
w: NN weights
b: NN biases
epoch: integer
lr: float
Return
w: learned weights
b: learned biases
'''
errors = []
for i in range(epoch):
w, b = one_step_gd(X, y, w, b, lr)
error = cost_function(X, y, w, b)
errors.append(error)
plt.figure(dpi=100)
plt.plot(errors)
plt.xlabel('# epochs')
plt.ylabel('loss')
return w, b
# In[45]:
w, b = GD(X, y, w, b, epoch=1000, lr=0.01)
# # 4. Putting it together
# In[74]:
# Generate a dataset
X, y = make_circles(n_samples=100, noise=0.05, factor=0.5)
plt.figure(dpi=100)
plt.scatter(X[:, 0][y == 0], X[:, 1][y == 0], label=0)
plt.scatter(X[:, 0][y == 1], X[:, 1][y == 1], label=1)
plt.xlabel('feature 0')
plt.ylabel('feature 1')
plt.legend()
# In[75]:
y = y.reshape(-1, 1)
X.shape, y.shape
# In[76]:
# Initialize the network
w, b = nn_parameter_maker([2, 3, 1])
# In[77]:
# Train the network
w, b = GD(X, y, w, b, epoch=20000, lr=0.3)
# In[78]:
# Get predictions
y_pred = predict(X, w, b)
# In[79]:
# Look at the first 10 preds vs. labels
np.concatenate((y_pred[0:10], y[0:10]), axis=1)
# In[80]:
plt.figure(dpi=100)
plt.plot(y_pred, label='random predictions')
plt.plot(y, label='labels')
plt.legend()
plt.xlabel('Datapoints')
plt.ylabel('Output')
# In[81]:
y_pred = (y_pred > 0.5)*1
accuracy(y_pred, y)
# In[82]:
# Check accuracy on test set
# Generate the test set
X_te, y_te = make_circles(n_samples=100, noise=0.05, factor=0.5, random_state=1)
y_te = y_te.reshape(-1, 1)
# Get preds
test_preds = predict(X_te, w, b)
# Calculate acc
test_preds = (test_preds > 0.5)*1
accuracy(test_preds, y_te)
# In[ ]:
# In[ ]: