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(0500):
    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

 

위 소스코드를 실행시키면, 아래 출력값을 확인할 수 있다.

파라미터 업데이트

 

반응형

+ Recent posts