now is better than never

[인공지능(AI) 기초 다지기] 5. 딥러닝 핵심 기초 (4) 본문

Python/[코칭스터디 9기] 인공지능 AI 기초 다지기

[인공지능(AI) 기초 다지기] 5. 딥러닝 핵심 기초 (4)

김초송 2023. 3. 7. 17:29

3) Gradient Descent

 

- Hypothesis Function (가설 함수)

  • input x 에 대해 어떤 output y 를 예측할지 알려주며, H(x)로 표현
  • 변수 W와 b 를 학습해서 주어진 데이터를 최적화하는 것

 

- Cost Function : Intuition

  • 모델의 예측값이 실제 데이터와 얼마나 다른지를 나타내는 값
  • 잘 학습 될 수록 낮은 cost
  • Linear Regression에서 쓰이는 cost function은 MSE

 

- MSE (Mean Squared Error)

  • (예측값 - 실제값)^2 의 평균

 

- Gradient Descent : Intuition

  • ∂cost / ∂W = ∇W
    ∇ : 그래디언트, 다차원 공간에서 편미분(∂)한 것들을 모아 놓은 것
  • 기울기가 양수일 때는 W를 줄이고, 음수일 때는 W를 늘림
  • 기울기가 가파를 때는 W를 크게 움직이고, 완만(cost가 0에 가까움)할 때는 작게 움직임
  • = gradient를 이용해서 cost를 줄인다

gradient = 2 * torch.sum((W * x_train - y_train) * x_train)
lr = 0.1
W -= lr * gradient

 

- Full Code

x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

W = torch.zeros(1)
lr = 0.1

nb_epochs = 10
for epoch in range(1, nb_epochs+1):
    hypothesis = x_train * W
    
    cost = torch.mean((hypothesis - y_train) ** 2)
    gradient = torch.sum((W * x_train - y_train) * x_train)
    
    print('Epoch {:4d}/{} W: {:.3f}, Cost: {:.6f}'.format(
        epoch, nb_epochs, W.item(), cost.item()
    ))
    
    W -= lr * gradient

 

- Gradient Descent with torch.optim

  • 시작할 때 optimizer로 정의
  • optimizer.zero_grad() : optimizer 의 저장된 모든 학습 가능한 변수의 gradient 0 초기화
  • cost.backward() : 각 변수들의 gradient 계산
  • optimizer.step() : 저장된 gradient로 gradient descent 실행
optimizer = torch.optim.SGD([W], lr=0.15)

# cost 로 H(x) 개선
optimizer.zero_grad()
cost.backward()
optimizer.step()
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

W = torch.zeros(1, requires_grad=True)

optimizer = torch.optim.SGD([W], lr=0.15)

nb_epochs = 10
for epoch in range(1, nb_epochs+1):
    hypothesis = x_train * W
    
    cost = torch.mean((hypothesis - y_train) ** 2)
    
    print('Epoch {:4d}/{} W: {:.3f}, Cost: {:.6f}'.format(
        epoch, nb_epochs, W.item(), cost.item()
    ))
    
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()