Build Deep Learning Framework:Step6 Manual Backpropagation

Post at — Feb 21, 2025
#Deep_Learning_Framework

How to Build Deep Learning Framework Step By Step Using 60 steps:Step6

The Chain Rule is the core rule for differentiating composite functions in calculus, described as: if the function $$ y=f(g(x)) $$ then the derivative of x is: $$ \frac{dy}{dx} = \frac{dy}{dg}*\frac{dg}{dx} $$

The code:

 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
import numpy as np


class Variable:
    def __init__(self, data):
        self.data = data
        self.grad = None

class Function:
    def __call__(self, input):
        x = input.data
        y = self.forward(x)
        output = Variable(y)
        self.input = input
        return output

    def forward(self, x):
        raise NotImplementedError()

    def backward(self, gy):
        raise NotImplementedError()

class Square(Function):
    def forward(self, x):
        y = x ** 2
        return y

    def backward(self, gy):
        x = self.input.data
        gx = 2 * x * gy
        return gx

class Exp(Function):
    def forward(self, x):
        y = np.exp(x)
        return y

    def backward(self, gy):
        x = self.input.data
        gx = np.exp(x) * gy
        return gx

A = Square()
B = Exp()
C = Square()

x = Variable(np.array(0.5))
a = A(x)
b = B(a)
y = C(b)

y.grad = np.array(1.0)
b.grad = C.backward(y.grad)
a.grad = B.backward(b.grad)
x.grad = A.backward(a.grad)
print(x.grad)

the function is $$ y = \left(e^{x^{2}}\right)^{2} = e^{2x^{2}} $$

set $$ u = 2*x^2 $$

then $$ y = e^u $$

so $$ \frac{dy}{du} = e^{u} $$

$$ \frac{du}{dx} = 4x $$

$$ \frac{dy}{dx} = e^{2x^{2}} \cdot 4x $$

final answer is $$ \frac{dy}{dx} =\boxed{4x \cdot e^{2x^{2}}} $$

when x is 0.5 $$ \frac{dy}{dx} = \boxed{4*0.5 \cdot e^{2*(0.5)^{2}}} $$

same with the code result

1
2
(deep-learning-from-scratch-3) D:\project\deep-learning-from-scratch-3>python steps\step06.py 
3.297442541400256