-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathoptimization_tutorial.py
More file actions
213 lines (175 loc) Β· 10.7 KB
/
optimization_tutorial.py
File metadata and controls
213 lines (175 loc) Β· 10.7 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
`νμ΄ν μΉ(PyTorch) κΈ°λ³Έ μ΅νκΈ° <intro.html>`_ ||
`λΉ λ₯Έ μμ <quickstart_tutorial.html>`_ ||
`ν
μ(Tensor) <tensorqs_tutorial.html>`_ ||
`Datasetκ³Ό Dataloader <data_tutorial.html>`_ ||
`λ³ν(Transform) <transforms_tutorial.html>`_ ||
`μ κ²½λ§ λͺ¨λΈ ꡬμ±νκΈ° <buildmodel_tutorial.html>`_ ||
`Autograd <autogradqs_tutorial.html>`_ ||
**μ΅μ ν(Optimization)** ||
`λͺ¨λΈ μ μ₯νκ³ λΆλ¬μ€κΈ° <saveloadrun_tutorial.html>`_
λͺ¨λΈ λ§€κ°λ³μ μ΅μ ννκΈ°
==========================================================================
μ΄μ λͺ¨λΈκ³Ό λ°μ΄ν°κ° μ€λΉλμμΌλ, λ°μ΄ν°μ λ§€κ°λ³μλ₯Ό μ΅μ ννμ¬ λͺ¨λΈμ νμ΅νκ³ , κ²μ¦νκ³ , ν
μ€νΈν μ°¨λ‘μ
λλ€.
λͺ¨λΈμ νμ΅νλ κ³Όμ μ λ°λ³΅μ μΈ κ³Όμ μ κ±°μΉ©λλ€; κ° λ°λ³΅ λ¨κ³μμ λͺ¨λΈμ μΆλ ₯μ μΆμΈ‘νκ³ ,
μΆμΈ‘κ³Ό μ λ΅ μ¬μ΄μ μ€λ₯(\ *μμ€(loss)*\ )λ₯Ό κ³μ°νκ³ , (`μ΄μ μ₯ <autograd_tutorial.html>`_\ μμ λ³Έ κ²μ²λΌ)
λ§€κ°λ³μμ λν μ€λ₯μ λν¨μ(derivative)λ₯Ό μμ§ν λ€, κ²½μ¬νκ°λ²μ μ¬μ©νμ¬ μ΄ νλΌλ―Έν°λ€μ **μ΅μ ν(optimize)**\ ν©λλ€.
μ΄ κ³Όμ μ λν μμΈν μ€λͺ
μ `3Blue1Brownμ μμ ν <https://www.youtube.com/watch?v=tIeHLnjs5U8>`__ μμμ μ°Έκ³ νμΈμ.
κΈ°λ³Έ(Pre-requisite) μ½λ
------------------------------------------------------------------------------------------
μ΄μ μ₯μΈ `Datasetκ³Ό DataLoader <data_tutorial.html>`_\ μ `μ κ²½λ§ λͺ¨λΈ ꡬμ±νκΈ° <buildmodel_tutorial.html>`_\ μμ
μ½λλ₯Ό κ°μ Έμμ΅λλ€.
"""
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
train_dataloader = DataLoader(training_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork()
##############################################
# νμ΄νΌνλΌλ―Έν°(Hyperparameter)
# ------------------------------------------------------------------------------------------
#
# νμ΄νΌνλΌλ―Έν°(Hyperparameter)λ λͺ¨λΈ μ΅μ ν κ³Όμ μ μ μ΄ν μ μλ μ‘°μ κ°λ₯ν λ§€κ°λ³μμ
λλ€.
# μλ‘ λ€λ₯Έ νμ΄νΌνλΌλ―Έν° κ°μ λͺ¨λΈ νμ΅κ³Ό μλ ΄μ¨(convergence rate)μ μν₯μ λ―ΈμΉ μ μμ΅λλ€.
# (νμ΄νΌνλΌλ―Έν° νλ(tuning)μ λν΄ `λ μμ보기 <https://tutorials.pytorch.kr/beginner/hyperparameter_tuning_tutorial.html>`__)
#
# νμ΅ μμλ λ€μκ³Ό κ°μ νμ΄νΌνλΌλ―Έν°λ₯Ό μ μν©λλ€:
# - **μν(epoch) μ** - λ°μ΄ν°μ
μ λ°λ³΅νλ νμ
# - **λ°°μΉ ν¬κΈ°(batch size)** - λ§€κ°λ³μκ° κ°±μ λκΈ° μ μ κ²½λ§μ ν΅ν΄ μ νλ λ°μ΄ν° μνμ μ
# - **νμ΅λ₯ (learning rate)** - κ° λ°°μΉ/μνμμ λͺ¨λΈμ λ§€κ°λ³μλ₯Ό μ‘°μ νλ λΉμ¨. κ°μ΄ μμμλ‘ νμ΅ μλκ° λλ €μ§κ³ , κ°μ΄ ν¬λ©΄ νμ΅ μ€ μμΈ‘ν μ μλ λμμ΄ λ°μν μ μμ΅λλ€.
#
learning_rate = 1e-3
batch_size = 64
epochs = 5
#####################################
# μ΅μ ν λ¨κ³(Optimization Loop)
# ------------------------------------------------------------------------------------------
#
# νμ΄νΌνλΌλ―Έν°λ₯Ό μ€μ ν λ€μλ μ΅μ ν λ¨κ³λ₯Ό ν΅ν΄ λͺ¨λΈμ νμ΅νκ³ μ΅μ νν μ μμ΅λλ€.
# μ΅μ ν λ¨κ³μ κ° λ°λ³΅(iteration)μ **μν**\ μ΄λΌκ³ λΆλ¦
λλ€.
#
# νλμ μνμ λ€μ λ λΆλΆμΌλ‘ ꡬμ±λ©λλ€:
# - **νμ΅ λ¨κ³(train loop)** - νμ΅μ© λ°μ΄ν°μ
μ λ°λ³΅(iterate)νκ³ μ΅μ μ λ§€κ°λ³μλ‘ μλ ΄ν©λλ€.
# - **κ²μ¦/ν
μ€νΈ λ¨κ³(validation/test loop)** - λͺ¨λΈ μ±λ₯μ΄ κ°μ λκ³ μλμ§λ₯Ό νμΈνκΈ° μν΄ ν
μ€νΈ λ°μ΄ν°μ
μ λ°λ³΅(iterate)ν©λλ€.
#
# νμ΅ λ¨κ³(training loop)μμ μΌμ΄λλ λͺ κ°μ§ κ°λ
λ€μ κ°λ΅ν μ΄ν΄λ³΄κ² μ΅λλ€. μ΅μ ν λ¨κ³(optimization loop)λ₯Ό λ³΄λ €λ©΄
# :ref:`full-impl-label` λΆλΆμΌλ‘ 건λλ°μλ©΄ λ©λλ€.
#
# μμ€ ν¨μ(loss function)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# νμ΅μ© λ°μ΄ν°λ₯Ό μ 곡νλ©΄, νμ΅λμ§ μμ μ κ²½λ§μ μ λ΅μ μ 곡νμ§ μμ νλ₯ μ΄ λμ΅λλ€. **μμ€ ν¨μ(loss function)**\ λ
# νλν κ²°κ³Όμ μ€μ κ° μ¬μ΄μ νλ¦° μ λ(degree of dissimilarity)λ₯Ό μΈ‘μ νλ©°, νμ΅ μ€μ μ΄ κ°μ μ΅μννλ €κ³ ν©λλ€.
# μ£Όμ΄μ§ λ°μ΄ν° μνμ μ
λ ₯μΌλ‘ κ³μ°ν μμΈ‘κ³Ό μ λ΅(label)μ λΉκ΅νμ¬ μμ€(loss)μ κ³μ°ν©λλ€.
#
# μΌλ°μ μΈ μμ€ν¨μμλ νκ· λ¬Έμ (regression task)μ μ¬μ©νλ `nn.MSELoss <https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html#torch.nn.MSELoss>`_\ (νκ· μ κ³± μ€μ°¨(MSE; Mean Square Error))λ
# λΆλ₯(classification)μ μ¬μ©νλ `nn.NLLLoss <https://pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss>`_ (μμ λ‘κ·Έ μ°λ(Negative Log Likelihood)),
# κ·Έλ¦¬κ³ ``nn.LogSoftmax``\ μ ``nn.NLLLoss``\ λ₯Ό ν©μΉ `nn.CrossEntropyLoss <https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss>`_
# λ±μ΄ μμ΅λλ€.
#
# λͺ¨λΈμ μΆλ ₯ λ‘μ§(logit)μ ``nn.CrossEntropyLoss``\ μ μ λ¬νμ¬ λ‘μ§(logit)μ μ κ·ννκ³ μμΈ‘ μ€λ₯λ₯Ό κ³μ°ν©λλ€.
# μμ€ ν¨μλ₯Ό μ΄κΈ°νν©λλ€.
loss_fn = nn.CrossEntropyLoss()
#####################################
# μ΅ν°λ§μ΄μ (Optimizer)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# μ΅μ νλ κ° νμ΅ λ¨κ³μμ λͺ¨λΈμ μ€λ₯λ₯Ό μ€μ΄κΈ° μν΄ λͺ¨λΈ λ§€κ°λ³μλ₯Ό μ‘°μ νλ κ³Όμ μ
λλ€. **μ΅μ ν μκ³ λ¦¬μ¦**\ μ μ΄ κ³Όμ μ΄ μνλλ λ°©μ(μ¬κΈ°μμλ νλ₯ μ κ²½μ¬νκ°λ²(SGD; Stochastic Gradient Descent))μ μ μν©λλ€.
# λͺ¨λ μ΅μ ν μ μ°¨(logic)λ ``optimizer`` κ°μ²΄μ μΊ‘μν(encapsulate)λ©λλ€. μ¬κΈ°μλ SGD μ΅ν°λ§μ΄μ λ₯Ό μ¬μ©νκ³ μμΌλ©°, PyTorchμλ ADAMμ΄λ RMSPropκ³Ό κ°μ λ€λ₯Έ μ’
λ₯μ λͺ¨λΈκ³Ό λ°μ΄ν°μμ λ μ λμνλ
# `λ€μν μ΅ν°λ§μ΄μ <https://pytorch.org/docs/stable/optim.html>`_\ κ° μμ΅λλ€.
#
# νμ΅νλ €λ λͺ¨λΈμ λ§€κ°λ³μμ νμ΅λ₯ (learning rate) νμ΄νΌνλΌλ―Έν°λ₯Ό λ±λ‘νμ¬ μ΅ν°λ§μ΄μ λ₯Ό μ΄κΈ°νν©λλ€.
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
#####################################
# νμ΅ λ¨κ³(loop)μμ μ΅μ νλ μΈλ¨κ³λ‘ μ΄λ€μ§λλ€:
# * ``optimizer.zero_grad()``\ λ₯Ό νΈμΆνμ¬ λͺ¨λΈ λ§€κ°λ³μμ λ³νλλ₯Ό μ¬μ€μ ν©λλ€. κΈ°λ³Έμ μΌλ‘ λ³νλλ λν΄μ§κΈ°(add up) λλ¬Έμ μ€λ³΅ κ³μ°μ λ§κΈ° μν΄ λ°λ³΅ν λλ§λ€ λͺ
μμ μΌλ‘ 0μΌλ‘ μ€μ ν©λλ€.
# * ``loss.backwards()``\ λ₯Ό νΈμΆνμ¬ μμΈ‘ μμ€(prediction loss)μ μμ νν©λλ€. PyTorchλ κ° λ§€κ°λ³μμ λν μμ€μ λ³νλλ₯Ό μ μ₯ν©λλ€.
# * λ³νλλ₯Ό κ³μ°ν λ€μλ ``optimizer.step()``\ μ νΈμΆνμ¬ μμ ν λ¨κ³μμ μμ§λ λ³νλλ‘ λ§€κ°λ³μλ₯Ό μ‘°μ ν©λλ€.
########################################
# .. _full-impl-label:
#
# μ 체 ꡬν
# ------------------------------------------------------------------------------------------
#
# μ΅μ ν μ½λλ₯Ό λ°λ³΅νμ¬ μννλ ``train_loop``\ μ ν
μ€νΈ λ°μ΄ν°λ‘ λͺ¨λΈμ μ±λ₯μ μΈ‘μ νλ ``test_loop``\ λ₯Ό μ μνμμ΅λλ€.
def train_loop(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
# λͺ¨λΈμ νμ΅(train) λͺ¨λλ‘ μ€μ ν©λλ€ - λ°°μΉ μ κ·ν(Batch Normalization) λ° λλ‘μμ(Dropout) κ³μΈ΅λ€μ μ€μν©λλ€.
# μ΄ μμμμλ μμ΄λ λμ§λ§, λͺ¨λ² μ¬λ‘λ₯Ό μν΄ μΆκ°ν΄λμμ΅λλ€.
model.train()
for batch, (X, y) in enumerate(dataloader):
# μμΈ‘(prediction)κ³Ό μμ€(loss) κ³μ°
pred = model(X)
loss = loss_fn(pred, y)
# μμ ν
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), batch * batch_size + len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_loop(dataloader, model, loss_fn):
# λͺ¨λΈμ νκ°(eval) λͺ¨λλ‘ μ€μ ν©λλ€ - λ°°μΉ μ κ·ν(Batch Normalization) λ° λλ‘μμ(Dropout) κ³μΈ΅λ€μ μ€μν©λλ€.
# μ΄ μμμμλ μμ΄λ λμ§λ§, λͺ¨λ² μ¬λ‘λ₯Ό μν΄ μΆκ°ν΄λμμ΅λλ€.
model.eval()
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, correct = 0, 0
# torch.no_grad()λ₯Ό μ¬μ©νμ¬ ν
μ€νΈ μ λ³νλ(gradient)λ₯Ό κ³μ°νμ§ μλλ‘ ν©λλ€.
# μ΄λ requires_grad=Trueλ‘ μ€μ λ ν
μλ€μ λΆνμν λ³νλ μ°μ° λ° λ©λͺ¨λ¦¬ μ¬μ©λ λν μ€μ¬μ€λλ€.
with torch.no_grad():
for X, y in dataloader:
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
########################################
# μμ€ ν¨μμ μ΅ν°λ§μ΄μ λ₯Ό μ΄κΈ°ννκ³ ``train_loop``\ μ ``test_loop``\ μ μ λ¬ν©λλ€.
# λͺ¨λΈμ μ±λ₯ ν₯μμ μμ보기 μν΄ μμ λ‘κ² μν(epoch) μλ₯Ό μ¦κ°μμΌ λ³Ό μ μμ΅λλ€.
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loop(train_dataloader, model, loss_fn, optimizer)
test_loop(test_dataloader, model, loss_fn)
print("Done!")
#################################################################
# λ μ½μ΄λ³΄κΈ°
# ------------------------------------------------------------------------------------------
# - `Loss Functions <https://pytorch.org/docs/stable/nn.html#loss-functions>`_
# - `torch.optim <https://pytorch.org/docs/stable/optim.html>`_
# - `Warmstart Training a Model <https://tutorials.pytorch.kr/recipes/recipes/warmstarting_model_using_parameters_from_a_different_model.html>`_
#