-
Notifications
You must be signed in to change notification settings - Fork 186
/
Copy pathautogradient.py
executable file
·145 lines (99 loc) · 2.35 KB
/
autogradient.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
#!/usr/bin/env python
import math
import numpy as np
class Op(object):
def __init__(self):
pass
def forward(self):
pass
def grad(self):
pass
class ConstantOp(Op):
def __init__(self, x):
self.x = x
def forward(self):
return self.x
def grad(self):
return 0
class CoefficientOp(Op):
def __init__(self, x):
self.x = x
def forward(self):
return self.x
def grad(self):
return self.x
class VariableOp(Op):
def __init__(self, x):
self.x = x
def forward(self):
return self.x
def grad(self):
return 1
def test_VariableOp():
x = 10
variable = VariableOp(x)
print("X: {}, forward: {}, grad: {}".format(
x, variable.forward(), variable.grad()))
class SquareOp(Op):
def __init__(self, x):
self.x = x
def forward(self):
return pow(self.x, 2)
def grad(self):
return 2 * self.x
def test_SquareOp():
x = 10
variable = SquareOp(x)
print("X: {}, forward: {}, grad: {}".format(
x, variable.forward(), variable.grad()))
class CubicOp(Op):
def __init__(self, x):
self.x = x
def forward(self):
return math.pow(self.x, 3)
def grad(self):
return 3 * math.pow(self.x, 2)
def test_CubicOp():
x = 10
variable = CubicOp(x)
print("X: {}, forward: {}, grad: {}".format(
x, variable.forward(), variable.grad()))
class AddOp(Op):
def __init__(self, *ops):
self.ops = ops
def forward(self):
result = 0
for op in self.ops:
result += op.forward()
return result
def grad(self):
result = 0
for op in self.ops:
result += op.grad()
return result
class MultipleOp(Op):
def __init__(self, *ops):
self.ops = ops
def forward(self):
result = 1
for op in self.ops:
result *= op.forward()
return result
def grad(self):
result = 1
for op in self.ops:
result *= op.grad()
return result
def main():
x = 1
# y = 3 * x**3 + 2 * x**2 + x + 10
# y' = 9 * x**2 + 4 * x + 1
first_item = MultipleOp(CoefficientOp(3), CubicOp(x))
second_item = MultipleOp(CoefficientOp(2), SquareOp(x))
third_item = VariableOp(x)
forth_item = ConstantOp(10)
y = AddOp(AddOp(first_item, second_item), third_item, forth_item)
# Should be "X: 1, forward: 16.0, grad: 14.0"
print("X: {}, forward: {}, grad: {}".format(x, y.forward(), y.grad()))
if __name__ == "__main__":
main()