-
Notifications
You must be signed in to change notification settings - Fork 0
/
neural2.py
426 lines (323 loc) · 11.4 KB
/
neural2.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
import pprint
import turtle
import time
import math
import random
turtle.shape("circle")
turtle.turtlesize(0.5, 0.5)
turtle.ht()
turtle.penup()
turtle.speed(0)
turtle.setup(1200, 600)
turtle.tracer(50, 0)
class Network:
"""docstring for Network"""
def __init__(self):
self.layers = [Layer("input"), Layer("hidden"), Layer("output")]
def getLayer(self, layerName):
for layer in self.layers:
if layer.name == layerName:
return layer
return
def addNeuron(self, layerName, neuron):
if not neuron in self.getLayer(layerName).neurons:
self.getLayer(layerName).addNeuron(neuron)
def getNeuronsFromLayer(self, layerName):
return self.getLayer(layerName).neurons
def getAllNeurons(self):
allNeurons = []
for layer in self.layers:
allNeurons.extend(layer.neurons)
return allNeurons
def isNeuronInLayer(self, neuron, layerName):
for networkNeuron in self.getNeuronsFromLayer(layerName):
if networkNeuron == neuron:
return True
return False
def getAllConnections(self):
allConnections = []
for neuron in self.getAllNeurons():
for inputConnection in neuron.inputConnections:
alreadyAdded = False
for connection in allConnections:
if connection.equals(inputConnection):
alreadyAdded = True
break
if not alreadyAdded:
allConnections.append(inputConnection)
for outputConnection in neuron.outputConnections:
alreadyAdded = False
for connection in allConnections:
if connection.equals(outputConnection):
alreadyAdded = True
break
if not alreadyAdded:
allConnections.append(outputConnection)
return allConnections
class Layer:
def __init__(self, name):
self.name = name
self.neurons = []
def addNeuron(self, neuron):
self.neurons.append(neuron)
class DrawableObject:
def __init__(self, type, penColor = "black", fillColor = "black"):
self.type = type
self.penColor = penColor
self.fillColor = fillColor
def getType(self):
return self.type;
def draw(self, turtle):
self.beforeDraw(turtle)
self.doDraw(turtle)
self.afterDraw(turtle)
return
def doDraw(self, turtle):
return
def beforeDraw(self, turtle):
turtle.color(self.penColor, self.fillColor)
return
def afterDraw(self, turtle):
return
class DrawableCircle(DrawableObject):
def __init__(self, x = 0, y = 0, radius = 10, penColor = "black", fillColor = "black"):
DrawableObject.__init__(self, 'circle', penColor, fillColor)
self.x = x
self.y = y
self.radius = radius
def doDraw(self, turtle):
turtle.pu()
turtle.setpos(self.x, self.y)
turtle.begin_fill()
turtle.circle(self.radius)
turtle.end_fill()
return
class DrawableLine(DrawableObject):
def __init__(self, x1 = 0, y1 = 0, x2 = 0, y2 = 0, penColor = "black", fillColor = "black"):
DrawableObject.__init__(self, 'line', penColor, fillColor)
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def doDraw(self, turtle):
turtle.pu()
turtle.setpos(self.x1, self.y1)
turtle.pd()
turtle.goto(self.x2, self.y2)
turtle.pu()
return
class Neuron(DrawableCircle):
def __init__(self, value = 0.0):
DrawableCircle.__init__(self, 0, 0, 10, "black", "gray")
self.value = value
self.inputConnections = []
self.outputConnections = []
self.biasValue = -1
self.biasWeight = 0.5
self.error = 0
def addInputConnection(self, neuron):
connection = Connection(neuron, self)
if not self.hasInputConnection(connection):
self.inputConnections.append(connection)
neuron.outputConnections.append(connection)
def addOutputConnection(self, neuron):
connection = Connection(self, neuron)
if not self.hasOutputConnection(connection):
self.outputConnections.append(connection)
neuron.inputConnections.append(connection)
def hasInputConnection(self, connection):
for inputConnection in self.inputConnections:
if connection.equals(inputConnection):
return True
return False
def hasOutputConnection(self, connection):
for outputConnection in self.outputConnections:
if connection.equals(outputConnection):
return True
return False
def doDraw(self, turtle):
DrawableCircle.doDraw(self, turtle)
# Tutaj mozesz sobie dorysowywac wszystko zwiazane z neuronem
turtle.write("V: " + str(self.value) + " | Er: " + str(self.error) + " | Bw: " + str(self.biasWeight) + " | Bv: " + str(self.biasValue))
def calculateOutput(self):
# Suma inputow
inputTotal = 0
if len(self.inputConnections):
for inputConnection in self.inputConnections:
inputTotal += inputConnection.input.calculateOutput() * inputConnection.weight
else:
return self.value
# Odejmij bias
inputTotal += self.biasValue * self.biasWeight
# Activation function - sigmoid
self.value = 1 / (1 + math.exp(inputTotal * -1))
# Sigmoid rounding
if self.value > 0.9999:
self.value = 1
if self.value < 0.0001:
self.value = 0
# Funkcja aktywacyjna
return self.value
def calculateError(self, desiredValue):
error = 0
if not len(self.outputConnections):
error = self.value * (1 - self.value) * (desiredValue - self.value)
else:
outputErrorTotal = 0
for outputConnection in self.outputConnections:
outputErrorTotal += outputConnection.output.calculateError(desiredValue)
error = self.value * (1 - self.value) * outputErrorTotal
self.error = error
return error
def updateWeight(self, learningRate = 0.5):
self.biasWeight += learningRate * self.biasValue * self.error
class Connection(DrawableLine):
def __init__(self, input, output, weight = 0.5, x1 = 0, y1 = 0, x2 = 0, y2 = 0, penColor = "black", fillColor = "black"):
DrawableLine.__init__(self, 0, 0, 0, 0, "black", "black")
self.weight = weight
self.input = input
self.output = output
def equals(self, connection):
return self.input == connection.input and self.output == connection.output
def doDraw(self, turtle):
DrawableLine.doDraw(self, turtle)
turtle.goto((self.x1 + self.x2)/2, (self.y1 + self.y2)/2)
turtle.write("W: " + str(self.weight))
turtle.goto((self.x1 + self.x2)/2, (self.y1 + self.y2)/2)
turtle.pd()
turtle.color("red")
turtle.goto(self.x2, self.y2)
turtle.pu()
def updateWeight(self, learningRate = 0.5):
self.weight += learningRate * self.input.value * self.output.error
class NetworkBuilder:
def __init__(self):
pass
def build(self):
pass #finish later :* rob
def buildSimple(self, neuronsInInput, neuronsInHidden, neuronsInOutput):
network = Network()
for neurons in range(neuronsInInput):
network.addNeuron('input', Neuron())
for neurons in range(neuronsInHidden):
network.addNeuron('hidden', Neuron())
for neurons in range(neuronsInOutput):
network.addNeuron('output', Neuron())
for inputNeuron in network.getNeuronsFromLayer("input"):
for hiddenNeuron in network.getNeuronsFromLayer("hidden"):
inputNeuron.addOutputConnection(hiddenNeuron)
for hiddenNeuron in network.getNeuronsFromLayer("hidden"):
for outputNeuron in network.getNeuronsFromLayer("output"):
hiddenNeuron.addOutputConnection(outputNeuron)
return network
class Screen():
def __init__(self, turtle, drawableObjects = []):
self.drawableObjects = drawableObjects
self.turtle = turtle.clone()
# Turtle follower jest po to zeby podtrzymywac stary rysunek w momencie kiedy jest updatowany.
# Nowy obrazek jest narysowany na stary, i stary usuwany
self.turtleFollower = self.turtle.clone()
self.height = self.turtle.getscreen().window_height()
self.width = self.turtle.getscreen().window_width()
def drawWith(self, turtle):
self.height = turtle.getscreen().window_height()
self.width = turtle.getscreen().window_width()
for drawableObject in self.drawableObjects:
drawableObject.draw(turtle)
turtle.getscreen().update()
def step(self, delay = 1):
self.turtle.clear()
self.drawWith(self.turtle)
self.turtleFollower.clear()
self.drawWith(self.turtleFollower)
time.sleep(delay)
class UIHelper():
def __init__(self, screen):
self.screen = screen
def tx(self, x):
return x - (self.screen.width / 2)
def ty(self, y):
return -1 * (y - (self.screen.height / 2))
def getGridPos(self, sliceX, sliceY, x, y):
lenX = self.screen.width / sliceX
lenY = self.screen.height / sliceY
return {"x": (x * lenX) - (lenX / 2), "y": (y * lenY) - (lenY / 2)}
def translateCoordinates(self, network):
# Kalkulacja koordynatow kazdego obiektu na podstawie screena (jego wielkosci) - ustawianie x i y neuronow a pozniej polaczen
# Loop po wszystkich neuronach i ustawienie ich lokacji
layerCount = len(network.layers)
for layerIndex, layer in enumerate(network.layers):
for index, neuron in enumerate(layer.neurons):
layerNeuronCount = len(layer.neurons)
gridPos = self.getGridPos(layerCount, layerNeuronCount, layerIndex + 1, index + 1)
#print("layer: " + str(layerIndex) + " neuron: " + str(index) + " gridpos: " + str(gridPos))
neuron.x = self.tx(gridPos["x"])
neuron.y = self.ty(gridPos["y"])
layerIndex += 1
# Loop po wszystkich polaczeniach i ustawienie ich coordynatow wzgledem ich input,output
for connection in network.getAllConnections():
connection.x1 = connection.input.x
connection.y1 = connection.input.y + connection.input.radius
connection.x2 = connection.output.x
connection.y2 = connection.output.y + connection.output.radius
return
class Trainer():
def __init__(self):
pass
def train(self, network, inputs, desiredOutputs, learningRate = 0.5):
# Set inputs
for key, neuron in enumerate(network.getNeuronsFromLayer("input")):
neuron.value = inputs[key]
# Get network outputs
outputs = []
for key, neuron in enumerate(network.getNeuronsFromLayer("output")):
outputs.append(neuron.calculateOutput())
# Calculate neuron errors
for key, neuron in enumerate(network.getNeuronsFromLayer("input")):
neuron.calculateError(desiredOutputs[0])
# Update weight for all connection
for connection in network.getAllConnections():
connection.updateWeight(learningRate)
# Update bias weight for all neurons
for neuron in network.getAllNeurons():
neuron.updateWeight(learningRate)
def run(self, network, inputs, desiredOutputs = []):
# Set inputs
for key, neuron in enumerate(network.getNeuronsFromLayer("input")):
neuron.value = inputs[key]
# Get network outputs
outputs = []
for key, neuron in enumerate(network.getNeuronsFromLayer("output")):
outputs.append(neuron.calculateOutput())
print(str(inputs) + " : " + str(outputs))
networkBuilder = NetworkBuilder()
network = networkBuilder.buildSimple(2,10,1)
screen = Screen(turtle, [])
trainer = Trainer()
i = 0
# Animacja lub wyswietlanie krokowe, moze byc nieskonczona
while 1 == 1:
i += 1
# Tutaj wszystkie zmiany w danym kroku. Np jakas ingerencja w strukture w czasie. Mozna dodawac obiekty do sieci i zmieniac ja.
x = random.random()
y = random.random()
trainer.train(network, [x, y], [x + y], 0.1)
if (i % 1000) == 0:
print("Iteration: " + str(i))
trainer.run(network, [0, 0])
if (i % 100000) == 0:
for x in range(1, 3):
in1 = float(input("Enter input 1: "))
in2 = float(input("Enter input 2: "))
trainer.run(network, [in1, in2])
# Pobieranie obiektow z sieci
objects = []
objects.extend(network.getAllNeurons())
objects.extend(network.getAllConnections())
# Tworzysz screen poprzez podanie mu wszystkich elementow ktore dziedzicza DrawableObject
screen.drawableObjects = objects
# Translacja koordynatow
#UIHelper(screen).translateCoordinates(network)
# Nastepny krok animacji, delay w sekundach
#screen.step(0)
turtle.done()