-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeuralNetwork.py
More file actions
73 lines (56 loc) · 1.84 KB
/
NeuralNetwork.py
File metadata and controls
73 lines (56 loc) · 1.84 KB
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
from Matrix import Matrix
import math
import random
def sigmoid(x):
return 1/(1+math.e**(-x))
def step(x):
if x < 0:
return 0
else:
return 1
def toRange(a, b, c, d, e):
return ((a - b) / (c - b)) * (e - d) + d
def mutate(chance=0.2):
def mutate_fn(x):
if random.random()<chance:
# return x + random.gauss(0, 1)
return x + random.uniform(-1, 1)
else:
return x
return mutate_fn
class NeuralNetwork:
__slots__ = ("nb_inputs", "nb_outputs", "poids_input_output",
"biais_output", "activation_fn")
def __init__(self, nb_inputs, nb_outputs):
self.nb_inputs = nb_inputs
self.nb_outputs = nb_outputs
self.poids_input_output = Matrix.random(nb_outputs, nb_inputs)
self.biais_output = Matrix.random(nb_outputs, 1)
self.activation_fn = step
@staticmethod
def fromDict(dict):
nn = NeuralNetwork(4, 1)
nn.poids_input_output = Matrix.from_array(dict["poids"])
nn.biais_output = Matrix.from_array(dict["biais"])
return nn
def predict(self, inputs):
"""
inputs: Matrix nb_input rows 1 col
"""
assert inputs.cols == 1 and inputs.rows == self.nb_inputs
somme_poids = self.poids_input_output * inputs
res = somme_poids + self.biais_output
res.mapImpl(lambda i, j, el: self.activation_fn(el))
return res
def mutate(self, fn):
self.poids_input_output.mapImpl(lambda i, j, el: fn(el))
self.biais_output.mapImpl(lambda i, j, el: fn(el))
def toDict(self):
return {
"biais": self.biais_output.toDict(),
"poids": self.poids_input_output.toDict()
}
if __name__ == "__main__":
nn = NeuralNetwork(4, 1)
print(nn.poids_input_output)
print(nn.biais_output)