-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_neural_network.py
58 lines (48 loc) · 1.78 KB
/
dynamic_neural_network.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
class DynamicNeuralNetwork:
def __init__(self):
self.layers = []
self.loss = None
self.loss_prime = None
# add layer to network
def add(self, layer):
self.layers.append(layer)
# set loss to use
def use(self, loss, loss_prime):
self.loss = loss
self.loss_prime = loss_prime
# predict output for given input
def predict(self, input_data):
# sample dimension first
samples = len(input_data)
result = []
# run network over all samples
for i in range(samples):
# forward propagation
output = input_data[i]
for layer in self.layers:
output = layer.forward_propagation(output)
result.append(output)
return result
# train the network
def fit(self, x_train, y_train, epochs, learning_rate=0.1):
# sample dimension first
samples = len(x_train)
training_errors = []
# training loop
for i in range(epochs):
err = 0
for j in range(samples):
# forward propagation
output = x_train[j]
for layer in self.layers:
output = layer.forward_propagation(output)
# compute loss (for display purpose only)
err += self.loss(y_train[j], output)
# backward propagation
error = self.loss_prime(y_train[j], output)
for layer in reversed(self.layers):
error = layer.backward_propagation(error, learning_rate)
# calculate average error on all samples
err /= samples
training_errors += [err]
return training_errors