-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep03.py
74 lines (60 loc) · 1.72 KB
/
step03.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
import numpy as np
class Variable:
def __init__(self, data):
self.data = data
self.grad = None # grad: 미분 값
self.creator = None
def set_creator(self, func):
self.creator = func
def backward(self):
f = self.creator # 1. 함수를 가져옴
if f is not None:
x = f.input # 2. 함수의 입력을 가져옴
x.grad = f.backward(self.grad) # 3. 함수의 backward 메서드를 호출
x.backward() # 하나 앞 변수의 backward 메서드를 호출(재귀)
class Function:
def __call__(self, input):
x = input.data
y = self.forward(x) # 구체적인 계산은 forward 메서드에서 함
output = Variable(y)
output.set_creator(self) # 출력 변수에 창조자를 설정
self.input = input # 입력 변수를 기억
self.output = output # 출력도 저장
return output
def forward(self, x):
raise NotImplementedError()
def backward(self, gy):
raise NotImplementedError()
# x^2
class Square(Function):
def forward(self, x):
return x ** 2
def backward(self, gy):
x = self.input.data
gx = 2 * x * gy
return gx
# e^x
class Exp(Function):
def forward(self, x):
return np.exp(x)
def backward(self, gy):
x = self.input.data
gx = np.exp(x) * gy
return gx
# 수치미분
def numerical_diff(f, x, eps=1e-4):
x0 = Variable(x.data - eps)
x1 = Variable(x.data + eps)
y0 = f(x0)
y1 = f(x1)
return (y1.data - y0.data) / (2 * eps)
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)
y.backward()
print(x.grad)