You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
print('e^1 equals: ', torch.exp(torch.FloatTensor([1]))) #torch.exp를 통해 exponential을 이용 가능!W=torch.zeros((2, 1), requires_grad=True) # W 초기화, 학습 가능 설정b=torch.zeros(1, requires_grad=True) # b 초기화, 학습 가능 설정hypothesis=1/ (1+torch.exp(-(x_train.matmul(W) +b))) # 모델 정의. matmul을 이용해 x 데이터만큼 weight 곱함.# hypothesis = torch.sigmoid(x_train.matmul(W) + b) # 위 처럼 수식을 직접 입력하는 것 대신에, Pytorch에서 제공하는 Sigmoid 함수로 쉽게 모델을 정의할 수도 있다!print(hypothesis)
print(hypothesis.shape)
5. Computing the Cost Function
losses=-(y_train*torch.log(hypothesis) + (1-y_train) *torch.log(1-hypothesis))
print(losses) # 전체 샘플에 대한 losscost=losses.mean() # loss 평균print(cost)
# F.binary_cross_entropy(hypothesis, y_train) # 위 처럼 수식을 직접 입력하는 것 대신에, PyTorch에서 제공하는 cross entropy 함수로 쉽게 모델을 정의할 수도 있다!
6. Whole Training Procedure
W=torch.zeros((2, 1), requires_grad=True) # W 초기화 및 학습 가능 설정b=torch.zeros(1, requires_grad=True) # b 초기화 및 학습 가능 설정optimizer=optim.SGD((W, b), lr=1) # SGD로 Gradient descent. W, b를 학습시킨다고 선언, lr을 설정함.nb_epochs=1000# 1000회 돌림!forepochinrange(nb_epochs+1):
hypothesis=torch.sigmoid(x_train.matmul(W) +b) # 모델cost=F.binary_cross_entropy(hypothesis, y_train) # 코스트# Gradient descentoptimizer.zero_grad() # 기존 Grad 초기화 (이걸 하지 않으면 기존 grad에 더하게 됨)cost.backward() # cost를 minimize하는 방향으로 backpropagate를 하게 된다.optimizer.step() # Update!ifepoch%100==0:
print('Epoch {:%d}/{} Cost: {:.6f"'.format(epoch, nb_epochs, cost.item()))
7. Evaluation
내가 만든 모델의 정확도를 평가해 보자.
Training set으로 훈련 시켰으니, Test set으로 평가를 해보자.
예측값과 정답값들을 비교하여, 평균을 내서 정확도를 구할 수 있다. (수작업 방법)
hypothesis=torch.sigmoid(x_test.matmul(W) +b) # 모델에 test 셋을 넣어서 hypothesis를 예측을 한다.print(hypothesis[:5]) # 모델을 통한 예측값 5개!prediction=hypothesis>=torch.FloatTensor([0.5]) # 0.5보다 크면 1로, 0.5보다 작으면 0으로 만들어서 예측값을 binary하게 만든다.print(prediction[:5]) # binary 한 예측값 5개!correct_prediction=prediction.float() ==y_train# 예측값과 정답값이 같은지를 판단해 correct prediction에 넣는다.print(correct_prediction[:5]) # correct prediction 확인!
8. Higher Implementation
우리는 앞에서 Binary classifier의 hypothesis 모델을 직접 만들어서 이용했다.
하지만 PyTorch의 클래스를 상속받아서 쉽게 모델을 정의할 수 있다.
classBinaryClassifier(nn.Module): # nn.Module 클래스 상속받아서 BinaryClassifier 만듦.def__init__(self):
super().__init__()
self.linear=nn.Linear(8, 1) # 8개의 element 받아서 0인지 1인지 예측하는 모델self.sigmoid=nn.Sigmoid()
defforward(self, x):
returnself.sigmoid(self.linear(x)) # 모델은 self.linear을 한 후 self.sigmoid를 하는 모델임을 정의model=BinaryClassifier() # 모델!
9. Higher Implementation with Class full code
optimizer=optim.SGD(model.parameters(), lr=1) # optimizer에 model의 parameter를 넣어 훈련 가능하게 함.nb_epochs=100forepochinrange(nb_epochs+1):
hypothesis=model(x_train) # 모델 정의cost=F.binary_cross_entropy(hypothesis, y_train) # hypothesis 예측값과 y_train 비교optimizer.zero_grad()
cost.backward()
optimizer.step()
ifepoch%10==0:
prediction=hypothesis>=torch.FloatTensor([0.5])
correct_prediction=prediction.float() ==y_trainaccuracy=correct_prediction.sum().item() /len(correct_prediction)
print('Epoch {:4d} / {} Cost : {:.6f} Accuracy {:2.2f}'.format(epoch, nb_epochs, cost.item(), accuracy*100,))