-
Notifications
You must be signed in to change notification settings - Fork 1
/
NIT6004 Project 1_Neural Network and Deep Learning.py
211 lines (103 loc) · 3.31 KB
/
NIT6004 Project 1_Neural Network and Deep Learning.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
#!/usr/bin/env python
# coding: utf-8
# ### Install Required Libraries
# In[1]:
#!pip install numpy
# In[2]:
#!pip install pandas opencv-python keras tensorflow
# In[3]:
#!pip install pandas opencv-python keras tensorflow
# ### Task 1: Import libraries
# In[4]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
import cv2
# ### Task 2: Import Dataset:
# In[19]:
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# In[20]:
x_train.shape
# In[21]:
print(x_test.shape, y_test.shape)
# Let's test any data sample to check if it is corect data or not
# In[22]:
print("label=",y_train[0])
plt.imshow(x_train[0])
# ### Task 2: Data Preprocessing
# In[23]:
print(x_train.max(), x_train.min(), x_test.max(), x_test.min())
# - The training data ranges between 0-255, now we will rescale the feature values to be in the range [0, 1]
# In[24]:
x_train_processed, x_test_processed = x_train / 255.0, x_test / 255.0
# In[25]:
print(x_train_processed.max(), x_train_processed.min(), x_test_processed.max(), x_test_processed.min())
# ### Task 3: Build a Classifier using MLP (Multi Layer perceptron)
# In[13]:
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Flatten, Dense,Dropout
from keras.optimizers import Adam
# In[26]:
model = keras.models.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
# In[28]:
model.summary()
# ### Task 4: Compile the Model
# In[32]:
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# ### Task 5: Train and Test the model.
# In[34]:
history = model.fit(x_train_processed, y_train, epochs=5)
history
# # Evaluation
# In[37]:
test_loss, test_acc = model.evaluate(x_test_processed, y_test)
# In[38]:
print("Test Loss: ", test_loss)
print("Test Accuracy: ", test_acc)
# - Access Loss and Accuracy details from the training history
# In[41]:
training_loss = history.history['loss']
training_accuracy = history.history['accuracy']
# In[76]:
# Create subplots for loss and accuracy
plt.figure(figsize=(8, 3))
# Loss subplot
plt.subplot(1, 2, 1)
plt.plot(training_loss, label='Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
# Accuracy subplot
plt.subplot(1, 2, 2)
plt.plot(training_accuracy, label='Training Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# - As we can see in the graph, loss has been decreased with each epoch where accuracy has been increased
# ### Let's make predictions on the test test and check whether those predictions are correct or not
# In[53]:
model.predict(x_test_processed)[0].argmax()
# In[54]:
y_test[0]
# In[71]:
predictions = model.predict(x_test_processed)
plt.figure(figsize=(12, 5))
for i in range(9):
plt.subplot(1, 9, i+1)
prediction = predictions[i].argmax()
image =plt.imshow(x_test_processed[i])
plt.xlabel('prediction: '+str(prediction))
plt.xticks([]) # Hide the x-axis scale and ticks
plt.yticks([]) # Hide the y-axis scale and ticks