/
final_miniproject.py
587 lines (427 loc) · 17.4 KB
/
final_miniproject.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
# -*- coding: utf-8 -*-
"""Final_MiniProject.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1oW8HAUeDp8JY23bFvGLAaqg2l0hx0dgD
## Implementation of the gradient for the un-regularized neural network
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn import metrics
from sklearn import decomposition
from sklearn import manifold
import matplotlib.pyplot as plt
import numpy as np
import copy
import random
import time
SEED = 1234
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
# torch.backends.cudnn.deterministic = True
ROOT = '.data'
train_data = datasets.MNIST(root=ROOT, train=True, download=True)
# normalize data: make data to have mean of zero and a standard deviation of one.
mean = train_data.data.float().mean() / 255
std = train_data.data.float().std() / 255
print(f'Calculated mean: {mean}')
print(f'Calculated std: {std}')
# Data augmentation: manipulating the available training data in a way that artifically creates more training
# examples (randomely rotating, adding padding around the image) augmented data will be transformed to a tensor and
# normalize
train_transforms = transforms.Compose([
transforms.RandomRotation(5, fill=(0,)),
transforms.RandomCrop(28, padding=2),
transforms.ToTensor(),
transforms.Normalize(mean=[mean], std=[std])])
test_transforms = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[mean], std=[std])
])
# Load the train and test data with the relevant defined transforms
train_data = datasets.MNIST(root=ROOT,
train=True,
download=True,
transform=train_transforms)
test_data = datasets.MNIST(root=ROOT,
train=False,
download=True,
transform=test_transforms)
# Length of datasets
print(f'Number of training examples: {len(train_data)}')
print(f'Number of testing examples: {len(test_data)}')
# Sample image visualization
def plot_images(N_IMAGES, input_data): # input_data = train_data or test_data or va
images = [image for image, label in [input_data[i] for i in range(N_IMAGES)]]
n_images = len(images)
rows = int(np.sqrt(n_images))
cols = int(np.sqrt(n_images))
fig = plt.figure()
for i in range(rows * cols):
ax = fig.add_subplot(rows, cols, i + 1)
ax.imshow(images[i].view(28, 28).cpu().numpy(), cmap='bone')
ax.axis('off')
# Creating a validation data for a proxy test to check how model performs
VALID_RATIO = 0.9
num_train_examples = int(len(train_data) * VALID_RATIO)
num_valid_examples = len(train_data) - num_train_examples
# Take a random 10% of the training set to use as a validation set
train_data, valid_data = data.random_split(train_data,
[num_train_examples, num_valid_examples])
# Check number of examples for each portions
print(f'Number of training examples: {len(train_data)}')
print(f'Number of validation examples: {len(valid_data)}')
print(f'Number of testing examples: {len(test_data)}')
# Replace the validation set's transform by overwriting it with previously built test transforms
valid_data = copy.deepcopy(valid_data) # To prevent changing of default transforms of other training data
valid_data.dataset.transform = test_transforms
BATCH_SIZE = 100
train_iterator = data.DataLoader(train_data,
shuffle=True,
batch_size=BATCH_SIZE)
valid_iterator = data.DataLoader(valid_data,
batch_size=BATCH_SIZE)
test_iterator = data.DataLoader(test_data,
batch_size=BATCH_SIZE)
class Multilayer_Perceptron(nn.Module):
def __init__(self, input_dim, output_dim):
super().__init__()
self.input_fc = nn.Linear(input_dim, 250)
self.hidden_fc = nn.Linear(250, 100)
self.output_fc = nn.Linear(100, output_dim)
def forwad_propagation(self, x): # x: input tensor to the network
# x = [batch_size, height, width]
batch_size = x.shape[0]
# transform to
x = x.view(batch_size, -1) # reshape the tensor to x = [batch size, height * width] -
# 1 is when not sure about number of rows
# First neural layer
nn_layer_1 = self.input_fc(x)
nn_layer_act_func_1 = F.relu(nn_layer_1)
# Second or Hidden neural layer
nn_layer_2 = self.hidden_fc(nn_layer_act_func_1)
nn_layer_act_func_2 = F.relu(nn_layer_2)
# Output layer or prediction layer
# y_predict_layer = [batch_size_output_dim]
y_predict_layer = self.output_fc(nn_layer_act_func_2)
return y_predict_layer, nn_layer_act_func_2
# Define Multilayer perceptron model by creating an instance of it and setting the correct input and output dimensions.
INPUT_DIM = 28 * 28
OUTPUT_DIM = 10
model = Multilayer_Perceptron(INPUT_DIM, OUTPUT_DIM)
# Calculate the number of trainable parameters (weights and biases)
def count_parameters(mlp_model):
return sum(p.numel() for p in mlp_model.parameters() if p.requires_grad)
# Calculate and print number of trainable parameters
print(f'The model has {count_parameters(model):,} trainable parameters')
# Optimizer
optimizer = optim.Adam(model.parameters())
# Cost function
criterion = nn.CrossEntropyLoss()
# define device to put model and data, by defult it is GPU or else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Put the model and cost function in the defined device
model = model.to(device)
criterion = criterion.to(device)
# Calculate the accuracy of the model
def calculate_accuracy(y_pred, y):
top_pred = y_pred.argmax(1, keepdim=True)
correct = top_pred.eq(y.view_as(top_pred)).sum()
acc = correct.float() / y.shape[0]
return acc
'''
Define the training loop function for the model
The training loop will perform following tasks:
* put the model into train mode
* iterate over the data loader, returning batches of (image, label)
* place the batch on to GPU, if not available on CPU
* clear the gradients calculated from the last batch
* pass a batch of images, x, through to model to get predictions, y_pred
* calculate the loss between the predictions and the actual labels
* calculate the accuracy between our predictions and the actual labels
* calculate the gradients of each parameter
* update the parameters by taking an optimizer step
* update metrics
'''
def train(model, iterator, optimizer, criterion, device):
epoch_loss = 0
epoch_acc = 0
model.train()
for (x, y) in iterator:
x = x.to(device)
y = y.to(device)
optimizer.zero_grad()
y_pred, _ = model.forwad_propagation(x)
loss = criterion(y_pred, y)
acc = calculate_accuracy(y_pred, y)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
'''
The evaluation loop is similar to the training loop bu serves different purposes performing following:
* put to model into evaluation mode with model.eval()
* wrap the iterations inside a with torch.no_grad() to make sure gradients are not calculated in evaluation step
* do not calculate gradients as we are not updating parameters
* do not take an optimizer step as we are not calculating gradients
'''
def evaluate(model, iterator, criterion, device):
epoch_loss = 0
epoch_acc = 0
model.eval()
with torch.no_grad():
for (x, y) in iterator:
x = x.to(device)
y = y.to(device)
y_pred, A = model.forwad_propagation(x)
loss = criterion(y_pred, y)
acc = calculate_accuracy(y_pred, y)
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
# Define a function to tell how long an epoch took
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
# Model training
best_valid_loss = float('inf')
EPOCHS = 10
for epoch in range(EPOCHS):
start_time = time.monotonic()
train_loss, train_acc = train(model, train_iterator, optimizer, criterion, device)
valid_loss, valid_acc = evaluate(model, valid_iterator, criterion, device)
# Make sure always saves the set of parameters that has the best validation loss (validation accuracy)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), 'tut1-model.pt')
end_time = time.monotonic()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
print(f'Epoch: {epoch + 1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc * 100:.2f}%')
print(f'\t Valid Loss: {valid_loss:.3f} | Valid Acc: {valid_acc * 100:.2f}%')
# Test the model
# Afterwards, load the parameters of the model that achieved the best validation loss
# Then use this to evaluate our model on the test set.
model.load_state_dict(torch.load('tut1-model.pt'))
test_loss, test_acc = evaluate(model, test_iterator, criterion, device)
print(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc * 100:.2f}%')
# Examining the model with simple exploratory
# This function will return input image and model prediction output with ground truth
def get_predictions(model, iterator, device):
model.eval()
images = []
labels = []
probs = []
with torch.no_grad():
for (x, y) in iterator:
x = x.to(device)
y_pred, _ = model.forwad_propagation(x)
y_prob = F.softmax(y_pred, dim=-1)
top_pred = y_prob.argmax(1, keepdim=True)
images.append(x.cpu())
labels.append(y.cpu())
probs.append(y_prob.cpu())
images = torch.cat(images, dim=0)
labels = torch.cat(labels, dim=0)
probs = torch.cat(probs, dim=0)
return images, labels, probs
# Getting the predictions
images, labels, probs = get_predictions(model, test_iterator, device)
# It can get these predictions or prediction labels and, by taking the index of the highest predicted probability.
pred_labels = torch.argmax(probs, 1)
# Develop confusion matrix from the actual labels and the predicted labels
def plot_confusion_matrix(labels, pred_labels):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1)
cm = metrics.confusion_matrix(labels, pred_labels)
cm = metrics.ConfusionMatrixDisplay(cm, display_labels=range(10))
cm.plot(values_format='d', cmap='Blues', ax=ax)
plt.savefig('confusion_matrix.png')
plt.show()
plot_confusion_matrix(labels, pred_labels)
# Check whether predicted labels and actual labesl matches or no
corrects = torch.eq(labels, pred_labels)
# FInd out incorrectly classified examples into an array
incorrect_examples = []
for image, label, prob, correct in zip(images, labels, probs, corrects):
if not correct:
incorrect_examples.append((image, label, prob))
incorrect_examples.sort(reverse=True, key=lambda x: torch.max(x[2], dim=0).values)
# Plot the incorrectly predicted images along with how confident they were on the actual label
# Then see how confident they were at the incorrect label.
def plot_most_incorrect(incorrect, n_images):
rows = int(np.sqrt(n_images))
cols = int(np.sqrt(n_images))
fig = plt.figure(figsize=(40, 20))
for i in range(rows * cols):
ax = fig.add_subplot(rows, cols, i + 1)
image, true_label, probs = incorrect[i]
true_prob = probs[true_label]
incorrect_prob, incorrect_label = torch.max(probs, dim=0)
ax.imshow(image.view(28, 28).cpu().numpy(), cmap='bone')
ax.set_title(f'true label: {true_label} ({true_prob:.3f})\n' \
f'pred label: {incorrect_label} ({incorrect_prob:.3f})')
ax.axis('off')
fig.subplots_adjust(hspace=0.5)
plt.savefig('most_incorrect.png')
plt.show()
# Try with 30 incorrectly classified image compared with ground truth and see how confident are the predections
N_IMAGES = 40
plot_most_incorrect(incorrect_examples, N_IMAGES)
# For more understanding it can get the output and intermediate representations from the model and try to visualize them
def get_representations(model, iterator, device):
model.eval()
outputs = []
intermediates = []
labels = []
with torch.no_grad():
for (x, y) in iterator:
x = x.to(device)
y_pred, h = model.forwad_propagation(x)
outputs.append(y_pred.cpu())
intermediates.append(h.cpu())
labels.append(y)
outputs = torch.cat(outputs, dim=0)
intermediates = torch.cat(intermediates, dim=0)
labels = torch.cat(labels, dim=0)
return outputs, intermediates, labels
# Get representations
outputs, intermediates, labels = get_representations(model, train_iterator, device)
# Output representations from the ten dimensional output layer, reduced down to two dimensions (10-dim)
output_pca_data = get_pca(outputs)
def plot_weights(weights, n_weights):
rows = int(np.sqrt(n_weights))
cols = int(np.sqrt(n_weights))
fig = plt.figure(figsize=(40, 20))
for i in range(rows * cols):
ax = fig.add_subplot(rows, cols, i + 1)
ax.imshow(weights[i].view(28, 28).cpu().numpy(), cmap='bone')
ax.axis('off')
plt.savefig('weights_visualization.png')
plt.show()
# Plotting 40 weights
N_WEIGHTS = 40
weights = model.input_fc.weight.data
plot_weights(weights, N_WEIGHTS)
"""### Implementation of the gradient for the regularized neural network"""
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sn
import numpy as np
import pandas as pd
import math
import datetime
import platform
print('Python version:', platform.python_version())
print('Tensorflow version:', tf.__version__)
print('Keras version:', tf.keras.__version__)
mnist_dataset = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist_dataset.load_data()
numbers_to_display = 25
num_cells = math.ceil(math.sqrt(numbers_to_display))
plt.figure(figsize=(10,10))
for i in range(numbers_to_display):
plt.subplot(num_cells, num_cells, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(y_train[i])
plt.show()
(_, IMAGE_WIDTH, IMAGE_HEIGHT) = x_train.shape
IMAGE_CHANNELS = 1
print('IMAGE_WIDTH:', IMAGE_WIDTH);
print('IMAGE_HEIGHT:', IMAGE_HEIGHT);
print('IMAGE_CHANNELS:', IMAGE_CHANNELS);
x_train_with_chanels = x_train.reshape(
x_train.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
x_test_with_chanels = x_test.reshape(
x_test.shape[0],
IMAGE_WIDTH,
IMAGE_HEIGHT,
IMAGE_CHANNELS
)
print('x_train_with_chanels:', x_train_with_chanels.shape)
print('x_test_with_chanels:', x_test_with_chanels.shape)
x_train_normalized = x_train_with_chanels / 255
x_test_normalized = x_test_with_chanels / 255
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Convolution2D(
input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS),
kernel_size=5,
filters=8,
strides=1,
activation=tf.keras.activations.relu,
kernel_initializer=tf.keras.initializers.VarianceScaling()
))
model.add(tf.keras.layers.MaxPooling2D(
pool_size=(2, 2),
strides=(2, 2)
))
model.add(tf.keras.layers.Convolution2D(
kernel_size=5,
filters=16,
strides=1,
activation=tf.keras.activations.relu,
kernel_initializer=tf.keras.initializers.VarianceScaling()
))
model.add(tf.keras.layers.MaxPooling2D(
pool_size=(2, 2),
strides=(2, 2)
))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(
units=128,
activation=tf.keras.activations.relu
));
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(
units=10,
activation=tf.keras.activations.softmax,
kernel_initializer=tf.keras.initializers.VarianceScaling()
))
model.summary()
!pip3 install ann_visualizer
!sudo apt-get install graphviz && pip3 install graphviz
from ann_visualizer.visualize import ann_viz;
#Build your model here
ann_viz(model, title = "Regularized Net")
adam_optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(
optimizer=adam_optimizer,
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy']
)
log_dir=".logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
training_history = model.fit(
x_train_normalized,
y_train,
epochs=10,
validation_data=(x_test_normalized, y_test),
callbacks=[tensorboard_callback]
)
# Commented out IPython magic to ensure Python compatibility.
# %%capture
# train_loss, train_accuracy = model.evaluate(x_train_normalized, y_train)
print('Training loss: ', train_loss)
print('Training accuracy: ', train_accuracy)
# Commented out IPython magic to ensure Python compatibility.
# %%capture
# validation_loss, validation_accuracy = model.evaluate(x_test_normalized, y_test)
print('Validation loss: ', validation_loss)
print('Validation accuracy: ', validation_accuracy)