/
neuralNetwork.py
476 lines (268 loc) · 10.9 KB
/
neuralNetwork.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
import numpy as np
import copy
import scipy.optimize as spop
import warnings
import neuralNetworkUnit as nnu
import neuralNetworkBranch as nnb
class NeuralNetwork(object):
def __init__(self, nInputs, nOutputs, hiddenLayersDims, outputActivationFunctions = None, outputActivationDerivatives = None, hiddenActivationFunctions = None,\
hiddenActivationDerivatives = None):
"""Constructs a NeuralNetwork object. Input parameters shoudl be
nInputs - The number of inputs to the model
nOutputs - The number of outputs to the model
hiddenLayersDims - a 2-tuple of the form (nHiddenLayers,nUnitsPerLayer), where nUnitsPerLayer excludes the hidden bias unit
outputActivationFunctions - an array of length nOutputs containing activation functions for the outputs
outputActivationDerivatives - an array of length nOutputs containing the first derivatives of the activation functions for the outputs
hiddenActivationFunctions - an array of shape (nHiddenLayers,nUnitsPerLayer) containing activation functions for the hidden units
hiddenActivationDerivatives - an array of shape (nHiddenLayers,nUnitsPerLayer) containing the first derivatives of the activation functions for the hidden units
"""
self._nInputs = nInputs
self._nOutputs = nOutputs
self._nHiddenLayers, self._nUnitsPerLayer = hiddenLayersDims
self._outputActivationFunctions = outputActivationFunctions
self._outputActivationDerivatives = outputActivationDerivatives
self._hiddenActivationFunctions = hiddenActivationFunctions
self._hiddenActivationDerivatives = hiddenActivationDerivatives
self.initialiseActivationFunctions()
self.initialiseNetwork()
self._nBranches = len(self.collectAllBranches())
@property
def nInputs(self):
"""The number of inputs to the model
"""
return self._nInputs
@property
def nOutputs(self):
"""The number of outputs to the model
"""
return self._nOutputs
@property
def nHiddenLayers(self):
"""The number of hidden layers
"""
return self._nHiddenLayers
@property
def nUnitsPerLayer(self):
"""The number of hidden units on each of the hidden layers
"""
return self._nUnitsPerLayer
@property
def outputActivationFunctions(self):
"""The activation functions for the output layer
"""
return self._outputActivationFunctions
@property
def outputActivationDerivatives(self):
"""The first derivatives of the activation functions for the output layer
"""
return self._outputActivationDerivatives
@property
def hiddenActivationFunctions(self):
"""The activation functions for the hidden layers
"""
return self._hiddenActivationFunctions
@property
def hiddenActivationDerivatives(self):
"""The first derivatives of the activation functions for the hidden layers
"""
return self._hiddenActivationDerivatives
@property
def nBranches(self):
"""The number of branches in the network
"""
return self._nBranches
def initialiseActivationFunctions(self):
"""Set the activation functions to common defaults if we haven't been given any explicitly
"""
###uniform for output units
if self._outputActivationFunctions == None or self._outputActivationDerivatives == None:
self._outputActivationFunctions = []
self._outputActivationDerivatives = []
actFunc = lambda x : x
dActFunc = lambda x : 1.0
for i in range(self.nOutputs):
self._outputActivationFunctions.append(actFunc)
self._outputActivationDerivatives.append(dActFunc)
self._outputActivationFunctions = np.array(self._outputActivationFunctions)
self._outputActivationDerivatives = np.array(self._outputActivationDerivatives)
if self._hiddenActivationFunctions == None or self._hiddenActivationDerivatives == None:
self._hiddenActivationFunctions = []
self._hiddenActivationDerivatives = []
for i in range(self.nHiddenLayers):
fTemp = []
dTemp = []
#Make the default sigmoid the one suggested in LeCun et al 1998
twist = 0.01
a = 1.7159
c = 2.0/3.0
actFunc = lambda x : a*np.tanh(c*x) + twist*x
dActFunc = lambda x : twist + a*c*(1.0 - (np.tanh(c*x)**2.0))
# actFunc = lambda x : np.tanh(x)
# dActFunc = lambda x : 1.0 - np.tanh(x)**2.0
#plus all of the bias
for j in range(self.nUnitsPerLayer+1):
fTemp.append(actFunc)
dTemp.append(dActFunc)
self._hiddenActivationFunctions.append(fTemp)
self._hiddenActivationDerivatives.append(dTemp)
self._hiddenActivationFunctions = np.array(self._hiddenActivationFunctions)
self._hiddenActivationDerivatives = np.array(self._hiddenActivationDerivatives)
def initialiseNetwork(self):
self.initialiseInputLayer()
self.initialiseHiddenLayers()
self.initialiseOutputLayer()
def initialiseInputLayer(self):
#make nInputs input units, plus 1 for the bias
self.inputLayer = []
unit = nnu.NeuralNetworkUnit('bias',lambda x:x,lambda x:1.0)
self.inputLayer.append(unit)
for i in range(self.nInputs):
unit = nnu.NeuralNetworkUnit('input',lambda x:x,lambda x:1.0)
self.inputLayer.append(unit)
self.inputLayer = np.array(self.inputLayer)
def initialiseHiddenLayers(self):
#make all of the hidden layers of the Neural Network, with the zero'th element of each layer as the bias
self.hiddenLayers = []
#make first bias, and connect the first hidden layer to the input layer
layer = []
biasUnit = nnu.NeuralNetworkUnit('bias',lambda x:x,lambda x:1.0)
layer.append(biasUnit)
for i in range(self.nUnitsPerLayer):
unit = nnu.NeuralNetworkUnit('hidden',self.hiddenActivationFunctions[0,i+1],self.hiddenActivationDerivatives[0,i+1])
for inUnit in self.inputLayer:
branch = nnb.NeuralNetworkBranch(inUnit,unit)
unit.attachBranchIn(branch)
inUnit.attachBranchOut(branch)
layer.append(unit)
self.hiddenLayers.append(layer)
#now make the rest of the hidden layers, connecting them to the previous one
for i in range(1,self.nHiddenLayers):
lastLayer = self.hiddenLayers[-1]
newLayer = []
biasUnit = nnu.NeuralNetworkUnit('bias',self.hiddenActivationFunctions[i,0],self.hiddenActivationDerivatives[i,0])
newLayer.append(biasUnit)
for j in range(self.nUnitsPerLayer):
unit = nnu.NeuralNetworkUnit('hidden',self.hiddenActivationFunctions[i,j+1],self.hiddenActivationDerivatives[i,j+1])
for lastUnit in lastLayer:
branch = nnb.NeuralNetworkBranch(lastUnit,unit)
unit.attachBranchIn(branch)
lastUnit.attachBranchOut(branch)
newLayer.append(unit)
self.hiddenLayers.append(newLayer)
self.hiddenLayers = np.array(self.hiddenLayers)
def initialiseOutputLayer(self):
#finally, make the output layer, connecting it to the last hidden layer. This one doesn't have a bias
self.outputLayer = []
lastHiddenLayer = self.hiddenLayers[-1]
for i in range(self.nOutputs):
unit = nnu.NeuralNetworkUnit('output',self.outputActivationFunctions[i],self.outputActivationDerivatives[i])
for hiddenUnit in lastHiddenLayer:
branch = nnb.NeuralNetworkBranch(hiddenUnit,unit)
unit.attachBranchIn(branch)
hiddenUnit.attachBranchOut(branch)
self.outputLayer.append(unit)
self.outputLayer = np.array(self.outputLayer)
def collectAllBranches(self):
"""Helper method to collect references to all branches in a standard way, so that we can work out their
derivatives and update the weights.
Reads through network units from top to bottom, left to right, taking the branches to the right in the order they're stored
"""
allBranches = []
for unit in self.inputLayer:
for branch in unit.branchesOut:
allBranches.append(branch)
for layer in self.hiddenLayers:
for unit in layer:
for branch in unit.branchesOut:
allBranches.append(branch)
for unit in self.outputLayer:
for branch in unit.branchesOut:
allBranches.append(branch)
return allBranches
def updateWeights(self,weightUpdate):
"""Given a set of weight updates for the branches calculated in the order in collectAllBranches(), update the weights!
"""
branches = self.collectAllBranches()
for i in range(self.nBranches):
branches[i].weight -= weightUpdate[i]
def reassignWeights(self,weights):
"""Given a set of weights for the branches calculated in the order in collectAllBranches(), change the weights on all branches (useful for numerical checking)
"""
branches = self.collectAllBranches()
for i in range(self.nBranches):
branches[i].weight = weights[i]
def feedForward(self, inputs):
"""Propagate the inputs through the network
"""
inputs = np.atleast_1d(inputs)
if not len(inputs) == self.nInputs:
raise ValueError("The input vector is the wrong length for this network")
#don't forget we have a bias unit in here too
for i in range(1,self.nInputs+1):
self.inputLayer[i].activation = inputs[i-1]
self.inputLayer[i].output = inputs[i-1]
for layer in self.hiddenLayers:
for unit in layer:
unit.forwardValue()
for unit in self.outputLayer:
unit.forwardValue()
def copy(self):
return copy.deepcopy(self)
def getWeights(self):
branches = self.collectAllBranches()
weights = []
for b in branches:
weights.append(b.weight)
return np.atleast_1d(weights)
def __call__(self,inputs):
self.feedForward(inputs)
outputs = []
for unit in self.outputLayer:
outputs.append(unit.output)
return np.atleast_1d(outputs)
def makeFastFeedForwardFunction(self):
"""A faster, vectorisable way of feeding forward. DOESNT WORK FOR DIFFERENT ACTIVATION FUNCTIONS
"""
outWeightMatrix = []
for unit in self.outputLayer:
row = []
for b in unit.branchesIn:
print b.weight
row.append(b.weight)
outWeightMatrix.append(row)
outWeightMatrix = np.array(outWeightMatrix).squeeze()
hiddenMatrices = []
for layer in self.hiddenLayers:
matrix = []
#ignore the bias unit, since it has no branches in
for unit in layer[1:]:
row = []
for b in unit.branchesIn:
row.append(b.weight)
matrix.append(row)
matrix = np.array(matrix)
hiddenMatrices.append(matrix)
hidActFunc = (self.hiddenLayers[0])[1].activationFunction
outActFunc = self.outputLayer[0].activationFunction
def ffFunc(inp):
forward = np.insert(inp.T,0,1.0,axis=0)
for matrix in hiddenMatrices:
next = np.dot(matrix,forward)
next = hidActFunc(next)
forward = np.insert(next,0,1.0,axis=0)
out = np.dot(outWeightMatrix,forward)
return outActFunc(out)
return ffFunc
def printNetwork(self):
"""Print all of the information about the network, for debugging
"""
i = 0
for branch in self.collectAllBranches():
print 'branch', i
print 'weight', branch.weight
lUnit = branch.leftUnit
rUnit = branch.rightUnit
print 'left unit type/activation/output/delta', lUnit.unitType, lUnit.activation, lUnit.output, lUnit.delta
print 'right unit type/activation/output/delta', rUnit.unitType, rUnit.activation, rUnit.output, rUnit.delta
print '\n'
i+=1