Pytorch_Logistic_regression

Pytorch Logistic regression(Binary Classifier만들기)

모두를 위한 딥러닝 - 파이토치 강의 참고

  • 0과 1 두 가지를 분류하기 위한 binary classifier를 만들어 보았습니다.

  • binary 분류 문제를 해결하기 위해서는 선형 회구와 같은 실수값이 아닌 확률값을 예측해야 합니다.

  • 이를 위해 선형 함수와 sigmoid 함수를 통과하는 BinaryClassifier를 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
# 모델 정의
class BinaryClassifier(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(8, 1)
self.sigmoid = nn.Sigmoid()

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

model = BinaryClassifier()
  • 학습에 사용할 모델을 만들었으니 사용할 데이터를 불러오고 optimizer를 정의합니다.
1
2
3
4
5
6
7
xy = np.loadtxt('data/data-03-diabetes.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
x_train = torch.FloatTensor(x_data)
y_train = torch.FloatTensor(y_data)

optimizer = optim.SGD(model.parameters(), lr=1)
  • 마지막으로 epoch수 만큼 반복해 학습합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
epochs = 100

for epoch in range(epochs + 1):

hypothesis = model(x_train)

loss = F.binary_cross_entropy(hypothesis, y_train)

optimizer.zero_grad()
loss.backward()
optimizer.step()

if epoch % 10 == 0:
prediction = (hypothesis >= torch.FloatTensor([0.5])).float()
correct_prediction = (prediction == y_train).float()
accuracy = correct_prediction.sum().item() / len(correct_prediction)

print('Epoch : {:4d}/{} loss : {:6f} Accuracy : {:2.2f}'.format(
epoch, epochs, loss.item(), accuracy*100
))
  • Accuracy를 나타내줄때 올바른 예측은 hypothesis(predict) 값이 0.5보다 큰값을 기준으로 사용했습니다.

  • binary 문제를 해결하기 위해서는 sigmoid함수를 사용했습니다. 다음 강의때 다시한번 적겠지만 세개 이상의 class를 가지는 분류문제를 해결하기 위해서는 softmax함수를 사용해야 한다는 차이점을 기억해야겠습니다.

Full Code

Full Code

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×