[PyTorch] Lab02 - Linear regression

11695 단어 PyTorchPyTorch

📌 학습 목표


  • 데이터 정의
  • Hypothesis 정의
  • Loss
  • Gradient Descent

데이터 정의

예시 데이터로 공부한 시간(x)에 대한 점수(y)를 사용한다.

이를 torch.tensor로 아래와 같이 표현한다.

# Data
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[2], [4], [6]])

Hypothesis 정의

Linear regression은 학습 데이터에 가장 맞는 직선을 찾는 것이다.

그 직선을 Hypothesis라고 하고 수식으로는 다음과 같이 표현한다.

y=Wx+by = Wx + b

여기서 W를 weight, b를 bias라고 한다.

이제 weight와 bias를 0으로 초기화하여 생성한다.

여기서 requires_grad=True 는 학습한다는 것을 의미한다.

# Hypothesis
W = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
hypothesis = x_train * W + b

Loss

모델이 정답과 얼마나 가까운지 알기 위해 Loss(cost)를 계산한다.

Linear regression에서는 Mean Squared Error(MSE)를 사용한다.

MSE는 다음과 같다.

cost(W,b)=1mi=1m(H(x(i))y(i))2cost(W,b) = \frac{1}{m}\sum_{i=1}^{m}(H(x^{(i)})-y^{(i)})^2

H(x)는 예측한 점수(predict), y는 실제 점수(true)다.

이를 torch에서 표현하면 다음과 같다.

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

Gradient Descent

다음으로 학습을 위해 SGD(stocastic GD)를 사용한다.

  • torch.optim 라이브러리를 이용한다.

    • 학습할 tensor를 입력(W, b)
    • lr(learning rate) 을 지정
  • optimizer를 통해 학습

    • zero_grad()는 gradient 초기화
    • backward() 는 gradient 계산
    • step() 은 갱신
# Cost
optimizer = torch.optim.SGD([W, b], lr=0.01)

optimizer.zero_grad()
cost.backward()
optimizer.step()

좋은 웹페이지 즐겨찾기