-
Notifications
You must be signed in to change notification settings - Fork 1
/
image_classification_mnist_convolutionday8.py
executable file
·166 lines (122 loc) · 4.21 KB
/
image_classification_mnist_convolutionday8.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
# -*- coding: utf-8 -*-
"""Image Classification mnist-Convolution.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1T9hF8yEd_nQkYN-NqfRawXBSvED0Bwdb
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
import random
import seaborn as sns
(xtr,ytr),(xts,yts) = mnist.load_data()
y_true = yts
print('xtr shape',xtr.shape,sep=':')
print('ytr shape',ytr.shape,sep=':')
n_cols = 5
n_classes = 10
fig,axes = plt.subplots(nrows=n_classes,ncols=n_cols,figsize=(5,10))
fig.tight_layout()
for i in range(n_cols):
for j in range(n_classes):
images = xtr[ytr==j]
selected_image = images[random.randint(0,(len(images)-1)),:,:]
axes[j][i].imshow(selected_image,cmap='gray')
axes[j][i].axis('off')
if i ==2:
axes[j][i].set_title(str(j))
sns.countplot(ytr)
plt.show()
"""# Pre-processing"""
xtr = xtr.reshape(xtr.shape[0],28,28,1)
xtr = xtr/255
xts = xts.reshape(xts.shape[0],28,28,1)
xts = xts/255
"""# OneHotEncoding ytr array"""
from keras.utils.np_utils import to_categorical
ytr = to_categorical(ytr,10) #10 represents number of classes/categories
yts = to_categorical(yts,10)
ytr.shape[1]
"""Image Augmentation"""
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(width_shift_range=0.1,
height_shift_range=0.1,
zoom_range = 0.1,
rotation_range=10)
"""# creating Nural Net model"""
from keras.models import Sequential
from keras.layers import Dense , Flatten , Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.optimizers import Adam , RMSprop
def create_model():
model = Sequential()
model.add(Conv2D(32,kernel_size=(5,5),input_shape = (28,28,1),
activation='relu'))
model.add(Conv2D(32,(5,5),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dense(256,activation='relu'))
model.add(Dense(10,activation='softmax'))
model.compile(Adam(lr=0.001),loss='categorical_crossentropy',
metrics=['accuracy'])
return model
model = create_model()
print(model.summary())
h = model.fit_generator(datagen.flow(xtr,ytr,batch_size=50),steps_per_epoch=2000,
epochs=10,
verbose=1,
validation_data=(xts,yts))
plt.plot(h.history['loss'],label='loss')
plt.plot(h.history['val_loss'],label='val_loss')
plt.legend()
plt.show()
plt.plot(h.history['acc'],label='acc')
plt.plot(h.history['val_acc'],label='val_acc')
plt.legend()
plt.show()
model.save('model_mnist.h5')
from google.colab import files
files.download('model_mnist.h5')
import requests
from PIL import Image
url = 'https://i.stack.imgur.com/RdEpj.png'
response = requests.get(url,stream=True)
img = Image.open(response.raw)
plt.imshow(img,cmap='gray')
plt.grid()
plt.show()
import cv2
img = np.asarray(img)
img = cv2.resize(img,(28,28))
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#img = cv2.bitwise_not(img) #only required when image is in white background
plt.imshow(img,cmap='gray')
plt.show()
img = img/255
img = img.reshape(1,28,28,1)
prediction = model.predict_classes(img)
print('prediction is:',str(prediction))
from keras.models import Model
layer1 = Model(inputs=model.layers[0].input, outputs=model.layers[0].output)
layer2 = Model(inputs=model.layers[0].input, outputs=model.layers[2].output)
visual_layer1, visual_layer2 = layer1.predict(img), layer2.predict(img)
print(visual_layer1.shape)
print(visual_layer2.shape)
#layer 1
plt.figure(figsize=(10, 6))
for i in range(32):
plt.subplot(8, 4, i+1)
plt.imshow(visual_layer1[0, :, :, i], cmap=plt.get_cmap('jet'))
plt.axis('off')
#layer 2
plt.figure(figsize=(10, 6))
for i in range(32):
plt.subplot(8, 8, i+1)
plt.imshow(visual_layer2[0, :, :, i], cmap=plt.get_cmap('jet'))
plt.axis('off')