-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeuralNet.py
109 lines (91 loc) · 2.99 KB
/
NeuralNet.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
import math
import random
from typing import List
class Neuron:
inputs: int
weights: List[float]
b: float
@staticmethod
def sigmoid(val: float) -> float:
if val > 100:
return 1
if val < -100:
return 0
return 1 / (1 + math.exp(-val))
def __init__(self, inputs: int):
self.inputs = inputs
self.weights = []
while len(self.weights) < self.inputs:
self.weights.append(random.random() * 20 - 10)
self.b = random.random() * 20 - 10
def push(self, input_data: List[float]) -> float:
return Neuron.sigmoid(
sum(
map(
lambda it: self.weights[it] * input_data[it],
range(self.inputs)
)
) + self.b
)
@staticmethod
def from_array(inputs: int, arr: List[float]):
neuron = Neuron(inputs)
neuron.weights = arr[:-1]
neuron.b = arr[-1]
return neuron
class NeuralNet:
inputs: int
outputs: int
hidden: List[int]
layers: List[List[Neuron]]
def __init__(self, inputs: int, outputs: int, hidden: List[int]):
self.inputs = inputs
self.outputs = outputs
self.hidden = hidden
self.layers = []
current_inputs = self.inputs
for hid in self.hidden:
new_layer = []
while len(new_layer) < hid:
new_layer.append(Neuron(current_inputs))
self.layers.append(new_layer)
current_inputs = hid
output_layer = []
while len(output_layer) < self.outputs:
output_layer.append(Neuron(current_inputs))
self.layers.append(output_layer)
def push(self, input_data: List[float]) -> List[float]:
current_data = input_data[:]
for layer in self.layers:
current_data = list(
map(
lambda neuron: neuron.push(current_data),
layer
)
)
return current_data
def json(self) -> dict:
weights = []
for layer in self.layers:
for neuron in layer:
for w in neuron.weights:
weights.append(w)
weights.append(neuron.b)
return {
'inputs': self.inputs,
'outputs': self.outputs,
'hidden': self.hidden,
'weights': weights
}
@staticmethod
def from_json(data: json):
neural_net = NeuralNet(data['inputs'], data['outputs'], data['hidden'])
from_it = 0
current_inputs = data['inputs']
for layer in neural_net.layers:
for i in range(len(layer)):
to_it = from_it + layer[i].inputs + 1
layer[i] = Neuron.from_array(current_inputs, data['weights'][from_it:to_it])
from_it = to_it
current_inputs = len(layer)
return neural_net