-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathpolynomial_autograd.py
More file actions
executable file
ยท70 lines (58 loc) ยท 3.09 KB
/
polynomial_autograd.py
File metadata and controls
executable file
ยท70 lines (58 loc) ยท 3.09 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
# -*- coding: utf-8 -*-
"""
PyTorch: Tensor์ autograd
-----------------------------------
:math:`y=\sin(x)` ์ ์์ธกํ ์ ์๋๋ก, :math:`-\pi` ๋ถํฐ :math:`\pi` ๊น์ง
์ ํด๋ฆฌ๋ ๊ฑฐ๋ฆฌ(Euclidean distance)๋ฅผ ์ต์ํํ๋๋ก 3์ฐจ ๋คํญ์์ ํ์ตํฉ๋๋ค.
์ด ๊ตฌํ์ PyTorch Tensor ์ฐ์ฐ์ ์ฌ์ฉํ์ฌ ์์ ํ ๋จ๊ณ๋ฅผ ๊ณ์ฐํ๊ณ , PyTorch autograd๋ฅผ ์ฌ์ฉํ์ฌ
๋ณํ๋(gradient)๋ฅผ ๊ณ์ฐํฉ๋๋ค.
PyTorch Tensor๋ ์ฐ์ฐ ๊ทธ๋ํ์์ ๋
ธ๋(node)๋ก ํํ๋ฉ๋๋ค. ๋ง์ฝ ``x`` ๊ฐ ``x.requires_grad=True`` ์ธ
Tensor๋ผ๋ฉด, ``x.grad`` ๋ ์ด๋ค ์ค์นผ๋ผ ๊ฐ์ ๋ํ ``x`` ์ ๋ณํ๋๋ฅผ ๊ฐ๋ ๋๋ค๋ฅธ Tensor์
๋๋ค.
"""
import torch
import math
dtype = torch.float
device = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_default_device(device)
# ์
๋ ฅ๊ฐ๊ณผ ์ถ๋ ฅ๊ฐ์ ๊ฐ๋ Tensor๋ค์ ์์ฑํฉ๋๋ค.
# requires_grad=False๊ฐ ๊ธฐ๋ณธ๊ฐ์ผ๋ก ์ค์ ๋์ด ์ญ์ ํ ๋จ๊ณ ์ค์ ์ด Tensor๋ค์ ๋ํ ๋ณํ๋๋ฅผ
# ๊ณ์ฐํ ํ์๊ฐ ์์์ ๋ํ๋
๋๋ค.
x = torch.linspace(-math.pi, math.pi, 2000, dtype=dtype)
y = torch.sin(x)
# ๊ฐ์ค์น๋ฅผ ๊ฐ๋ ์์์ Tensor๋ฅผ ์์ฑํฉ๋๋ค. 3์ฐจ ๋คํญ์์ด๋ฏ๋ก 4๊ฐ์ ๊ฐ์ค์น๊ฐ ํ์ํฉ๋๋ค:
# y = a + b x + c x^2 + d x^3
# requires_grad=True๋ก ์ค์ ํ์ฌ ์ญ์ ํ ๋จ๊ณ ์ค์ ์ด Tensor๋ค์ ๋ํ ๋ณํ๋๋ฅผ ๊ณ์ฐํ ํ์๊ฐ
# ์์์ ๋ํ๋
๋๋ค.
a = torch.randn((), dtype=dtype, requires_grad=True)
b = torch.randn((), dtype=dtype, requires_grad=True)
c = torch.randn((), dtype=dtype, requires_grad=True)
d = torch.randn((), dtype=dtype, requires_grad=True)
learning_rate = 1e-6
for t in range(2000):
# ์์ ํ ๋จ๊ณ: Tensor๋ค ๊ฐ์ ์ฐ์ฐ์ ์ฌ์ฉํ์ฌ ์์ธก๊ฐ y๋ฅผ ๊ณ์ฐํฉ๋๋ค.
y_pred = a + b * x + c * x ** 2 + d * x ** 3
# Tensor๋ค๊ฐ์ ์ฐ์ฐ์ ์ฌ์ฉํ์ฌ ์์ค(loss)์ ๊ณ์ฐํ๊ณ ์ถ๋ ฅํฉ๋๋ค.
# ์ด ๋ ์์ค์ (1,) shape์ ๊ฐ๋ Tensor์
๋๋ค.
# loss.item() ์ผ๋ก ์์ค์ด ๊ฐ๊ณ ์๋ ์ค์นผ๋ผ ๊ฐ์ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.
loss = (y_pred - y).pow(2).sum()
if t % 100 == 99:
print(t, loss.item())
# autograd ๋ฅผ ์ฌ์ฉํ์ฌ ์ญ์ ํ ๋จ๊ณ๋ฅผ ๊ณ์ฐํฉ๋๋ค. ์ด๋ requires_grad=True๋ฅผ ๊ฐ๋
# ๋ชจ๋ Tensor๋ค์ ๋ํ ์์ค์ ๋ณํ๋๋ฅผ ๊ณ์ฐํฉ๋๋ค.
# ์ดํ a.grad์ b.grad, c.grad, d.grad๋ ๊ฐ๊ฐ a, b, c, d์ ๋ํ ์์ค์ ๋ณํ๋๋ฅผ
# ๊ฐ๋ Tensor๊ฐ ๋ฉ๋๋ค.
loss.backward()
# ๊ฒฝ์ฌํ๊ฐ๋ฒ(gradient descent)์ ์ฌ์ฉํ์ฌ ๊ฐ์ค์น๋ฅผ ์ง์ ๊ฐฑ์ ํฉ๋๋ค.
# torch.no_grad()๋ก ๊ฐ์ธ๋ ์ด์ ๋, ๊ฐ์ค์น๋ค์ด requires_grad=True ์ง๋ง
# autograd์์๋ ์ด๋ฅผ ์ถ์ ํ์ง ์์ ๊ฒ์ด๊ธฐ ๋๋ฌธ์
๋๋ค.
with torch.no_grad():
a -= learning_rate * a.grad
b -= learning_rate * b.grad
c -= learning_rate * c.grad
d -= learning_rate * d.grad
# ๊ฐ์ค์น ๊ฐฑ์ ํ์๋ ๋ณํ๋๋ฅผ ์ง์ 0์ผ๋ก ๋ง๋ญ๋๋ค.
a.grad = None
b.grad = None
c.grad = None
d.grad = None
print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')