score() | result() |
---|---|
45 | 불합격 |
50 | 불합격 |
55 | 불합격 |
60 | 합격 |
65 | 합격 |
70 | 합격 |
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
# 시그모이드 함수 정의
return 1/(1+np.exp(-x))
x=np.arange(-5.0,5.0,0.1)
y=sigmoid(x)
plt.plot(x,y,'g')
plt.plot([0,0],[1.0,0.0],':') # 가운데 점선 추가
plt.title('Sigmoid Function')
plt.show()
x=np.arange(-5.0,5.0,0.1)
y1=sigmoid(0.5*x)
y2=sigmoid(x)
y3=sigmoid(2*x)
plt.plot(x,y1,'r',linestyle='--') #W의 값이 0.5일때
plt.plot(x,y2,'g') #W의 값이 1일때
plt.plot(x,y3,'b',linestyle='--') #W의 값이 2일때
plt.plot([0,0],[1.0,0.0],':') #가운데 점선 추가
plt.title('Sigmoid Function')
plt.show()
x=np.arange(-5.0,5.0,0.1)
y1=sigmoid(x+0.5)
y2=sigmoid(x+1)
y3=sigmoid(x+1.5)
plt.plot(x,y1,'r',linestyle='--') #W의 값이 0.5일때
plt.plot(x,y2,'g') #W의 값이 1일때
plt.plot(x,y3,'b',linestyle='--') #W의 값이 2일때
plt.plot([0,0],[1.0,0.0],':') #가운데 점선 추가
plt.title('Sigmoid Function')
plt.show()
$$ if\; y=1 \rightarrow cost(H(x),y) = -log(H(x)) if\; y=0 \rightarrow cost(H(x),y) = -log(1-H(x))$$
y의 실제값이 1일때 그래프를 사용하고 의 실제값이 0일때, 그래프를 사용해야함.
$$ cost(W)=-\frac{1}{n}\sum_{i=1}^{n} [y^{(i)}logH(x^{(i)})+(1-y^{(i)})log(1-H(x^{(i)})] $$
정리하면, 위 비용 함수는 실제값 와 예측값 의 차이가 커지면 cost가 커지고, 실제값 와 예측값 의 차이가 작아지면 cost는 작아짐.
위 비용함수에 대해서 경사하강법을 수행하면서 최적의 가중치 를 찾아감.
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)
print(x_train.shape)
print(y_train.shape)
torch.Size([6, 2])
torch.Size([6, 1])
W = torch.zeros((2,1),requires_grad=True)
b = torch.zeros(1,requires_grad=True)
# 시그모이드 정의 대로 식 설정
hypothesis = 1 / (1 + torch.exp(-(x_train.matmul(W)+b)))
# torch를 통해 구현
hypothesis = torch.sigmoid(x_train.matmul(W)+b)
print(hypothesis)
print(y_train)
#hypothesis
tensor([[0.5000],
[0.5000],
[0.5000],
[0.5000],
[0.5000],
[0.5000]], grad_fn=<SigmoidBackward0>)
# answer
tensor([[0.],
[0.],
[0.],
[1.],
[1.],
[1.]])
-(y_train[0] * torch.log(hypothesis[0])) + (1-y_train[0]) * torch.log(1-hypothesis[0])
losses= -(y_train * torch.log(hypothesis) + (1-y_train) * torch.log(1-hypothesis))
cost = losses.mean()
print(losses)
print(cost)
tensor([[0.6931],
[0.6931],
[0.6931],
[0.6931],
[0.6931],
[0.6931]], grad_fn=<NegBackward0>)
tensor(0.6931, grad_fn=<MeanBackward0>)
torch.nn.functional
에서 제공하는 비용함수# torch.nn.functional as F에서 제공하는 비용함수 binary_cross_entropy(예측값, 실제값)
F.binary_cross_entropy(hypothesis,y_train)
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)
cost=-(y_train * torch.log(hypothesis) + (1-y_train)*torch.log(1-hypothesis)).mean()
optimizer.zero_grad()
cost.backward()
optimizer.step()
if epoch % 100 == 0:
print('Epoch {:4d}/{} Cost {:.6f}'.format(epoch,nb_epochs,cost.item()))
Epoch 0/1000 Cost 0.693147
Epoch 100/1000 Cost 0.134722
...
Epoch 900/1000 Cost 0.021888
Epoch 1000/1000 Cost 0.019852
print(W)
print(b)
tensor([[3.2530],
[1.5179]], requires_grad=True)
tensor([-14.4819], requires_grad=True)