본문 바로가기
IT 도서/Pytorch로 시작하는 딥 러닝 입문

03. 로지스틱 회귀 (Logistic Regression)

by 이민우 2021. 3. 1.
728x90
반응형

wikidocs.net/57805

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

*해당 글은 학습을 목적으로 위의 포스팅 내용 중 일부 내용만을 요약하여 작성한 포스팅입니다.

 상세한 내용 및 전체 내용 확인은 위의 링크에서 확인하실 수 있습니다.

 

이진 분류 (Binary Classifier)

  • 둘 중 하나를 고르는 문제
  • 시험 점수를 보고 합격, 불합격을 결정하는 게 예시.
  • 이진 분류를 그래프로 그리면 S자 형태가 나타나는데, 이러한 S자 형태의 그래프를 그리는 데 시그모이드 함수가  사용된다.

 

 

 

시그모이드 함수 (Sigmoid Function)

https://123okk2.tistory.com/145?category=960907
https://wikidocs.net/57805

  • W값은 경사도에 영향을 미친다. (경사도가 W의 크기에 비례)
  • b의 값은 커지면 좌로, 작아지면 우로 그래프가 이동한다.
  • 시그모이드 함수는 입력값이 한없이 커지먼 1에 수렴하고, 한 없이 작아지면 0에 수렴한다.
  • 그렇기에 늘 0~1의 값을 가지는데, 이 특성으로 0.5 이상이면 1, 0.5 이하면 0으로 판단하여 로지스틱 회귀에 활용할 수 있다.

 

 

 

로지스틱 회귀 (Logistic Regression)

  • 이진 분류를 풀기 위한 대표적인 알고리즘
  • 이름은 회귀이지만 실제로는 분류 작업에 사용이 가능하다.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import TensorDataset # 텐서데이터셋
from torch.utils.data import DataLoader # 데이터로더
from tqdm.notebook import tqdm

#데이터 지정
x_train = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] # 6*2
y_train = [[0], [0], [0], [1], [1], [1]]
x_train = torch.FloatTensor(x_train)
y_train = torch.FloatTensor(y_train)

trainset = TensorDataset(x_train, y_train)
trainset = DataLoader(trainset, batch_size=2, shuffle = True)

class LogisticRegression(nn.Module) :
    def __init__(self) :
        super().__init__()
        self.linear = nn.Linear(2, 1) #input = 2, output = 1
    
    def forward(self, x) :
       output = self.linear(x)
       output = F.sigmoid(output)
       return output

model = LogisticRegression()
optimizer = optim.SGD(model.parameters(), lr = 0.001)

n_epochs = 2000
for epoch in tqdm(range(n_epochs+1)) :
    for batch_idx, samples in enumerate(trainset) :
        x_train, y_train = samples

        predict = model(x_train) # H(x)

        cost = F.binary_cross_entropy(predict, y_train)

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

        print('Epoch {:4d}/{} Batch {}/{} Cost: {:.6f}'.format(
          epoch, n_epochs, batch_idx+1, len(trainset),
          cost.item()
        ))
728x90
반응형