IT Repository

(3) What is Neural Network? 본문

Basic fundamentals

(3) What is Neural Network?

IT찬니 2020. 1. 6. 20:29

 

 

 

 

Structure of Neuron

img src = https://s3-us-west-2.amazonaws.com/

1. Dendrite에서 다른 뉴런들로부터 전기신호를 받음
2. 신호들을 조합하여 처리
3. Axon terminal에서 다른 Neuron으로 넘겨줌

 

Neural Network: Mathematical Model of Neuron

아래는 위의 Neuron의 구조를 수학적으로 모델링한 것입니다.

$\array{\textbf{axon from a neuron} && \textbf{synapse} &&\textbf{dendrite} \\ x_0 & \rightarrow & w_0 & \rightarrow & w_0x_0 \\ &&&& w_1x_1 \\ &&&& w_2x_2} \Rightarrow \array{\textbf{Cell body}\\ \sum_i w_ix_i + b} \Rightarrow \textbf{activation function} \Rightarrow \array{\textbf{output axion} \\ f \left ( \sum_i w_ix_i + b \right )}$

이를 Perceptron 모델 또는 뉴럴 네트워크(Neural Network) 라고 명명합니다.

 

Activation function
들어온 신호의 값이 일정 이상(역치) 넘어야 다음 Neuron으로 신호를 전달하는 Neuron의 특징을 구현한 것입니다.
만약, activation function이 Linear하다면 어떠한 x값에서도 y값을 출력할 수 있게 됩니다.
따라서 activation function은 어떠한 x값에서는 y를 출력하지 않도록, Non-linear해야 합니다.

In [54]:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 1001)
linear_y = x
non_linear_y = np.maximum(0, x)

plt.figure(figsize=(8, 3))

ax1 = plt.subplot(1,2,1)
ax1.plot(x, linear_y)
ax1.set_title("Linear")

ax2 = plt.subplot(1,2,2)
ax2.plot(x, non_linear_y)
ax2.set_title("Non-linear")

plt.show()
 
 

Simplification of NN
위 모델링 구조에서 output을 보면 우리가 익숙한 $wx + b$에 activation function을 덧씌운 구조입니다.
우리는 이를 통해 Linear Regression과 비슷한 모델링이 가능하다는 해석을 할 수 있습니다.

이제 복잡하게 보이는 모델링 구조를 조금 단순화해보겠습니다.

$\begin{cases} \text{axon 1} \\ \text{axon 2} \\ \text{axon 3} \end{cases} \Rightarrow \text{output axon: } f (w_1x_1 + w_2x_2 + w_3x_3 + b)$

결국 output은 $f(WX + b)$가 되겠네요.
역시 Linear Regression과 같은 구조로 모델링이 가능하다는 것을 알 수 있습니다.

이러한 뉴럴 네트워크는 아래의 XOR Problem을 해결할 수 없다는 문제에 봉착합니다.

 

XOR Problem

In [79]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def draw_points(ax, mode, text_margin):
    ax.set_title(mode.upper())
    for x in [0, 1]:
        for y in [0, 1]:
            
            # label and scatter
            if mode=="and":
                value = x and y
            elif mode=="or":
                value = x or y
            elif mode=="xor":
                value = x^y
            
            color = "red" if value==0 else "blue"
            ax.text(x, y, str(value), color=color, alpha=0.7, fontsize=15)
            ax.scatter([0.2 if x==0 else 0.9], [0.2 if y==0 else 0.9], c=color, alpha=0.7)
            
            # text of coordinates
            x_text = x
            y_text = y
            if x==0:
                x_text -= text_margin
            if y==0:
                y_text -= text_margin
            else:
                y_text += text_margin
                
            ax.text(x_text, y_text, "({}, {})".format(x, y))
            
def draw_subplot(rows, columns, order):
    rect = plt.Rectangle((-0.4, -0.3), 1.9, 1.7, fill=False)
    ax = plt.subplot(rows, columns, order)
    ax.add_patch(rect)
    
    ax.plot([-10,10], [0.2,0.2], "--", color="black", alpha=0.2)
    ax.plot([0.2,0.2], [-10,10], "--", color="black", alpha=0.2)
    ax.axis("off")
    ax.axis(xmin=-0.5, xmax=1.7, ymin=-0.5, ymax=1.7)
    return ax
            
plt.figure(figsize=(15, 5))

ax1 = draw_subplot(1,3,1)
ax2 = draw_subplot(1,3,2)
ax3 = draw_subplot(1,3,3)

draw_points(ax1, "and", 0.2)
draw_points(ax2, "or", 0.2)
draw_points(ax3, "xor", 0.2)
plt.show()
 
 
(a, b) AND OR XOR
(0, 0) 0 0 0
(0, 1) 0 1 1
(1, 0) 0 1 1
(1, 1) 1 1 0

아래의 표는 AND, OR, XOR 논리 연산표이고, 위의 그림은 표의 각 좌표(a, b)를 그래프 상에 도식화한 것입니다.
각 좌표의 결과가 0일떄에는 빨간색, 1일때에는 파란색으로 표시했습니다.
(점선은 평면 좌표계라는 것을 좀 더 시각적으로 나타내기 위한 가이드 라인일뿐 특별한 의미는 없습니다.)

이를 Classification한다고 생각해 봅시다.

AND와 OR은 하나의 선으로 분류할 수 있습니다.
그러나 XOR은 하나의 선으로는 절대로 분류가 불가능합니다.

 

MLP

위와 같이 XOR은 하나의 Decision Boundary, 즉 Single Layer로는 해결이 불가능했습니다.
(이미 다른 많은 자료에서 "인공지능의 암흑기" 라는 주제로 이를 다루니 여기서는 더 이상 언급하지 않습니다.)

이 XOR Problem은 Input Layer와 Output Layer 사이에
추가적인 Hidden Layer를 두는 MLP(Multi Layer Perceptron) 구조로 해결했습니다.

하지만 층이 쌓일수록 너무 많은 Parameter들이 복잡하게 얽혀있어서, MLP를 트레이닝할 수 있는 방법이 없었습니다.

(그 후에 Backpropagation 알고리즘이 연구되고 나서야 MLP를 트레이닝할 수 있게 되었습니다.)

 

Solving XOR Problem

MLP를 통해 XOR Problem이 어떻게 해결되는지를 알고 싶다면 아래 계산 과정을 따라가 보시기 바랍니다.
관심없으신 분들은 넘어가셔도 좋습니다. (정말 중요한건 곧 배울 Backpropagation 이니까요.)

 

$H_i~(X) = \sigma (W_iX + b_i)$
($\sigma$는 Sigmoid function을 의미합니다.)

H1과 H2의 아웃풋이 각각 H3의 인풋 되는 MLP 모델을 구성한다고 가정합니다.
$(H_1, H_2) ~~~\Rightarrow~~~ H_3$

또한, 각 H들의 W와 b는 아래와 같이 설정된 상태입니다.
$\begin{eqnarray} H_1 & : ~~ & W_1 = (5, 5)& ,~b_1 = -8 \\ H_2 & : ~~ & W_2 = (-7, -7)& ,~b_2 = 3 \\ H_3 & : ~~ & W_3 = (-11, -11)& ,~b_3 = 6 \end{eqnarray}$

 

이제 $X = (0, 0)$ 을 인풋으로 넣어보겠습니다.

$\begin{eqnarray} H_1(0, 0) &=& \sigma \big( 5 \cdot 0 + 5 \cdot 0 - 8 \big) \\ &=& \sigma \big( -8 \big) \\ &=& 0 \end{eqnarray}$

$\begin{eqnarray} H_2(0, 0) &=& \sigma \big( (-7) \cdot 0 + (-7) \cdot 0 + 3 \big) \\ &=& \sigma \big( 3 \big) \\ &=& 1 \end{eqnarray}$

$\begin{eqnarray} H_3(0, 1) &=& \sigma \big( (-11) \cdot 0 + (-11) \cdot 1 + 6 \big) \\ &=& \sigma \big( -5 \big) \\ &=& 0 \end{eqnarray}$

XOR(0, 0)과 MLP의 마지막 층인 H3의 아웃풋 모두 0으로 동일한 결과가 나왔네요.

이와 같이 결과 표를 그려보면 아래와 같습니다.

(x1, x2) H1 H2 H3 XOR
(0, 0) 0 1 0 0
(1, 0) 0 0 1 1
(0, 1) 0 0 1 1
(1, 1) 1 0 0 0

'Basic fundamentals' 카테고리의 다른 글

(5) Model Capacity  (0) 2020.01.13
(4) What is Backpropagation?  (0) 2020.01.06
(2) What is Gradient Descent? (Optimization)  (0) 2020.01.05
(1) What is Loss Function?  (0) 2020.01.05
(0) Overview of Fundamentals  (0) 2020.01.05
Comments