-
Notifications
You must be signed in to change notification settings - Fork 4
/
04_2_BuildingCNN.py
236 lines (192 loc) · 4.93 KB
/
04_2_BuildingCNN.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
#%% [markdown]
# Train is better than test, means overfitting
# In this context, we need to provide better features from the images
# Any better way to extract features from images
# This process is called as feature extraction.
#
# ## Feature Extraction
# * Fourier transforms
# * Wavelet transforms
# * Histograms of oriented gradients (HOG)
#%%
with open('common.py') as fin:
exec(fin.read())
with open('matplotlibconf.py') as fin:
exec(fin.read())
#%% [markdown]
# # L1: Tensor
#%%
# Scalar is just numbers
scalar = 5
scalar
#%%
# Vector is list of numbers 1D. Tensor of order 1.
v = np.array([1, 5, 3, 2])
v.shape
#%%
# Matrices is tensors of order 2
m = np.array([[1, 5, 3, 2],
[0, 9, 3, 1]])
m.shape
#%% [markdown]
# ## L2
# ## Tensor
# The actual tensor starts with order 3
#%%
t = np.array([[[0, 1, 0],
[5, 0, 2]],
[[1, 2, 4],
[8, 3, 1]]])
t.shape
#%%
img = np.random.randint(255, size=(4,4,3), dtype='uint8')
img
#%%
img.shape
#%%
plt.figure(figsize=(5,5))
plt.subplot(221)
plt.imshow(img)
plt.title('All Channels combined')
#%%
plt.subplot(222)
plt.imshow(img[:, :, 0], cmap='Reds')
plt.title('Red channel')
#%%
plt.subplot(223)
plt.imshow(img[:, :, 1], cmap='Greens')
plt.title('Green channel')
#%%
plt.subplot(224)
plt.imshow(img[:, :, 2], cmap='Blues')
plt.title('Blue channel')
plt.tight_layout()
#%% [markdown]
# # Lab L3 - Building Convolutional Layer
#%%
from keras.layers import Conv2D
from scipy import misc
#%% [markdown]
# * Refer 04_2_1.png (Convolutional kernel)
# * Refer 04_2_2.png (Feature map)
#%%
# loading an example image from scipy.misc
img = misc.ascent()
#%%
plt.figure(figsize=(5,5))
plt.imshow(img, cmap = 'gray')
#%%
img.shape
#%%
# Convolutional Layers wants order-4 tensor as input
# 1 axis of length 1 for color channel
# 1 axis length 1 for dataset index
img_tensor = img.reshape((1, 512, 512, 1))
#%% [markdown]
# Usually filter size is 3x3, 5x5 or 7x7
# For this evaluation, let us use 11x11
#%%
from keras.models import Sequential
from keras.layers import Dense
#%%
model = Sequential()
# 1 filter, all weights to one
model.add(Conv2D(1, (11, 11), kernel_initializer='ones',
input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
model.summary()
#%%
img_pred_tensor = model.predict(img_tensor)
#%%
img_pred = img_pred_tensor[0, :, :, 0]
plt.imshow(img_pred, cmap='gray')
#%% [markdown]
# A convolution with a kernel will produce a new image, whose
# pixels will be combination of the original pixels in a receptive field
# and the values of the weights in the kernel.
# **This image is produced by learning by the network**
#
# Two additional arguments to be considered: **padding** and **stride**
#%%
img_pred_tensor.shape
#%%
img_tensor.shape
#%% [markdown]
# ### Padding
#
# The convolved image is slightly smaller than original due to default padding value as 'valid'.
# * valid - no padding
# * same - pad to keep the same image size (Needed when you think pixels at the border has meaning information)
# **Refer 04_2_3.png
#%%
model = Sequential()
# 1 filter, all weights to one
model.add(Conv2D(1, (11, 11),
padding='same',
kernel_initializer='ones',
input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
padsame_img_tensor = model.predict(img_tensor)
padsame_img_tensor.shape
#%%
plt.imshow(padsame_img_tensor[0, :, :, 0], cmap='gray')
#%% [markdown]
# ### Stride
#
# stride (1, 1) means with no padding, the output image will lose one pixel on each side
#
# increasing stride means skipping few piexels
#
# applicable only image with higher resolution
#%%
model = Sequential()
# 1 filter, all weights to one
model.add(Conv2D(1, (11, 11),
strides = (5, 5),
padding='same',
kernel_initializer='ones',
input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
stride5x5_img_tensor = model.predict(img_tensor)
stride5x5_img_tensor.shape
#%%
plt.imshow(stride5x5_img_tensor[0, :, :, 0], cmap='gray')
#%%
# Asymmerric strides
model = Sequential()
# 1 filter, all weights to one
model.add(Conv2D(1, (11, 11),
strides = (11, 5),
padding='same',
kernel_initializer='ones',
input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
stride11x5_img_tensor = model.predict(img_tensor)
stride11x5_img_tensor.shape
#%%
plt.imshow(stride11x5_img_tensor[0, :, :, 0], cmap='gray')
#%% [markdown]
# # L4 - Pooling
#%%
from keras.layers import MaxPooling2D
from keras.layers import AveragePooling2D
from keras.layers import GlobalMaxPooling2D
#%%
# MaxPooling2D
model = Sequential()
# 1 filter, all weights to one
model.add(MaxPooling2D(pool_size=(5,5),
input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
img_pred = model.predict(img_tensor)[0, :, :, 0]
img_pred.shape
#%%
plt.imshow(img_pred, cmap='gray')
#%%
# GlobalMaxPooling2D
model = Sequential()
# 1 filter, all weights to one
model.add(GlobalMaxPooling2D(input_shape=(512, 512, 1)))
model.compile('adam', 'mse')
img_pred_tensor = model.predict(img_tensor)
img_pred_tensor.shape