forked from rasbt/python-machine-learning-book-3rd-edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch13_part1.py
600 lines (256 loc) · 9.21 KB
/
ch13_part1.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
# coding: utf-8
import tensorflow as tf
import numpy as np
import pathlib
import matplotlib.pyplot as plt
import os
import tensorflow_datasets as tfds
# *Python Machine Learning 3rd Edition* by [Sebastian Raschka](https://sebastianraschka.com) & [Vahid Mirjalili](http://vahidmirjalili.com), Packt Publishing Ltd. 2019
#
# Code Repository: https://github.com/rasbt/python-machine-learning-book-3rd-edition
#
# Code License: [MIT License](https://github.com/rasbt/python-machine-learning-book-3rd-edition/blob/master/LICENSE.txt)
# # Chapter 13: Parallelizing Neural Network Training with TensorFlow (Part 1/2)
#
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
# ## TensorFlow and training performance
# ### Performance challenges
# ### What is TensorFlow?
# ### How we will learn TensorFlow
# ## First steps with TensorFlow
# ### Installing TensorFlow
#! pip install tensorflow
print('TensorFlow version:', tf.__version__)
np.set_printoptions(precision=3)
# ### Creating tensors in TensorFlow
a = np.array([1, 2, 3], dtype=np.int32)
b = [4, 5, 6]
t_a = tf.convert_to_tensor(a)
t_b = tf.convert_to_tensor(b)
print(t_a)
print(t_b)
tf.is_tensor(a), tf.is_tensor(t_a)
t_ones = tf.ones((2, 3))
t_ones.shape
t_ones.numpy()
const_tensor = tf.constant([1.2, 5, np.pi], dtype=tf.float32)
print(const_tensor)
# ### Manipulating the data type and shape of a tensor
t_a_new = tf.cast(t_a, tf.int64)
print(t_a_new.dtype)
t = tf.random.uniform(shape=(3, 5))
t_tr = tf.transpose(t)
print(t.shape, ' --> ', t_tr.shape)
t = tf.zeros((30,))
t_reshape = tf.reshape(t, shape=(5, 6))
print(t_reshape.shape)
t = tf.zeros((1, 2, 1, 4, 1))
t_sqz = tf.squeeze(t, axis=(2, 4))
print(t.shape, ' --> ', t_sqz.shape)
# ### Applying mathematical operations to tensors
tf.random.set_seed(1)
t1 = tf.random.uniform(shape=(5, 2),
minval=-1.0,
maxval=1.0)
t2 = tf.random.normal(shape=(5, 2),
mean=0.0,
stddev=1.0)
t3 = tf.multiply(t1, t2).numpy()
print(t3)
t4 = tf.math.reduce_mean(t1, axis=0)
print(t4)
t5 = tf.linalg.matmul(t1, t2, transpose_b=True)
print(t5.numpy())
t6 = tf.linalg.matmul(t1, t2, transpose_a=True)
print(t6.numpy())
norm_t1 = tf.norm(t1, ord=2, axis=1).numpy()
print(norm_t1)
np.sqrt(np.sum(np.square(t1), axis=1))
# ### Split, stack, and concatenate tensors
tf.random.set_seed(1)
t = tf.random.uniform((6,))
print(t.numpy())
t_splits = tf.split(t, 3)
[item.numpy() for item in t_splits]
tf.random.set_seed(1)
t = tf.random.uniform((5,))
print(t.numpy())
t_splits = tf.split(t, num_or_size_splits=[3, 2])
[item.numpy() for item in t_splits]
A = tf.ones((3,))
B = tf.zeros((2,))
C = tf.concat([A, B], axis=0)
print(C.numpy())
A = tf.ones((3,))
B = tf.zeros((3,))
S = tf.stack([A, B], axis=1)
print(S.numpy())
# ## Building input pipelines using tf.data: The TensorFlow Dataset API
# ### Creating a TensorFlow Dataset from existing tensors
a = [1.2, 3.4, 7.5, 4.1, 5.0, 1.0]
ds = tf.data.Dataset.from_tensor_slices(a)
print(ds)
for item in ds:
print(item)
ds_batch = ds.batch(3)
for i, elem in enumerate(ds_batch, 1):
print('batch {}:'.format(i), elem.numpy())
# ### Combining two tensors into a joint dataset
tf.random.set_seed(1)
t_x = tf.random.uniform([4, 3], dtype=tf.float32)
t_y = tf.range(4)
ds_x = tf.data.Dataset.from_tensor_slices(t_x)
ds_y = tf.data.Dataset.from_tensor_slices(t_y)
ds_joint = tf.data.Dataset.zip((ds_x, ds_y))
for example in ds_joint:
print(' x: ', example[0].numpy(),
' y: ', example[1].numpy())
## method 2:
ds_joint = tf.data.Dataset.from_tensor_slices((t_x, t_y))
for example in ds_joint:
print(' x: ', example[0].numpy(),
' y: ', example[1].numpy())
ds_trans = ds_joint.map(lambda x, y: (x*2-1.0, y))
for example in ds_trans:
print(' x: ', example[0].numpy(),
' y: ', example[1].numpy())
# ### Shuffle, batch, and repeat
tf.random.set_seed(1)
ds = ds_joint.shuffle(buffer_size=len(t_x))
for example in ds:
print(' x: ', example[0].numpy(),
' y: ', example[1].numpy())
ds = ds_joint.batch(batch_size=3,
drop_remainder=False)
batch_x, batch_y = next(iter(ds))
print('Batch-x: \n', batch_x.numpy())
print('Batch-y: ', batch_y.numpy())
ds = ds_joint.batch(3).repeat(count=2)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
ds = ds_joint.repeat(count=2).batch(3)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
tf.random.set_seed(1)
## Order 1: shuffle -> batch -> repeat
ds = ds_joint.shuffle(4).batch(2).repeat(3)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
tf.random.set_seed(1)
## Order 1: shuffle -> batch -> repeat
ds = ds_joint.shuffle(4).batch(2).repeat(20)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
tf.random.set_seed(1)
## Order 2: batch -> shuffle -> repeat
ds = ds_joint.batch(2).shuffle(4).repeat(3)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
tf.random.set_seed(1)
## Order 2: batch -> shuffle -> repeat
ds = ds_joint.batch(2).shuffle(4).repeat(20)
for i,(batch_x, batch_y) in enumerate(ds):
print(i, batch_x.shape, batch_y.numpy())
# ### Creating a dataset from files on your local storage disk
imgdir_path = pathlib.Path('cat_dog_images')
file_list = sorted([str(path) for path in imgdir_path.glob('*.jpg')])
print(file_list)
fig = plt.figure(figsize=(10, 5))
for i,file in enumerate(file_list):
img_raw = tf.io.read_file(file)
img = tf.image.decode_image(img_raw)
print('Image shape: ', img.shape)
ax = fig.add_subplot(2, 3, i+1)
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(img)
ax.set_title(os.path.basename(file), size=15)
# plt.savefig('ch13-catdot-examples.pdf')
plt.tight_layout()
plt.show()
labels = [1 if 'dog' in os.path.basename(file) else 0
for file in file_list]
print(labels)
ds_files_labels = tf.data.Dataset.from_tensor_slices(
(file_list, labels))
for item in ds_files_labels:
print(item[0].numpy(), item[1].numpy())
def load_and_preprocess(path, label):
image = tf.io.read_file(path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [img_height, img_width])
image /= 255.0
return image, label
img_width, img_height = 120, 80
ds_images_labels = ds_files_labels.map(load_and_preprocess)
fig = plt.figure(figsize=(10, 5))
for i,example in enumerate(ds_images_labels):
print(example[0].shape, example[1].numpy())
ax = fig.add_subplot(2, 3, i+1)
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(example[0])
ax.set_title('{}'.format(example[1].numpy()),
size=15)
plt.tight_layout()
#plt.savefig('ch13-catdog-dataset.pdf')
plt.show()
# ### Fetching available datasets from the tensorflow_datasets library
print(len(tfds.list_builders()))
print(tfds.list_builders()[:5])
## Run this to see the full list:
tfds.list_builders()
# Fetching CelebA dataset
celeba_bldr = tfds.builder('celeb_a')
print(celeba_bldr.info.features)
print('\n', 30*"=", '\n')
print(celeba_bldr.info.features.keys())
print('\n', 30*"=", '\n')
print(celeba_bldr.info.features['image'])
print('\n', 30*"=", '\n')
print(celeba_bldr.info.features['attributes'].keys())
print('\n', 30*"=", '\n')
print(celeba_bldr.info.citation)
# Download the data, prepare it, and write it to disk
celeba_bldr.download_and_prepare()
# Load data from disk as tf.data.Datasets
datasets = celeba_bldr.as_dataset(shuffle_files=False)
datasets.keys()
#import tensorflow as tf
ds_train = datasets['train']
assert isinstance(ds_train, tf.data.Dataset)
example = next(iter(ds_train))
print(type(example))
print(example.keys())
ds_train = ds_train.map(lambda item:
(item['image'], tf.cast(item['attributes']['Male'], tf.int32)))
ds_train = ds_train.batch(18)
images, labels = next(iter(ds_train))
print(images.shape, labels)
fig = plt.figure(figsize=(12, 8))
for i,(image,label) in enumerate(zip(images, labels)):
ax = fig.add_subplot(3, 6, i+1)
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(image)
ax.set_title('{}'.format(label), size=15)
plt.show()
# Alternative ways for loading a dataset
mnist, mnist_info = tfds.load('mnist', with_info=True,
shuffle_files=False)
print(mnist_info)
print(mnist.keys())
ds_train = mnist['train']
assert isinstance(ds_train, tf.data.Dataset)
ds_train = ds_train.map(lambda item:
(item['image'], item['label']))
ds_train = ds_train.batch(10)
batch = next(iter(ds_train))
print(batch[0].shape, batch[1])
fig = plt.figure(figsize=(15, 6))
for i,(image,label) in enumerate(zip(batch[0], batch[1])):
ax = fig.add_subplot(2, 5, i+1)
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(image[:, :, 0], cmap='gray_r')
ax.set_title('{}'.format(label), size=15)
plt.show()
# ---
#
# Readers may ignore the next cell.