[PyTorch] Lab08.1 - Perceptron

Yun Geonil·2021년 2월 20일
0

📌 학습 목표


  • Perceptron
  • AND, OR
  • XOR
  • Code: XOR

Perceptron

  • 인간의 Neuron을 본따 만든 것을 인공 신경망이라고 한다.

    아래 그림과 같이 input data에 대해 weights들을 모두 곱해주고 bias를 더한뒤 어떠한 함수(activation function)을 지나 출력하게 된다.

AND, OR

  • ANDOR의 게이트는 다음과 같다.

    AND는 둘다 1이여야만 1을 출력하고, OR은 하나만 1이여도 1을 출력하게 된다. x에대한 y를 그래프로 그려 선으로 분리해보면 분리가 가능하다는 것을 쉽게 알 수 있다.

XOR

  • XOR의 게이트는 다음과 같다.

    XOR(Exclusive OR)은 상호배타적 OR이라고 하며 input A, B가 서로 다를 때만 1을 출력하고 같다면 0을 출력하는 게이트이다. AND, OR과 마찬가지로 x에대한 y를 그래프로 그려 "직선"으로 분리해보면 분리가 불가능하다.

Code : XOR

  • XOR을 학습하는 모델을 만들어보자.

    torch.nn.Sequential은 순서대로 구조를 쌓는 것이다. 지금은 linear에 sigmoid 를 쌓았다. 그 뒤 학습을 진행시키면 일정 이상부터 학습이 되지 않는다.

import torch

device = 'cpu'
torch.manual_seed(1)

X = torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]).to(device)
Y = torch.FloatTensor([[0], [1], [1], [0]]).to(device)

linear = torch.nn.Linear(2, 1, bias=True)
sigmoid = torch.nn.Sigmoid()
model = torch.nn.Sequential(linear, sigmoid).to(device)

#define loss function and optimizer
criterion = torch.nn.BCELoss().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=1)

for step in range(10001):
    optimizer.zero_grad()
    hypothesis = model(X)
    
    cost = criterion(hypothesis, Y)
    cost.backward()
    
    optimizer.step()
    if step % 1000 == 0:
        print(step, cost.item())
'''
0 0.7018222212791443
1000 0.6931471824645996
2000 0.6931471824645996
3000 0.6931471824645996
4000 0.6931471824645996
5000 0.6931471824645996
6000 0.6931471824645996
7000 0.6931471824645996
8000 0.6931471824645996
9000 0.6931471824645996
10000 0.6931471824645996
'''
  • 모델 평가

    앞서 훈련시킨 모델을 평가해보도록 한다.

with torch.no_grad():
    hypothesis = model(X)
    predicted = (hypothesis > 0.5).float()
    accuracy = (predicted == Y).float().mean()
    print('\nHypothesis: ', hypothesis.detach().cpu().numpy(), 
					'\nCorrect: ', predicted.detach().cpu().numpy(), 
					'\nAccuracy: ', accuracy.item())
'''
Hypothesis:  [[0.5]
 [0.5]
 [0.5]
 [0.5]] 
Correct:  [[0.]
 [0.]
 [0.]
 [0.]] 
Accuracy:  0.5
'''

결과를 살펴보면 제대로 분류하지 못하고 있다. 그렇다면 XOR을 어떻게 분류할 수 있을까.

바로 레이어를 쌓는 것이다. 이는 다음에 알아보도록 한다.

0개의 댓글