[파이토치로 시작하는 딥러닝 기초]02_Linear Regression

2020. 12. 21. 16:52·AI Study/DL_Basic
반응형

Linear Regression

  • Data definition (학습할 데이터 알아보기)
  • Hypothesis (가설검정 함수 구현하기)
  • Compute loss (컴퓨팅 loss구하기)
  • Gradient descent

Data Definition

공부한 시간과 점수의 상관관계가 얼마나 있는가?

  • 내가 4시간 공부하면 성적을 얼마나 받을까?

 

  • train set : 학습할 때 사용되는 데이터 set

  • test set : 학습이 끝난 후 이 model이 얼마나 잘 작동하는지 판별하기 위한 data set

실습

  • data는 torch.tensor!
  • 입력 : x_train
  • 출력 : y_train
  • 입철력은 x, y로 구분
import torch

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

Hypothesis

Linear Regression은 학습 data와 가장 잘 맞는 하나의 직선을 찾는 일.

𝑦=𝑊𝑥+𝑏y=Wx+b

  • 𝑊W : Weight

  • 𝑏b : Bias

  • Weight 와 Bias를 0으로 초기화 -> 어떤 입력을 받아도 항상 출력 0을 예측

  • requires_grad = True -> 학습할 것이라고 명시

W = torch.zeros(1, requires_grad = True) # W를 학습할 것이라고 명시
b = torch.zeros(1, requires_grad = True) # b를 학습할 것이라고 명시
hypothesis = x_train*W + b

Compute loss

학습을 하려면 우리의 모델이 얼마나 정답과 가까운지 알아야 한다.
얼마나 가까운지 확인하는 수치를 cost 또는 loss라고 한다.
연속형 결과에선 Mean Squared Error(MSE)를 loss로 사용한다.

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

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

Gradient descent

  • torch.optim 라이브러리 사용
    • [W, b]는 학습할 tensor 들
    • lr = 0.01은 learning rate

 

  • 항상 붙어다니는 3줄
    • zero_grad()로 gradient 초기화
    • backward()로 gradient 계산
    • step()으로 개선

Full code

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

W = torch.zeros(1, requires_grad = True) # W를 학습할 것이라고 명시
b = torch.zeros(1, requires_grad = True) # b를 학습할 것이라고 명시

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

nb_epochs = 1000
for epoch 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()
    
print('Weight : ', W)
print('Bias : ', b)

>>> 
Weight :  tensor([2.0000], requires_grad=True)
Bias :  tensor([8.7018e-06], requires_grad=True)

 

반응형

'AI Study > DL_Basic' 카테고리의 다른 글

[파이토치로 시작하는 딥러닝 기초]05_ Logistic Regression  (0) 2020.12.22
[파이토치로 시작하는 딥러닝 기초]04.02_Loading Data  (0) 2020.12.21
[파이토치로 시작하는 딥러닝 기초]04.01_Multivariable_Linear_regression  (0) 2020.12.21
[파이토치로 시작하는 딥러닝 기초]03_Deeper Look at Gradient Descent  (0) 2020.12.21
[파이토치로 시작하는 딥러닝 기초]01_Tensor Manipulation(텐서 조작)  (0) 2020.11.26
'AI Study/DL_Basic' 카테고리의 다른 글
  • [파이토치로 시작하는 딥러닝 기초]04.02_Loading Data
  • [파이토치로 시작하는 딥러닝 기초]04.01_Multivariable_Linear_regression
  • [파이토치로 시작하는 딥러닝 기초]03_Deeper Look at Gradient Descent
  • [파이토치로 시작하는 딥러닝 기초]01_Tensor Manipulation(텐서 조작)
자동화먹
자동화먹
많은 사람들에게 도움이 되는 생산적인 기록하기
    반응형
  • 자동화먹
    자동화먹의 생산적인 기록
    자동화먹
  • 전체
    오늘
    어제
    • 분류 전체보기 (144)
      • 생산성 & 자동화 툴 (30)
        • Notion (24)
        • Obsidian (0)
        • Make.com (1)
        • tips (5)
      • Programming (37)
        • Python (18)
        • Oracle (6)
        • Git (13)
      • AI Study (65)
        • DL_Basic (14)
        • ML_Basic (14)
        • NLP (21)
        • Marketing&Recommend (4)
        • chatGPT (0)
        • etc (12)
      • 주인장의 생각서랍 (10)
        • 생각정리 (4)
        • 독서기록 (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Python
    빅데이터
    git
    Transformer
    파이토치로 시작하는 딥러닝 기초
    seq2seq
    노션
    노션첫걸음
    nlp
    ML
    파이토치
    Github
    데이터분석
    머신러닝
    cnn
    dl
    Google Cloud Platform
    딥러닝
    자연어처리
    Jupyter notebook
    LSTM
    python기초
    데이터베이스
    notion
    GPT
    기초
    빅데이터분석
    gcp
    git commit
    pytorch
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
자동화먹
[파이토치로 시작하는 딥러닝 기초]02_Linear Regression
상단으로

티스토리툴바