forked from PyTorchKR/tutorials-kr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomial_module.py
More file actions
executable file
Β·66 lines (53 loc) Β· 2.59 KB
/
Copy pathpolynomial_module.py
File metadata and controls
executable file
Β·66 lines (53 loc) Β· 2.59 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
# -*- coding: utf-8 -*-
"""
PyTorch: μ¬μ©μ μ μ nn.Module
------------------------------------
:math:`y=\sin(x)` μ μμΈ‘ν μ μλλ‘, :math:`-\pi` λΆν° :math:`\pi` κΉμ§
μ ν΄λ¦¬λ 거리(Euclidean distance)λ₯Ό μ΅μννλλ‘ 3μ°¨ λ€νμμ νμ΅ν©λλ€.
μ΄λ²μλ μ¬μ©μκ° μλ‘κ² μ μν Moduleμ νμ ν΄λμ€(subclass)λ‘ λͺ¨λΈμ μ μν©λλ€.
κΈ°μ‘΄ Moduleλ€μ μ¬μ©νλ κ°λ¨ν ꡬμ±λ³΄λ€ λ 볡μ‘ν λͺ¨λΈμ μνλ€λ©΄, μ΄ λ°©λ²μΌλ‘ λͺ¨λΈμ μ μνλ©΄ λ©λλ€.
"""
import torch
import math
class Polynomial3(torch.nn.Module):
def __init__(self):
"""
μμ±μμμ 4κ°μ λ§€κ°λ³μλ₯Ό μμ±(instantiate)νκ³ , λ©€λ² λ³μλ‘ μ§μ ν©λλ€.
"""
super().__init__()
self.a = torch.nn.Parameter(torch.randn(()))
self.b = torch.nn.Parameter(torch.randn(()))
self.c = torch.nn.Parameter(torch.randn(()))
self.d = torch.nn.Parameter(torch.randn(()))
def forward(self, x):
"""
μμ ν ν¨μμμλ μ
λ ₯ λ°μ΄ν°μ ν
μλ₯Ό λ°κ³ μΆλ ₯ λ°μ΄ν°μ ν
μλ₯Ό λ°νν΄μΌ ν©λλ€.
ν
μλ€ κ°μ μμμ μ°μ°λΏλ§ μλλΌ, μμ±μμμ μ μν Moduleμ μ¬μ©ν μ μμ΅λλ€.
"""
return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3
def string(self):
"""
Pythonμ λ€λ₯Έ ν΄λμ€(class)μ²λΌ, PyTorch λͺ¨λμ μ¬μ©ν΄μ μ¬μ©μ μ μ λ©μλλ₯Ό μ μν μ μμ΅λλ€.
"""
return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'
# μ
λ ₯κ°κ³Ό μΆλ ₯κ°μ κ°λ ν
μλ€μ μμ±ν©λλ€.
x = torch.linspace(-math.pi, math.pi, 2000)
y = torch.sin(x)
# μμμ μ μν ν΄λμ€λ‘ λͺ¨λΈμ μμ±ν©λλ€.
model = Polynomial3()
# μμ€ ν¨μμ optimizerλ₯Ό μμ±ν©λλ€. SGD μμ±μμ model.paramaters()λ₯Ό νΈμΆν΄μ£Όλ©΄
# λͺ¨λΈμ λ©€λ² νμ΅ κ°λ₯ν (torch.nn.Parameterλ‘ μ μλ) λ§€κ°λ³μλ€μ΄ ν¬ν¨λ©λλ€.
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-6)
for t in range(2000):
# μμ ν λ¨κ³: λͺ¨λΈμ xλ₯Ό μ λ¬νμ¬ μμΈ‘κ° yλ₯Ό κ³μ°ν©λλ€.
y_pred = model(x)
# μμ€μ κ³μ°νκ³ μΆλ ₯ν©λλ€.
loss = criterion(y_pred, y)
if t % 100 == 99:
print(t, loss.item())
# λ³νλλ₯Ό 0μΌλ‘ λ§λ€κ³ , μμ ν λ¨κ³λ₯Ό μννκ³ , κ°μ€μΉλ₯Ό κ°±μ ν©λλ€.
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f'Result: {model.string()}')