Autograd 방식을 사용한 파라미터 업데이트
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
|
import torch
if torch.cuda.is_available():
DEVICE = torch.device('cuda')
else:
DEVICE = torch.device('cpu')
BATCH_SIZE = 32
INPUT_SIZE = 500
HIDDEN_SIZE = 50
OUTPUT_SIZE = 5
learning_rate = 1e-5
input_x = torch.randn(BATCH_SIZE, INPUT_SIZE, device=DEVICE, dtype=torch.float, requires_grad=False)
w1 = torch.randn(INPUT_SIZE, HIDDEN_SIZE, device=DEVICE, dtype=torch.float, requires_grad=True)
w2 = torch.randn(HIDDEN_SIZE, OUTPUT_SIZE, device=DEVICE, dtype=torch.float, requires_grad=True)
output_y = torch.randn(BATCH_SIZE, OUTPUT_SIZE, device=DEVICE, dtype=torch.float, requires_grad=False)
for iteration in range(0, 500):
y_pred = input_x.mm(w1).clamp(min=0).mm(w2)
loss = (y_pred - output_y).pow(2).sum()
if iteration%100 == 0:
print("iter: ", iteration, ", Loss: ", loss.item())
loss.backward()
with torch.no_grad():
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad
w1.grad.zero_()
w2.grad.zero_()
|
cs |
위 소스코드를 실행시키면, 아래 출력값을 확인할 수 있다.
반응형
'머신러닝_딥러닝 > Pytorch' 카테고리의 다른 글
MLP모델 (CIFAR-10 dataset) (0) | 2021.10.17 |
---|---|
오토인코더(AutoEncoder) 구현 기초예제 (0) | 2021.10.17 |
오토인코더 (AutoEncoder) (0) | 2021.10.17 |
MLP모델 설계 및 학습 2탄 (MNIST dataset) (0) | 2021.10.16 |
MLP모델 설계 및 학습 1탄 (MNIST dataset) (0) | 2021.10.16 |