now is better than never

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

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

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

김초송 2023. 3. 7. 16:35

2) Linear Regression

 

- Data Definition

  • test dataset 
    입력 : x_train = hours (공부 시간)
    출력 : y_train = points (시험 점수)
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[2], [4], [6]])

 

- Hypothesis

  • y = Wx + b
    학습 데이터와 가장 잘 맞는 하나의 직선을 찾는 일
  • W : weight
  • b : bias
W = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
hypothesis = x_train * W + b
  • Weight와 bias를 0으로 초기화
    항상 출력 0을 예측
  • requires_grad = True 
    학습할 것이라고 명시

 

- Computer Loss

  • Mean Squared Error (MSE) : 얼마나 정답과 가까운지 계산
    예측값과 y_train의 값의 차이를 제곱해서 평균을 낸 것 

cost = torch.mean((hypothesis - y_train)**2)

 

- Gradient Descent

  • Loss 를 이용해서 모델 개선시키는 방법
optimizer = torch.optim.SGD([W, b], lr=0.01)

optimizer.zero_grad()
cost.backward()
optimizer.step()
  • torch.optim 라이브러리 사용
    [W, b] 는 학습할 tensor들
    lr=0.01 은 learning rate
  • SDG : Stochastic Gradient Descent
  • zero_grad() : gradient 초기화
    backward() : gradient 계산
    step() : 개선

 

- Training Process

  1. 데이터 정의
  2. Hypothesis 초기화
  3. Optimizer 정의

    --- 원하는 만큼 for 문 반복
    1. Hypothesis 예측
    2. Cost 계산
    3. Optimizer로 학습
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[2], [4], [6]])

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

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

nb_epochs = 1000

for epch in range(1, nb_epochs+1):
    hypothesis = x_train * W + b
    cost = torch.mean((hypothesis - y_train)**2)
    
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()