-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
129 lines (96 loc) · 3.01 KB
/
engine.py
File metadata and controls
129 lines (96 loc) · 3.01 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
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
import numpy as np
class Value:
def __init__(self,data,children =(),op='',label =''):
self.data = data
self.prev = set(children)
self.op = op
self.label = label
self.grad = 0
self.backward_ = lambda:None
def __add__(self, other):
if not isinstance(other,Value):
other = Value(other)
out = Value(self.data + other.data,(self,other),'+')
def backward_():
self.grad += out.grad * 1
other.grad += out.grad * 1
out.backward_ = backward_
return out
def __sub__(self, other):
if not isinstance(other,Value):
other = Value(other)
out = Value(self.data - other.data,(self,other),'-')
def backward_():
self.grad += out.grad * 1
other.grad += out.grad * -1
out.backward_ = backward_
return out
def __mul__(self, other):
if not isinstance(other,Value):
other = Value(other)
out = Value(self.data * other.data,(self,other),'*')
def backward_():
self.grad += out.grad * other.data
other.grad += out.grad * self.data
out.backward_ = backward_
return out
def __truediv__(self, other):
if not isinstance(other, Value):
other = Value(other)
out = Value(self.data / other.data, (self, other), '/')
def backward_():
self.grad += out.grad * (1 / other.data)
other.grad += out.grad * (-self.data / (other.data ** 2))
out.backward_ = backward_
return out
def relu(self):
x = self.data
re = self.data if self.data > 0 else 0
out = Value(re,(self,),'relu')
def backward_():
relu_derv = 1 if x > 0 else 0
self.grad += out.grad * relu_derv
out.backward_ = backward_
return out
def backward(self):
topo = []
visited = set()
def build(v):
if v not in visited:
visited.add(v)
for child in v.prev:
build(child)
topo.append(v)
build(self)
self.grad = 1
for node in reversed(topo):
node.backward_()
def __radd__(self, other):
return self + other
def __rsub__(self, other):
if not isinstance(other, Value):
other = Value(other)
return other - self
def __rmul__(self, other):
return self * other
def __neg__(self):
return self * -1
def __repr__(self):
return f'Value(data = {self.data}, grad = {self.grad})'
def __rtruediv__(self, other):
if not isinstance(other, Value):
other = Value(other)
return other / self
if __name__ =='__main__':
a = Value(5)
c = -a
c.grad = 1
c.backward()
print(a)
'''a = Value(3) ; a.label = 'a'
b = Value(4) ; a.label = 'a'
c = a * b; c.label = 'c'
x = c.relu(); x.label = 'relu'
x.backward()
print(a.grad)
print(b.grad)'''