본문 바로가기
인공지능 개발하기/Machine Learning

퍼셉트론과 XOR 문제

by 선의공 2024. 2. 18.

 
 
 

인공지능의 역사를 올라가보면
인공지능의 겨울이 두번 있었다고 합니다.
이중 첫번째 겨울의 원인이였던 XOR 문제를 해결한 방법 대해서 다뤄보려고 합니다. 
해당 포스팅을 보며 확인했습니다.
 
https://www.insilicogen.com/blog/340

 

 

人Co BLOG  :: 인공지능(AI)의 역사

Posted at 2020/03/10 14:16 Filed under 지식관리 인공지능의 개념은 언제, 어디서부터 시작되어 오늘날 이렇게 각광 받고 있는지 함께 알아보도록 하겠습니다! 영화 속 주인공인 토니 스타크가 아이언맨

www.insilicogen.com

https://www.letr.ai/blog/story-20211119-1

 

[AI 이야기] 인공지능의 결정적 인물들 (4)딥러닝의 선구자, 로젠블랫

시리즈의 네 번째 순서로 현대 딥러닝의 토대를 마련한 프랭크 로젠블랫에 관해 알아봅니다. 혹시 ...

www.letr.ai

https://ang-love-chang.tistory.com/26

 

[인공지능]다층 퍼셉트론으로 XOR문제 해결하기

이 책에 있는 내용을 정리 한 것임. 모두의 딥러닝 개정2판: 3 코딩으로 XOR 문제 해결하기 - 4 thebook.io 2 퍼셉트론의 과제 사람의 뇌가 작동하는 데 1,000억 개나 되는 뉴런이 존재해야 하는 이유는

ang-love-chang.tistory.com

 


 

1. 인공지능의 겨울 - 퍼셉트론

 
1943년에 최초로 뇌의 뉴런 작용을 수학적으로 제시한
맥컬리, 피츠의  '맥컬리-피츠' 라는 논문이 발표되었습니다.
 
15년 후 1958년 로젠블랫이 해당 논문의 개념에
가중치(Weight)이라는 개념을 추가하여
"퍼셉트론"이라는 논문을 발표하였구요.

 
로젠블랫은 이 내용을 바탕으로
미 해군 연구소의 이미지를 분류하는 시연을 성공하면서 
사회적으로 큰 관심을 받습니다.
 
하지만 퍼셉트론은 XOR이라는 문제를 풀지 못하는
한계가 있다고 비판되었으며
이로 인해  관심과 지원이 끊어지게 됩니다.
 
여기에 1971년 로젠블랫의 사망(자살로 추정되는)까지 겹치면서
"인공지능은 불가능하다"라는 사회적 인식이 심어지고
인공지능의 겨울이 찾아오게 된 것이지요
 
 


 

2. XOR이란?

 
 
XOR이란 0과 1로 표현되는 컴퓨터의 비트 연산 중 하나입니다.
 AND, NAND, OR 과 같은
평면상 직선으로 연산이 가능한
선형 문제가 아닌
직선으로 연산이 불가능한
비선형 문제입니다.
 
 

 

이미지 출처: https://velog.io/@hewas1230/PerceptronSigmoid

 

 
직선을 그어 구분이 가능안 AND, NAND, OR와 다르게
직선으로서 구분하지 못하는 문제에 도달해서
퍼셉트론은 XOR의 문제에 부딪히게 된 것이죠.
 
 
 


 

 

3. 문제 해결

 

1971 인공지능의 겨울 이 후에도 끊임없이 인공지능을 연구해온 학자가 있습니다.
바로 현재 딥러닝의 아버지라고 불리는 '제프리힌튼' 교수입니다.
 
제프리 힌튼 교수는 XOR문제를 다층 퍼셉트론(Multi - Layer Perceptron, MLP)로서
해결했습니다,
 
아래와 같이 평면상 선형식으로는 XOR의 문제를 
해결할 수 없었지만

 
 
평면을 휨으로서 좌표평면 자체에 변화를 주어
XOR의 0과 1을 구분해냈습니다.

 
 

 

이미지 출처 : http://www.aistudy.co.kr/neural/multilayer_perceptron.htm

 
 

퍼셉트론의 레이어가 추가될 수록 좌표평면이 왜곡되고,
데이터의 공간이 변형되면서 XOR 문제 해결함으로서
인공지능의 겨울이 끝나고
또다시 딥러닝의 발전이 가속되었습니다.
(MLP도 마찬가지로 과적합이나, gradient venising 같은 문제에
봉착하긴 했지만요..)
 
 
 


 

4. 구현

 
 

실제로 코드상에서 구현하며
테스트 해보겠습니다.
 
 
먼저 문제였던
단일 퍼셉트론 모델을 구현하기 위해
scikit learn에서 제공하는
 linear_mode 모듈의 Perceptron 을 사용했습니다.

import numpy as np
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score

x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([0, 1, 1, 0])
for _ in range(0,20):
    model = Perceptron()

    model.fit(x, y)
    predict = model.predict(x)
    acc_score = accuracy_score(y, predict)
    print(f'''
        {type(model).__name__} predict is [{predict}]
        accuracy score is [{ acc_score}]"
        ''')
   
   #결과
   '''
        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"


        Perceptron predict is [[0 0 0 0]]
        accuracy score is [0.5]"
   '''

 

Preceptron 모델을 사용해서 20번을 반복해도 XOR의 결과를 한번도 맞추지 못했습니다.
 
 
 
이번에는 해결책으로
다중 퍼셉트론을 구현하기 위해서
tensorflow의 keras 패키지를 사용해서
모델 구현을 해주겠습니다.

import numpy as np   
from keras.models import Model
from keras.layers import Input,Dense
from sklearn.metrics import accuracy_score
    
x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([0, 1, 1, 0])

input_layer = Input(shape= (2,)) #input_shape (2,)
hidden_layer = Dense(10, activation='relu')(input_layer)
output_layer = Dense(1, activation='sigmoid')(hidden_layer) #이진분류 activation = sigmoid

model = Model(inputs = input_layer, outputs = output_layer) 

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])#이진분류 loss = binary_crossentropy
model.fit(x, y, epochs=100, verbose=0)

predict = np.round(model.predict(x, verbose=0)).reshape(-1,).astype(int)
acc_score = accuracy_score(y, predict)
print(f'''
    {type(model).__name__} predict is [{predict}]
    accuracy score is [{ acc_score}]"
    ''')
    
    '''
        Functional predict is [[0 1 1 0]]
    	accuracy score is [1.0]"
    '''

 

저는 hidden layer 10, epochs를 100정도 주니 높은 확률로 XOR을 예측했습니다.
이렇게 다중 퍼셉트론으로 hidden layer를 1개의 층만 쌓아줘도
XOR 의 문제가 해결되는 것을 확인해봤습니다.
 
 
 
 
XOR은 직선으로 분리를 해낼 수 없어 
발생한 문제였잖아요?
 
당연히 선형이 아닌 모델을
사용해도 해결되겠죠!
 
그냥 추가로 svm을 복습한다고 생각하고,,,,
저번 포스팅에서 다룬 svm를 생각하면서
https://aigaeddo.tistory.com/42

 

[ML] 1. SVM(Support Vector Mchine)

이번 포스팅은 ML의 첫게시글이네요. ML의 중요한 개념인 SVM에 대해 학습해보겠습니다. 정말 잘 설명해주신 글이 있어 참고하였습니다. https://bkshin.tistory.com/entry/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-2%EC%84

aigaeddo.tistory.com

 
추가로 구현 해봤습니다.
역시 scikit -learn에 구현되어 있죠.
svm모듈의 SVC(Support Vector Classifier) 모델을 사용해볼게요!
svm 의 kernel이라는 개념은 고차원으로 매핑의 개념이었죠
default 값인 가우시안 커널인 'rbf'로 설정해서 사용해보겠습니다.

 import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([0, 1, 1, 0])
for _ in range(0,20):
    model = SVC(kernel='rbf',C=1) #default 값 : kernel 'rbf', c = 1

    model.fit(x, y)
    predict = model.predict(x)
    acc_score = accuracy_score(y, predict)
    print(f'''
        {type(model).__name__} predict is [{predict}]
        accuracy score is [{ acc_score}]"
        ''')
        
    '''
            SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"


        SVC predict is [[0 1 1 0]]
        accuracy score is [1.0]"
    '''

 
C의 값을 default값인 1로 줘도 XOR을 잘 예측하는 것을 확인할 수 있습니다.
 
 
 
이번 포스팅에서는 인공지능의 겨울이 왔던 문제였던,
XOR문제를 직접 코드로서 구현해봤습니다.
 
 
틀린점 있으면 지적 부탁드립니다!