Logistic Rergression

최지안·2024년 10월 7일

1. 이진 분류(Binary Classification)

💡

결과가 0 또는 1로 나오는 문제

2. 시그모이드 함수(Sigmoid Function)

💡

S자 형태로 그래프를 그려주는 시그모이드 함수

H(x)=sigmoid(Wx+b)=11+e(Wx+b)=σ(Wx+b)H(x) = \text{sigmoid}(Wx + b) = \frac{1}{1 + e^{-(Wx + b)}} = \sigma(Wx + b)

3. 비용 함수(Cost function)

💡

평균 제곱 오차(Mean Square Error, MSE

cost(W,b)=1ni=1n[y(i)H(x(i))]2\text{cost}(W, b) = \frac{1}{n} \sum_{i=1}^{n} \left[ y^{(i)} - H\left( x^{(i)} \right) \right]^2

4. pytorch로 logistic regression 구현하기

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

torch.manual_seed(1)

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

class BinaryClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(2, 1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        return self.sigmoid(self.linear(x))

model = BinaryClassifier()

# optimizer 설정
optimizer = optim.SGD(model.parameters(), lr=1)

nb_epochs = 1000
for epoch in range(nb_epochs + 1):

    # H(x) 계산
    hypothesis = model(x_train)

    # cost 계산
    cost = F.binary_cross_entropy(hypothesis, y_train)

    # cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()

    # 20번마다 로그 출력
    if epoch % 10 == 0:
        prediction = hypothesis >= torch.FloatTensor([0.5]) # 예측값이 0.5를 넘으면 True로 간주
        correct_prediction = prediction.float() == y_train # 실제값과 일치하는 경우만 True로 간주
        accuracy = correct_prediction.sum().item() / len(correct_prediction) # 정확도를 계산
        print('Epoch {:4d}/{} Cost: {:.6f} Accuracy {:2.2f}%'.format( # 각 에포크마다 정확도를 출력
            epoch, nb_epochs, cost.item(), accuracy * 100,
        ))

0개의 댓글