aboutsummaryrefslogtreecommitdiff
path: root/src/scalar.py
blob: c8c760124ac1cbd75c831afc6ce4758212f513ef (plain)
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
import math

class Scalar:
    def __init__(self, data, _children=(), _op='', label='') -> None:
        self.label = label

        self.data = float(data)
        self.grad = 0.0

        self._prev = set(_children)
        self._op = _op
        
        self._backward = lambda: None
    
    def __repr__(self) -> str:
        return f'Scalar({self.label}: {self.data})'

    def __add__(self, y):
        result = Scalar(self.data + y.data, (self, y), _op='+')

        def _backward():
            self.grad = result.grad
            y.grad = result.grad

        self._backward = _backward

        return result

    def __mul__(self, y):
        result = Scalar(self.data * y.data, (self, y), _op='*')

        def _backward():
            self.grad = y.data * result.grad
            y.grad = self.data * result.grad

        self._backward = _backward

        return result

    def tanh(self):
        x = self.data
        t = (math.exp(2 * x) - 1) / (math.exp(2 * x) + 1)
        result = Scalar(t, (self, ), 'tanh')

        def _backward():
            self.grad = (1 - (t ** 2)) * result.grad

        self._backward = _backward

        return result

    def build_children(self):
        result = []

        result.append(self)
        for child in self._prev:
            result += child.build_children()

        return result

    def backward(self):
        self.grad = 1.0
        children = self.build_children()

        for child in children:
            child._backward()