-
Notifications
You must be signed in to change notification settings - Fork 33
/
back_propagation_simple.py
57 lines (37 loc) · 1.31 KB
/
back_propagation_simple.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
def identity(i):
def function(x):
return x
def gradient(_):
return [1]
return function, gradient, [i]
def multiply(i, j):
def function(x, y):
return x * y
def gradient(x, y):
return y, x
return function, gradient, [i, j]
def add(i, j):
def function(x, y):
return x + y
def gradient(x, y):
return 1, 1
return function, gradient, [i, j]
def back_propagation_simple(inputs, functions):
# An unit is tuple of unit value, local gradient and indices of children.
units = [[input, [], []] for input in inputs]
for function, gradient, parents in functions:
arguments = []
for parent in parents:
arguments.append(units[parent][0])
units[parent][2].append(len(units))
units.append([function(*arguments), [], []])
for parent, local_gradient in zip(parents, gradient(*arguments)):
units[parent][1].append(local_gradient)
gradients = [0 for _ in range(len(units))]
gradients[len(units)-1] = 1
for j in range(len(units) - 1, 0, -1):
value, local_gradient, children = units[j-1]
for index in range(len(children)):
child = children[index]
gradients[j-1] += gradients[child] * local_gradient[index]
return gradients