-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheachmodule.py
453 lines (306 loc) · 12.3 KB
/
eachmodule.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
import numpy # Python's mathematical library
import Image # To convert image to pixels
from procedures import *
import time # To calculate time
import pickle # To write and read files
import matplotlib.pyplot as plt # Graphical representation
numpy.set_printoptions(threshold=numpy.nan)
numOfFiltersLayer1 = 20
numOfFiltersLayer2 = 40
# height and width of the filters
fsize = 5
alpha = 0.1
# epochs = 2000
numofInputImages = 4
numOfInputs1 = 28*28
numOfOutputs1 = 24*24
numOfInputs2 = numOfFiltersLayer1*12*12
numOfOutputs2 = 8*8
numOfHiddenNeurons = 200
numOfOutputNeurons = 2
target = numpy.array([[0.,0.],[0.,1.],[1.,0.],[1.,1.]])
# Activation Function - Sigmoid
def sigmoid(x):
out = 1/(1+numpy.exp(-x))
return out
# Sigmoid Derivative
def derivative(x):
return x*(1-x)
# Z-score normalization (also called batch-normalization?)
def zscore(x):
normalized = []
length = x.shape[1]
# (x-mean)/standard deviation
for i in range(length):
col = x[i]
mean = numpy.mean(col)
std = numpy.std(col)
if std !=0:
newval = (col - mean)/(std)
normalized.append(newval)
else:
normalized.append(col)
return normalized
# Reads and converts the input images into array of pixels
def readAllImages():
data = []
for i in range(numofInputImages):
name = './dataset/'+str(i)+'.jpg'
image = Image.open(name)
im = numpy.array( image, dtype="double" )
# im = numpy.roll(im,-1,axis=0) # expand up
# im = numpy.roll(im,1,axis=0) # expand down
# im = numpy.roll(im,2,axis=1) # expand right
# im = numpy.roll(im,-2,axis=1) # expand left
# Normalizing data so that each column of Z has mean 0 and standard 1
# also called as Z-score normalization
im = zscore(im)
data.append(im)
return data
start = time.time()
imagedata = readAllImages() # array of pixel data of all the input data
tt = time.time() - start
print ''
print 'Time taken to read and normalize the training dataset is: '+str(tt)
p = Procedures()
filters1 = []
filters2 = []
err_hl = []
err_FC = []
err_c2 = []
# # Creating filters for conv layer1
# # 20*1*5*5
# filters1 = p.initFilters(numOfFiltersLayer1, numOfInputs1, numOfOutputs1, fsize, 1)
# # print filters1[0]
# # 40*20*5*5
# filters2 = p.initFilters(numOfFiltersLayer2, numOfInputs2, numOfOutputs2, fsize, numOfFiltersLayer1)
# # print filters2[0]
# # Initialising weights of FC Layer
# weights_FC = p.initWeights(640,numOfHiddenNeurons) # FC.shape[0]=640
# # Initialising weights of Hidden Layer
# weights_HL = p.initWeights(numOfHiddenNeurons, numOfOutputNeurons)
# # Initialise biases
# # Biases of Convolution layer 1
# b1 = p.initBias(numOfFiltersLayer1)
# b2 = p.initBias(numOfFiltersLayer2)
# bhl = p.initBias(1)
# bFC = p.initBias(1)
f = open('./weights/filters1.txt')
filters1 = pickle.load(f)
f.close()
f = open('./weights/filters2.txt')
filters2 = pickle.load(f)
f.close()
f = open('./weights/FC_to_HL.txt')
weights_FC = pickle.load(f)
f.close()
f = open('./weights/HL_to_output.txt')
weights_HL = pickle.load(f)
f.close()
f = open('./weights/b1.txt')
b1 = pickle.load(f)
f.close()
f = open('./weights/b2.txt')
b2 = pickle.load(f)
f.close()
f = open('./weights/bhl.txt')
bhl = pickle.load(f)
f.close()
f = open('./weights/bFC.txt')
bFC = pickle.load(f)
f.close()
totalloss = []
tt1=0
tt2=0
tt3=0
tt4=0
tt5=0
tt6=0
tt7=0
tt8 =0
# Start the timer
start = time.time()
epochs = 1
# Start the training procedure
for iterat_epoch in range(epochs):
# print 'Running epoch: ' + str(iterat_epoch) + ' ....'
for iterat_image in range(numofInputImages):
# Read one input at a time
input_data = imagedata[iterat_image]
# -----------------------------------------------------------------------------------------------
# CONVOLUTION --> SIGMOID (Activation Fn) --> POOLING (FIRST ITERATION)
# -----------------------------------------------------------------------------------------------
# -------------------------------------- CONVOLUTION --------------------------------------------
input_data_3d = numpy.reshape(input_data, (1,28,28))
# print input_data_3d
start = time.time()
convolution_layer_1 = p.convolution(input_data_3d, filters1, numOfFiltersLayer1, 1, fsize, b1)
tt1 += time.time() - start
convolution_layer_1_shape = array(convolution_layer_1).shape
# Batch normalization
convolution_layer_1_values=[]
for i in range(convolution_layer_1_shape[0]):
convolution_layer_1_values.append(zscore(convolution_layer_1[0]))
# -------------------------------------- SIGMOID ACTIVATION --------------------------------------------
sigmoid_convLayer_1 = sigmoid(array(convolution_layer_1_values))
# -------------------------------------- POOLING --------------------------------------------
start = time.time()
pool_layer_1,index1 = p.pooling(sigmoid_convLayer_1, numOfFiltersLayer1)
tt2 += time.time() - start
# -----------------------------------------------------------------------------------------------
# CONVOLUTION --> SIGMOID (Activation Fn) --> POOLING (SECOND ITERATION)
# -----------------------------------------------------------------------------------------------
# -------------------------------------- CONVOLUTION --------------------------------------------
start = time.time()
convolution_layer_2 = p.convolution(array(pool_layer_1), filters2, numOfFiltersLayer2, numOfFiltersLayer1, fsize, b2)
tt3 += time.time() - start
convolution_layer_2_shape = array(convolution_layer_2).shape
# print convolution_layer_2
# Batch normalization
convolution_layer_2_values=[]
for i in range(convolution_layer_2_shape[0]):
convolution_layer_2_values.append(zscore(convolution_layer_2[0]))
# print convolution_layer_2_valu es[0]
# -------------------------------------- SIGMOID ACTIVATION --------------------------------------------
sigmoid_convLayer_2 = sigmoid(array(convolution_layer_2_values).astype(numpy.float64))
# -------------------------------------- POOLING --------------------------------------------
start = time.time()
pool_layer_2,index2 = p.pooling(sigmoid_convLayer_2, numOfFiltersLayer2)
tt4 += time.time() - start
# ---------------------------------- END OF SECOND ITERATION ---------------------------------------
# --------------------------------------------------------------------------------------------------
# ------------------------------[ FC --> HIDDEN LAYER --> OUTPUT ]----------------------------------
# --------------------------------------------------------------------------------------------------
# ----------------------------------- FULLY CONNECTED LAYER ----------------------------------------
FC = array(pool_layer_2).ravel()
# ---------------------------------------- HIDDEN LAYER ----------------------------------------
start = time.time()
hidden_values = numpy.dot( weights_FC.T, FC) + bhl
sigmoid_hidden_values = sigmoid(hidden_values)
tt5 += time.time() - start
# ------------------------------------------- OUTPUT ----------------------------------------
output_values = numpy.dot(weights_HL.T, sigmoid_hidden_values) + bFC
start = time.time()
output = sigmoid(output_values)
tt6 += time.time() - start
# if iterat_epoch%100 == 0:
# print '---------------------------------------------------------'
# print 'Output for image with label '+str(iterat_image)+' is:'
# print output
# print '---------------------------------------------------------'
# if iterat_epoch == epochs-1:
# print '---------------------------------------------------------'
# print 'Final Output for image with label '+str(iterat_image)+' is:'
# print output
# print '---------------------------------------------------------'
# ----------------------------------- END OF FORWARD PROPAGATION -----------------------------------
# --------------------------------------------------------------------------------------------------
# ---------------------------------------- BACK PROPAGATION ----------------------------------------
# --------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
# -------- [ CONVOLUTION LAYER 1 <-- CONVOLUTION LAYER 2 <-- FC <-- HIDDEN LAYER <-- OUTPUT ] ------
# --------------------------------------------------------------------------------------------------
# for i in range(8):
# print(target[i][0]*4) + (target[i][1]*2) + (target[i][2]*1)
start = time.time()
error = target[iterat_image] - output
loss = 0.5*error**2
totalloss.append(numpy.sum(loss))
# ------------------------------ Hidden Layer <-- Output -----------------------------------
slope_output_layer = derivative(output)
# Change factor
d_output = error*slope_output_layer
# dw - Change in weight
dweight_output = numpy.outer(sigmoid_hidden_values, d_output)
# + because -*- = +
weights_HL = weights_HL + alpha*(dweight_output)
bhl += alpha*numpy.sum(d_output)
# -------------------------------- FC <-- Hidden Layer -----------------------------------
slope_hidden_layer = derivative(sigmoid_hidden_values)
error_hidden_layer = numpy.dot(weights_HL, d_output)
err_hl.append(numpy.sum(0.5*error_hidden_layer**2))
d_hidden_layer = error_hidden_layer*slope_hidden_layer
dweight_hidden = numpy.outer(FC, d_hidden_layer)
weights_FC = weights_FC + alpha*(dweight_hidden)
bFC += alpha*numpy.sum(d_hidden_layer)
# ----------------------------- CONVOLUTION LAYER 2 <-- FC -----------------------------------
slope_FC = derivative(FC)
error_FC = numpy.dot( weights_FC, d_hidden_layer)
err_FC.append(numpy.sum(0.5*error_FC**2))
d_FC = error_FC*slope_FC
d_FC_3D = numpy.reshape(d_FC, (numOfFiltersLayer2, 4,4))
d_FC_2D = numpy.reshape(d_FC, (numOfFiltersLayer2, 4*4))
index2_reshape = numpy.reshape(index2, (numOfFiltersLayer2,4*4))
d_FC_new = []
for i in range(numOfFiltersLayer2):
scalar_dw = numpy.outer(d_FC_3D[i], pool_layer_1)
dw_c2 = numpy.sum(scalar_dw)
w = filters2[i]
# Weight updation
filters2[i] = w + alpha*(dw_c2)
b2[i] += alpha*numpy.sum(d_FC_2D[i])
tomodify = numpy.zeros((8*8))
xx = index2_reshape[i].astype(int)
yy = d_FC_2D[i]
for (ind, rep) in zip(xx, yy):
tomodify[ind] = rep
d_FC_new.append(tomodify)
d_FC_new_reshape = numpy.reshape(d_FC_new, (40,8,8))
# --------------------- CONVOLUTION LAYER 1 <-- CONVOLUTION LAYER 2 -----------------------------------
errr=[]
for n2 in range(numOfFiltersLayer2):
err=[]
for n1 in range(numOfFiltersLayer1):
new = numpy.zeros((12,12))
for ii in range(8):
for jj in range(8):
for k in range(5):
for l in range(5):
new[ii+k][jj+l] += d_FC_new_reshape[n2][ii][jj] * filters2[n2][n1][k][l]
err.append(new)
errr.append(err)
slope_conv2 = derivative(array(pool_layer_1))
error_conv2 = numpy.sum(errr,axis=0)
err_c2.append(numpy.sum(0.5*error_conv2**2))
d_c2 = error_conv2*slope_conv2
for i in range(numOfFiltersLayer1):
scalar_dw_c1 = numpy.outer(d_c2[i], input_data)
dw_c1 = numpy.sum(scalar_dw_c1)
w_c1 = filters1[i]
# Weight updation
filters1[i] = w_c1 + alpha*(dw_c1)
b1[i] += alpha*numpy.sum(d_c2[i])
tt8 += time.time() - start
tt7 = time.time()-start
hours = tt/(3600)
print ''
print 'Total Time elapsed in training the system is '+str(tt7)+' seconds!'
print ''
print ''
print 'The average time taken for Convolution module is '+str(tt1/4)+' seconds!'
print 'The output shape is ' + str(convolution_layer_1_shape)
print ''
print ''
print 'The average time taken for Pooling module is '+str(tt2/4)+' seconds!'
print 'The output shape is ' + str(array(pool_layer_1).shape)
print ''
print ''
print 'The average time taken for Convolution module is '+str(tt3/4)+' seconds!'
print 'The output shape is ' + str(convolution_layer_2_shape)
print ''
print ''
print 'The average time taken for Pooling module is '+str(tt4/4)+' seconds!'
print 'The output shape is ' + str(array(pool_layer_2).shape)
print ''
print ''
print 'The average time taken at FC layer '+str(tt5/4)+' seconds!'
print 'The output shape is ' + str(array(FC).shape)
print ''
print ''
print 'The average time taken at Hidden layer '+str(tt6/4)+' seconds!'
print 'The output shape is ' + str(array(hidden_values).shape)
print ''
print ''
print 'The average time taken for Back-Propagation is '+str(tt8/4)+' seconds!'
print ''
print ''