곰퓨타의 SW 이야기

Lab-05 Logistic Regression 본문

인공지능/부스트코스_파이토치로 시작하는 딥러닝 기초

Lab-05 Logistic Regression

곰퓨타 2021. 2. 15. 22:24

이번 강의도 역시 파이토치로 시작하는 딥러닝 기초 강의를 수강하였다.

www.boostcourse.org/ai214/lecture/42289/

 

파이토치로 시작하는 딥러닝 기초

부스트코스 무료 강의

www.boostcourse.org

 

 

Reminder : Logistic Regression

[문제 정의 Hypothesis]

logistic regression은 binary classification이다. 

 

m개의 sample로 이루어지고 d의 차원을 가진 x data (mxd) 가 있고, 이것을 가지고 m개의 0과 1로 이루어진 정답을 도출해야한다.

0과 1 중 더 가까운 곳으로 예측이 된다. 

P(x=1 ) = 1 - P(x=0)

|X| = (m,d)

|W| = (d ,1 )

|X*W| = (m,d) x (d,1) = (m,1)

X와 W를 곱한 후, sigmoid 함수를 통해 0또는 1로 예측한다.

sigmoid : 1 / (1+exp(-x))

(음수라면 0과 가까워지고, 양수라면 1에 가까워진다.)

 

H(x) = P(X = 1; W) = 1- P(X=0;W)  # w가 주어졌을 때 x가 1일 확률이 H(x)이다.

 

 

[Cost & gradient descent를 통한 weight update]
기울기가 작아지는 방향으로 weight update! 

 

1. import

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


# For reproducibility
torch.manual_seed(1)

 

 

2. data load

x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]] # |x_data| = (6,2) m=6, d=2
y_data = [[0], [0], [0], [1], [1], [1]] # |y_data| = (6,)

x_train = torch.FloatTensor(x_data)
y_train = torch.FloatTensor(y_data)

print(x_train.shape)
print(y_train.shape)

 

Computing Hypothesis

 

torch에서는 sigmoid함수를 제공해준다.

# torch에서 sigmoid 제공함
# exponential 위에 들어갈 X에 해당하는 값인 XW + b를 인수로 준다.
hypothesis = torch.sigmoid(x_train.matmul(W) + b)

 

4. Computing Cost Function

 

1) 수동으로 정의하는 방법

losses = -(y_train * torch.log(hypothesis) + 
           (1 - y_train) * torch.log(1 - hypothesis))
print(losses)

cost = losses.mean()
print(cost)

 

2) binary cross entropy 사용하는 방법

F.binary_cross_entropy(hypothesis, y_train)

 

 

📌 Whole Training Procedure

1) cost function 수동으로 정의하는 방법

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)


# 모델 초기화
W = torch.zeros((2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# optimizer 설정 SGD를 통해 W와 b를 학습할 것이다. learning rate는 1로 할 것이다.
optimizer = optim.SGD([W, b], lr=1)

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

    # Cost 계산 ==> 여기주목! 
    hypothesis = torch.sigmoid(x_train.matmul(W) + b) # or .mm or @
    cost = -(y_train * torch.log(hypothesis) + 
             (1 - y_train) * torch.log(1 - hypothesis)).mean()

    # cost로 H(x) 개선
    optimizer.zero_grad() # 초기화 필수
    cost.backward()
    optimizer.step()

    # 100번마다 로그 출력
    if epoch % 100 == 0:
        print('Epoch {:4d}/{} Cost: {:.6f}'.format(
            epoch, nb_epochs, cost.item()
        ))

 

 

2) binary cross entropy 사용하여 cost function 정의하는 방법

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)

# 모델 초기화
W = torch.zeros((2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# optimizer 설정
optimizer = optim.SGD([W, b], lr=1)

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

    # Cost 계산
    hypothesis = torch.sigmoid(x_train.matmul(W) + b) # or .mm or @
    cost = F.binary_cross_entropy(hypothesis, y_train)

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

    # 100번마다 로그 출력
    if epoch % 100 == 0:
        print('Epoch {:4d}/{} Cost: {:.6f}'.format(
            epoch, nb_epochs, cost.item()
        ))

 

 

 


6. Evaluation

당뇨병 데이터로 훈련하는 경우, Evaluate 하기 !!

 

훈련용 데이터와 test용 데이터를 구분하기 위해

x_data와 y_data에서 train data로는 처음부터 마지막 50개를 제외한 것을 지정하였고,

나머지 50개는 test data로 쪼갰다.

 

cf) 당뇨병 데이터 불러와서 훈련하는 과정 (이는 다음 github를 clone한 것이다. github.com/deeplearningzerotoall/PyTorch)

import numpy as np

xy = np.loadtxt('data-03-diabetes.csv', delimiter=',', dtype=np.float32)

x_data = xy[:-5, 0:-1]
y_data = xy[:-5, [-1]]

# 앞에서부터 뒤의 50개 빼고 train 데이터로
x_train = torch.FloatTensor(x_data[:-50])
y_train = torch.FloatTensor(y_data[:-50])

# 뒤에 50개는 test 데이터로
x_test = torch.FloatTensor(x_data[-50:])
y_test = torch.FloatTensor(y_data[-50:])

# 모델 초기화
W = torch.zeros((8, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# optimizer 설정
optimizer = optim.SGD([W, b], lr=1)


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

    # Cost 계산
    hypothesis = torch.sigmoid(x_train.matmul(W) + b) # or .mm or @
    cost = -(y_train * torch.log(hypothesis) + (1 - y_train) * torch.log(1 - hypothesis)).mean()

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

    # 10번마다 로그 출력
    if epoch % 10 == 0:
        print('Epoch {:4d}/{} Cost: {:.6f}'.format(
            epoch, nb_epochs, cost.item()
        ))

 

 

Evaluation

# 정확도 측정을 위해 test 데이터 활용
hypothesis = torch.sigmoid(x_test.matmul(W) + b)

# 0인지 1인지 찍는 과정 필요
# 0.5보다 크거나 같으면 prediction에는 True인 1이 들어가도록
# 0.5보다 작으면 prediction에는 False인 0이 들어가도록
prediction = hypothesis >= torch.FloatTensor([0.5])


# 예측값과 실제 test data 값의 차이를 비교하며 정확도 측정 
# prediction이 byte tensor이므로 float로 형변환
correct_prediction = prediction.float() == y_test


# 정확도 측정하기!
accuracy = correct_prediction.sum().item() / len(correct_prediction)
print('The model has an accuracy of {:2.2f}% for the training set.'.format(accuracy * 100))

 

 

 

 

 


cf ) Higher Implementation : nn.Module을 상속하여 logistic regression구현하기

# nn.Module 상속받아서 binary classifier 구현하느 방법 (logistic regression)
class BinaryClassifier(nn.Module):
    def __init__(self):
        #W와 b가 들어있음
        super().__init__()
        # self.linear= {W,b} W: 8개의 dimension, b는 사이즈 1
        self.linear = nn.Linear(8, 1)
        self.sigmoid = nn.Sigmoid()
    
    # 전체 모델의 sigmoid
    def forward(self, x):
        return self.sigmoid(self.linear(x))
        
        
  model = BinaryClassifier()
  
  # optimizer 설정
optimizer = optim.SGD(model.parameters(), lr=1)

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

    # H(x) 계산 -> P(X=1) 확률
    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])
        correct_prediction = prediction.float() == y_train
        accuracy = correct_prediction.sum().item() / len(correct_prediction)
        print('Epoch {:4d}/{} Cost: {:.6f} Accuracy {:2.2f}%'.format(
            epoch, nb_epochs, cost.item(), accuracy * 100,
        ))

 

 

 

 

이 강의는 모두를 위한 딥러닝 강의1을 수강한 사람들을 위한 강의라는 것이 살짝 느껴졌는데, 우선 이 강의를 다 듣고 모두를 위한 딥러닝 1 강의도 들어야 겠다..ㅎㅎ

Comments