-
Notifications
You must be signed in to change notification settings - Fork 2
/
tf_utils.py
647 lines (498 loc) · 28.2 KB
/
tf_utils.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
import numpy as np
import tensorflow as tf
import math
def load_dataset():
train_dataset = h5py.File('datasets/train_signs.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('datasets/test_signs.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
def random_mini_batches_GCN(X, Y, L, mini_batch_size, seed):
m = X.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
shuffled_L1 = L[permutation, :].reshape((L.shape[0], L.shape[1]), order = "F")
shuffled_L = shuffled_L1[:, permutation].reshape((L.shape[0], L.shape[1]), order = "F")
num_complete_minibatches = math.floor(m / mini_batch_size)
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_L = shuffled_L[k * mini_batch_size : k * mini_batch_size + mini_batch_size, k * mini_batch_size : k * mini_batch_size + mini_batch_size]
mini_batch = (mini_batch_X, mini_batch_Y, mini_batch_L)
mini_batches.append(mini_batch)
mini_batch = (X, Y, L)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_GCN1(X, X1, Y, L, mini_batch_size, seed):
m = X.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation, :]
shuffled_X1 = X1[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
shuffled_L1 = L[permutation, :].reshape((L.shape[0], L.shape[1]), order = "F")
shuffled_L = shuffled_L1[:, permutation].reshape((L.shape[0], L.shape[1]), order = "F")
num_complete_minibatches = math.floor(m / mini_batch_size)
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_L = shuffled_L[k * mini_batch_size : k * mini_batch_size + mini_batch_size, k * mini_batch_size : k * mini_batch_size + mini_batch_size]
mini_batch = (mini_batch_X, mini_batch_X1, mini_batch_Y, mini_batch_L)
mini_batches.append(mini_batch)
mini_batch = (X, X1, Y, L)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches(X1, X2, Y, mini_batch_size, seed):
m = X1.shape[0]
m1 = X2.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
permutation1 = list(np.random.permutation(m1))
shuffled_X2 = X2[permutation1, :]
num_complete_minibatches = math.floor(m1/mini_batch_size)
mini_batch_X1 = shuffled_X1
mini_batch_Y = shuffled_Y
for k in range(0, num_complete_minibatches):
mini_batch_X2 = shuffled_X2[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches2(X1, X2, Y1, Y2, mini_batch_size, seed):
m = X1.shape[0]
m1 = X2.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_Y1 = Y1[permutation, :].reshape((m, Y1.shape[1]))
permutation1 = list(np.random.permutation(m1))
shuffled_X2 = X2[permutation1, :]
shuffled_Y2 = Y2[permutation1, :].reshape((m1, Y2.shape[1]))
num_complete_minibatches = math.floor(m / mini_batch_size)
mini_batch_size1 = math.floor(m1/num_complete_minibatches)
mini_batch_X1 = shuffled_X1
mini_batch_Y1 = shuffled_Y1
for k in range(0, num_complete_minibatches):
#mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2 = shuffled_X2[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
#mini_batch_Y1 = shuffled_Y1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y2 = shuffled_Y2[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_Y1, mini_batch_Y2)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_single(X1, Y, mini_batch_size, seed):
m = X1.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
#shuffled_X2 = X2[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
num_complete_minibatches = math.floor(m/mini_batch_size)
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_ccc(X1, X2, X1_FULL, X2_FULL, X1_UN, X2_UN, Y_P, Y, mini_batch_size, seed):
m = X1.shape[0]
m1 = X1_UN.shape[0]
mini_batches = []
np.random.seed(seed)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_X2 = X2[permutation, :]
shuffled_X1_FULL = X1_FULL[permutation, :]
shuffled_X2_FULL = X2_FULL[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
permutation1 = list(np.random.permutation(m1))
shuffled_X1_UN = X1_UN[permutation1, :]
shuffled_X2_UN = X2_UN[permutation1, :]
shuffled_X1_UN_FULL = Y_P[permutation1, :]
num_complete_minibatches = math.floor(m/mini_batch_size)
mini_batch_size1 = math.floor(m1/num_complete_minibatches)
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2 = shuffled_X2[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X1_FULL = shuffled_X1_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2_FULL = shuffled_X2_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X1_UN = shuffled_X1_UN[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
mini_batch_X2_UN = shuffled_X2_UN[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
mini_batch_X1_UN_FULL = shuffled_X1_UN_FULL[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_FULL, mini_batch_X2_FULL, mini_batch_X1_UN, mini_batch_X2_UN, mini_batch_X1_UN_FULL, mini_batch_Y)
mini_batches.append(mini_batch)
if m % mini_batch_size != 0:
mini_batch_X1 = shuffled_X1[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2 = shuffled_X2[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X1_FULL = shuffled_X1_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2_FULL = shuffled_X2_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X1_UN = shuffled_X1_UN[num_complete_minibatches * mini_batch_size1 : m1, :]
mini_batch_X2_UN = shuffled_X2_UN[num_complete_minibatches * mini_batch_size1 : m1, :]
mini_batch_X1_UN_FULL = shuffled_X1_UN_FULL[num_complete_minibatches * mini_batch_size1 : m1, :]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_FULL, mini_batch_X2_FULL, mini_batch_X1_UN, mini_batch_X2_UN, mini_batch_X1_UN_FULL, mini_batch_Y)
return mini_batches
def random_mini_batches_un(X1, X2, X1_UN, X1_FULL, X2_FULL, Y, mini_batch_size, seed):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X1.shape[0]
m1 = X1_UN.shape[0]
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_X2 = X2[permutation, :]
shuffled_X1_FULL = X1_FULL[permutation, :]
shuffled_X2_FULL = X2_FULL[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
permutation1 = list(np.random.permutation(m1))
shuffled_X1_UN = X1_UN[permutation1, :]
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size)
mini_batch_size1 = math.floor(m1/num_complete_minibatches)
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2 = shuffled_X2[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X1_UN = shuffled_X1_UN[k * mini_batch_size1 : k * mini_batch_size1 + mini_batch_size1, :]
mini_batch_X1_FULL = shuffled_X1_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2_FULL = shuffled_X2_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_UN, mini_batch_X1_FULL, mini_batch_X2_FULL, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X1 = shuffled_X1[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2 = shuffled_X2[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X1_UN = shuffled_X1_UN[num_complete_minibatches * mini_batch_size1 : m1, :]
mini_batch_X1_FULL = shuffled_X1_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2_FULL = shuffled_X2_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_UN, mini_batch_X1_FULL, mini_batch_X2_FULL, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_unimodal(X1, mini_batch_size, seed):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X1.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = mini_batch_X1
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X1 = shuffled_X1[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X1)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_bimodal(X1, X2, X1_FULL, X2_FULL, mini_batch_size, seed):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X1.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_X2 = X2[permutation, :]
shuffled_X1_FULL = X1_FULL[permutation, :]
shuffled_X2_FULL = X2_FULL[permutation, :]
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2 = shuffled_X2[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X1_FULL = shuffled_X1_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2_FULL = shuffled_X2_FULL[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_FULL, mini_batch_X2_FULL)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X1 = shuffled_X1[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2 = shuffled_X2[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X1_FULL = shuffled_X1_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2_FULL = shuffled_X2_FULL[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_X1_FULL, mini_batch_X2_FULL)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_standard(X, Y, mini_batch_size, seed):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def random_mini_batches_standardtwoModality(X1, X2, Y, mini_batch_size, seed):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X1.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X1 = X1[permutation, :]
shuffled_X2 = X2[permutation, :]
shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1]))
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X1 = shuffled_X1[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_X2 = shuffled_X2[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X1 = shuffled_X1[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_X2 = shuffled_X2[num_complete_minibatches * mini_batch_size : m, :]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m, :]
mini_batch = (mini_batch_X1, mini_batch_X2, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def convert_to_one_hot(Y, C):
Y = np.eye(C)[Y.reshape(-1)].T
return Y
def predict(X, parameters):
W1 = tf.convert_to_tensor(parameters["W1"])
b1 = tf.convert_to_tensor(parameters["b1"])
W2 = tf.convert_to_tensor(parameters["W2"])
b2 = tf.convert_to_tensor(parameters["b2"])
W3 = tf.convert_to_tensor(parameters["W3"])
b3 = tf.convert_to_tensor(parameters["b3"])
params = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2,
"W3": W3,
"b3": b3}
x = tf.placeholder("float", [12288, 1])
z3 = forward_propagation(x, params)
p = tf.argmax(z3)
with tf.Session() as sess:
prediction = sess.run(p, feed_dict = {x: X})
return prediction
def create_placeholders(n_x, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288)
n_y -- scalar, number of classes (from 0 to 5, so -> 6)
Returns:
X -- placeholder for the data input, of shape [n_x, None] and dtype "float"
Y -- placeholder for the input labels, of shape [n_y, None] and dtype "float"
Tips:
- You will use None because it let's us be flexible on the number of examples you will for the placeholders.
In fact, the number of examples during test/train is different.
"""
### START CODE HERE ### (approx. 2 lines)
X = tf.placeholder("float", [n_x, None])
Y = tf.placeholder("float", [n_y, None])
### END CODE HERE ###
return X, Y
def initialize_parameters():
"""
Initializes parameters to build a neural network with tensorflow. The shapes are:
W1 : [25, 12288]
b1 : [25, 1]
W2 : [12, 25]
b2 : [12, 1]
W3 : [6, 12]
b3 : [6, 1]
Returns:
parameters -- a dictionary of tensors containing W1, b1, W2, b2, W3, b3
"""
tf.set_random_seed(1) # so that your "random" numbers match ours
### START CODE HERE ### (approx. 6 lines of code)
W1 = tf.get_variable("W1", [25,12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
b1 = tf.get_variable("b1", [25,1], initializer = tf.zeros_initializer())
W2 = tf.get_variable("W2", [12,25], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
b2 = tf.get_variable("b2", [12,1], initializer = tf.zeros_initializer())
W3 = tf.get_variable("W3", [6,12], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
b3 = tf.get_variable("b3", [6,1], initializer = tf.zeros_initializer())
### END CODE HERE ###
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2,
"W3": W3,
"b3": b3}
return parameters
def compute_cost(z3, Y):
"""
Computes the cost
Arguments:
z3 -- output of forward propagation (output of the last LINEAR unit), of shape (10, number of examples)
Y -- "true" labels vector placeholder, same shape as z3
Returns:
cost - Tensor of the cost function
"""
# to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits()
logits = tf.transpose(z3)
labels = tf.transpose(Y)
### START CODE HERE ### (1 line of code)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = labels))
### END CODE HERE ###
return cost
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 12288, number of training examples = 1080)
Y_train -- test set, of shape (output size = 6, number of training examples = 1080)
X_test -- training set, of shape (input size = 12288, number of training examples = 120)
Y_test -- test set, of shape (output size = 6, number of test examples = 120)
learning_rate -- learning rate of the optimization
num_epochs -- number of epochs of the optimization loop
minibatch_size -- size of a minibatch
print_cost -- True to print the cost every 100 epochs
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
tf.set_random_seed(1) # to keep consistent results
seed = 3 # to keep consistent results
(n_x, m) = X_train.shape # (n_x: input size, m : number of examples in the train set)
n_y = Y_train.shape[0] # n_y : output size
costs = [] # To keep track of the cost
# Create Placeholders of shape (n_x, n_y)
### START CODE HERE ### (1 line)
X, Y = create_placeholders(n_x, n_y)
### END CODE HERE ###
# Initialize parameters
### START CODE HERE ### (1 line)
parameters = initialize_parameters()
### END CODE HERE ###
# Forward propagation: Build the forward propagation in the tensorflow graph
### START CODE HERE ### (1 line)
z3 = forward_propagation(X, parameters)
### END CODE HERE ###
# Cost function: Add cost function to tensorflow graph
### START CODE HERE ### (1 line)
cost = compute_cost(z3, Y)
### END CODE HERE ###
# Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.
### START CODE HERE ### (1 line)
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)
### END CODE HERE ###
# Initialize all the variables
init = tf.global_variables_initializer()
# Start the session to compute the tensorflow graph
with tf.Session() as sess:
# Run the initialization
sess.run(init)
# Do the training loop
for epoch in range(num_epochs):
minibatch_cost = 0.
num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
seed = seed + 1
minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
# IMPORTANT: The line that runs the graph on a minibatch.
# Run the session to execute the optimizer and the cost, the feedict should contain a minibatch for (X,Y).
### START CODE HERE ### (1 line)
_ , temp_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
### END CODE HERE ###
minibatch_cost += temp_cost / num_minibatches
# Print the cost every epoch
if print_cost == True and epoch % 100 == 0:
print ("Cost after epoch %i: %f" % (epoch, minibatch_cost))
if print_cost == True and epoch % 5 == 0:
costs.append(minibatch_cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
# lets save the parameters in a variable
parameters = sess.run(parameters)
print ("Parameters have been trained!")
# Calculate the correct predictions
correct_prediction = tf.equal(tf.argmax(z3), tf.argmax(Y))
# Calculate accuracy on the test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train}))
print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))
return parameters