#pytorch
import torch
import numpy as np
import pandas as pd
#최적화 알고리즘: SGD 사용하기 위해
import torch.optim as optim
#For reproducibility
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)
print(x_data)
print(y_train)
x_data는 [공부시간, 출석 횟수]로 이루어져있고, y_data는 시험합격 = 1 & 시험불합격 = 0이다.
#모델초기화
# 입력데이터(x) ==> 2
# 출력(y) ==> 0 / 1
# requires_grad = True 학습을 위한 변
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)
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()
))

.item(): tensor 변수에서 값만 가져오기
torch.sigmoid: sigmoid 함수
nn.BCELoss: 직접 cost함수를 구현하는 대신 이걸 쓰면 편함
(binary cross entropy의 약자)
linear regression과 바뀐 H(x)와 cost를 위에서 코드로 구현함
print(W)
print(b)
위에서 학습한 weight과 bias를 출력해보면 다음과 같은 결과
#이미 학습하면서 계산된 W,b를 이용해서 hypothesis 계산
hypothesis = torch.sigmoid(x_train.matmul(W)+b)
print(hypothesis)
prediction = hypothesis >= torch.FloatTensor([0.5])
print(prediction[:5])
최종 hypothesis와 prediction 결과를 출력. hypothesis는 값으로 되어 있기 때문에 이를 label로 바꿔주는 과정이 필요함.
hypothesis를 0.5와 크기를 비교하고, 0.5보다 크면 label=1 작으면 label=0이 되는 것
print(prediction.type())
이때, prediction 타입은 bool이다.
# BoolTensor => FloatTensor
correct_prediction = prediction.float() == y_train
print(correct_prediction)
accuracy = correct_prediction.sum().item() / len(correct_prediction)
print('This model has an accuracy of {:2.2f}% for the training set'.format(accuracy*100))

.float(): bool -> float로 바꿔줌.sum(): bool로 표시된 배열을 값으로 더해줌
(T=1, F= 0)
prediction은 bool이기 때문에 float으로 바꿔준 후 y_train과 비교해야 한다. 얼마나 맞았는지는 변수 correct_prediction에 저장하기.
XX = torch.FloatTensor([100,1])
hypothesis_XX = torch.sigmoid(XX.matmul(W)+b)
prediction_XX = hypothesis_XX >= torch.FloatTensor([0.5])
print(prediction_XX)

새로운 데이터를 넣어주면 어떤 결과가 나올까?
공부를 100시간 하고 출석을 1번하면 시험에 합격한다는 결과가 나와!
본 게시물을 세종대학교 최유경 교수님 인공지능 수업을 바탕으로 정리하였습니다.