XOR 혹은 XNOR problem은 선형 모델로 즉, Single-Layer Perceptron(SLP)으로는 해결할 수 없다. 이를 해결하기 위해서 Multi-Layer Perceptron(MLP)를 도입해야 한다. SLP에서는 hidden layer가 없었다면, MLP에서는 hidden layers(latent layers)가 존재하며 hidden layer의 수가 neural network의 복잡도를 결정한다. 이를 deep neural network 라고도 한다.
Multi-Layer Perceptron: Hidden Layer가 있는 모델
Simple Example: XNOR, XOR Problem
XNOR Problem
:$y=$($x_1$ AND $x_2$) OR ((NOT $x_1$) AND (NOT $x_2$))
($x_1, x_2 \in {0,1}$)
input layer와 hidden layer 사이의 weight를 $w^{(1)}$이라 하고, hidden layer와 output layer 사이의 weight를 $w^{(2)}$라 하자. hidden layer ~ output layer만 보면 SLP와 동일하다. target과 예측치의 차이를 바탕으로 cost가 최소화되도록 cost를 미분한 gradient를 바탕으로 반대방향으로 update하면 된다. 즉, $\frac{\partial cost}{\partial w^{(2)}}$를 구하면 된다. 하지만 input layer ~ hidden layer는 SLP로는 해결할 수 없다. SLP는 오직 input과 output layers만 갖기 때문에 직접적으로 예측치와 실제 target 값을 비교하며 error를 최소화하는 weight를 update하면 된다. 반면, MLP에서는 hidden layers가 존재하므로 직접적으로 구할 수 없다. $\frac{\partial cost}{\partial w^{(1)}}$를 구해야 하는데, cost와 $w^{(1)}$의 관계를 직접적으로 파악할 수 없으므로 chain rule을 활용해야 한다. $\frac{\partial cost}{\partial w^{(1)}}= \frac{\partial cost}{\partial w^{(2)}}\times \frac{\partial w^{(2)}}{\partial w^{(1)}} $로 $ \frac{\partial cost}{\partial w^{(2)}}$와 $\frac{\partial w^{(2)}}{\partial w^{(1)}} $를 각각 구하면 Backpropagation 과정을 거치면 쉽게 구할 수 있다.
Backpropagation
우리가 구하고자 하는 gradient $\frac{\partial f}{\partial x}$는 chain rule에 의해 $\frac{\partial f}{\partial g}\frac{\partial g}{\partial x}$로 나눌 수 있다. 이때, $\frac{\partial f}{\partial g}$를 upstream gradient, $\frac{\partial g}{\partial x}$를 local gradient라 한다. 쉽게 말해, gradient = upstream gradient $\times$ local gradient로 나타낼 수 있는 것이다.
local gradient는 g 함수를 알면 쉽게 구할 수 있다. 우리는 upstream gradient만 잘 구하면 되는데, 이 또한 f와 g 사이의 노드만큼의 chain rule을 거치면 해결된다. 쉽게 계산하기 위해 대표적인 노드별 backpropagation 특징을 알아보자.
- 덧셈 노드 : g = x + y 에서는 gradient가 그대로 유지된다. 즉, $\frac{\partial f}{\partial g} = k$라면 $\frac{\partial g}{\partial x} = \frac{\partial g}{\partial y} = 1$이므로 $ \frac{\partial f}{\partial x} = \frac{\partial f}{\partial g} = k $이다.
- 곱셈 노드 : g = xy에서는 gradient가 서로 반대의 값이 곱해진다. 즉, $ \frac{\partial f}{\partial g} =k $라면 $ \frac{\partial g}{\partial x} = y$, $ \frac{\partial g}{\partial y} = x$이므로 $ \frac{\partial f}{\partial x} = \frac{\partial f}{\partial g} \frac{\partial g}{\partial x} = k\times y$이고 $ \frac{\partial f}{\partial y} = \frac{\partial f}{\partial g} \frac{\partial g}{\partial y} = k\times x$가 된다.
- 함수 노드 : g가 exponential, 혹은 그보다 더 복잡한 함수라면 앞서 언급했던 것처럼 gradient = upstream gradient $\times$ local gradient로 계산할 수 있다. upstream gradient를 직접 구할 수 없어도 맨 앞단에서부터 순차적으로 ug$\times$lg를 진행하며 upstream gradient를 구할 수 있다. 여기서 맨 앞단의 upstream gradient는 $\frac{\partial f}{\partial f}=1$이므로 1이다.
예제로 살펴보자.
이와 같은 예제에서는 두가지 방법으로 풀 수 있다.
첫번째 방법은 sigmoid 함수와 덧셈, 곱셈 노드로 나누어서 한번에 sigmoid 함수에 대한 gradient를 구하는 것이다. sigmoid 함수를 $f(z) = \frac{1}{1+e^{-z}}$라 두면 $\frac{\partial f}{\partial f} = 1$, $\frac{\partial f}{\partial z} =-\frac{e^{-z}}{(1+e^{-z})^2}= \frac{e^{-z}}{1+e^{-z}} \frac{1}{1+e^{-z}} =$ f$\times$(1-f)이므로 sigmoid 함수의 gradient는 f$\times$(1-f)이다. 자주 등장하니 외워두는 것이 좋겠다.
두번째 방법은 첫번째 방법처럼 직접 gradient를 구하는 것이 어려울 때, 맨 앞단에서부터 순차적으로 ug$\times$lg를 진행하는 것이다.
이때 주의할 점은 local gradient에서 대입할 변수를 헷갈리지 말아야 하며, 맨 앞단의 upstream gradient는 1이라는 점이다.
따라서 전체적인 학습과정을 보면, feedforward(순전파) 과정에서 input layer, hidden layers, output layer를 거쳐 출력한 예측치와 실제 target 값의 오차가 발생하면 이를 다시 backpropagation(역전파) 과정에서 output layer부터 input layer까지 gradients를 구하면서 parameters를 update하는 것이다.
Cost Function
cost function은 task 종류에 따라 달라진다. 만약 class가 2개인 binary classification이라면 logistic regression으로 나타낼 수 있으며, BCE(binary cross entropy)를 cost function으로 사용한다. class가 k($\leq$3)개인 multi-class classification이라면 Softmax를 거친 예측치와 one-hot 형태의 target 값을 cross entropy로 비교한다. regression의 경우 outlayer의 node(class 개수)가 1개이며, real value prediction이다. 이때 cost function은 MSE(mean square error)로 나타낸다.
- Logistic Regression : $$J(\theta) = - \frac{1}{m}[\sum^m_{i=1}y^{(i)}logh_\theta(x^{(i)})+(1-y^{(i)})log(1-h_\theta(x^{(i)}))]+\frac{\lambda}{2m}\sum^n_{j=1}\theta^2_j$$
- $ \frac{\lambda}{2m}\sum^n_{j=1}\theta^2_j$ 는 regulation term이다. 항상 0보다 크거나 같으며, $\theta$가 커질수록 $J(\theta)$가 커지고 cost가 커지므로 $\theta$가 커지지 못하도록 하는 penalty 역할을 한다.
- Neural Network : $h_\theta(x) \in \mathbb{R}^K$, $(h_\theta(x))_i=i^{th}$ output $$J(\theta) = -\frac{1}{m}[\sum^m_{i=1}\sum^K_{k=1}y_k^{(i)}log(h_\theta(x^{(i)}))_k+(1-y_k^{(i)})log(1-(h_\theta(x^{(i)}))_k]+\frac{\lambda}{2m}\sum^{L-1}_{l=1}\sum^{s_l}_{i=1}\sum^{s_l+1}_{j=1}(\theta_{ji}^{(l)})^2$$
- $ \frac{\lambda}{2m}\sum^{L-1}_{l=1}\sum^{s_l}_{i=1}\sum^{s_l+1}_{j=1}(\theta_{ji}^{(l)})^2$는 regulation term이다. 또한, $ \sum^K_{k=1}$은 k개의 output units을 다루기 위함이다.
여기서 notation을 알아보자. $m$은 batch size로, unit이 아닌 input의 총 개수 즉, feature의 차원이다. batch는 데이터를 한번에 업데이트하는 단위를 말한다. $l$은 layer의 총 개수이다. $s_l$은 l번째 layer에서 bias unit을 제외한 units의 총 개수이다.
cost function이 최소가 되도록 하는 parameter 즉, ${\underset{\theta}{min}} J(\theta)$를 찾아야 한다. 이를 위해서는 $J(\theta)$와 $\frac{\partial J(\theta)}{\partial \theta_{ij}^{(l)}}$를 알아야 한다.
Example: Backpropagation Algorithm for NN
$$\begin{bmatrix}\hat{y_{1}} \\ \hat{y_{2}} \\ \hat{y_{3}}\\ \end{bmatrix} = \begin{bmatrix}x_1^{(1)} & x_2^{(1)} \\x_1^{(2)} & x_2^{(2)} \\x_1^{(3)} & x_2^{(3)} \\ \end{bmatrix} \begin{bmatrix}W_{11}^{(1)} & W_{12}^{(1)} & W_{13}^{(1)} \\ W_{21}^{(1)} & W_{22}^{(1)} & W_{23}^{(1)}\\ \end{bmatrix}\begin{bmatrix}W_{11}^{(2)} \\ W_{21}^{(2)} \\ W_{31}^{(2)} \\ \end{bmatrix}$$
(sample수 $\times$ output units 수)
= (sample수 $\times$ input units 수) $\cdot$ (input units 수 $\times$ hidden units 수) $\cdot$ (hidden units 수 $\times$ output units 수)
Forward Propagation
$$a^{(1)}=x$$
$$z^{(2)}=\theta^{(1)}a^{(1)}$$
$$a^{(2)}=g(z^{(2)}) (add a_0^{(2)})$$
$$z^{(3)}=\theta^{(2)}a^{(2)}$$
$$a^{(3)}=g(z^{(3)}) = h_\theta(x) =\hat{y} $$
(regression에서는 $\hat{y}=z^{(3)}$이다)
Backpropagation
weight의 size는 앞서 언급했던 것과 같이 j번째 layer와 j+1번째 layer 사이의 weight에 대해 $s_j\times s_{j+1}$의 크기를 갖는다. 그러므로 이 예제에서 $W^{(1)}$의 size는 $2\times 3$이고 $W^{(2)}$의 size는 $3\times 1$이다.
cost function을 MSE(mean square error)로 정의하면 $J(cost)=\sum\frac{1}{2}(y-\hat{y})^2$으로 나타낼 수 있다. 이에 따른 gradient를 구해보자.
$\frac{\partial J}{\partial W^{(2)}}=\frac{\partial \sum\frac{1}{2}(y-\hat{y})^2}{\partial W^{(2)}} $$= \sum \frac{\partial \frac{1}{2}(y-\hat{y})^2}{\partial W^{(2)}} $$= -(y-\hat{y})\frac{\partial \hat{y}}{\partial W^{(2)}}$$=-(y-\hat{y})\frac{\partial \hat{y}}{\partial z^{(3)}}\frac{\partial z^{(3)}}{\partial W^{(2)}}$$= -(y-\hat{y})g'(z^{(3)})a^{(2)} $
이때, $ -(y-\hat{y})g'(z^{(3)})$을 backpropagating error 라고 하며 $\delta^{(3)}$으로 표시한다. 이를 대입하면 $W^{(2)}$에 대한 backpropagation 즉, upstream gradient 를 구할 수 있다. $$\frac{\partial J}{\partial W^{(2)}}= (a^{(2)})^T \delta^{(3)} $$ 이를 바탕으로 $W^{(1)}$에 대한 backpropagation 즉, local gradient를 구해보자. $\frac{\partial J}{\partial W^{(1)}}$$=\frac{\partial \frac{1}{2}(y-\hat{y})^2}{\partial W^{(1)}}$$= -(y-\hat{y})\frac{\partial \hat{y}}{\partial W^{(1)}}$ $= -(y-\hat{y})\frac{\partial \hat{y}}{\partial z^{(3)}}\frac{\partial z^{(3)}}{\partial W^{(1)}}$$= -(y-\hat{y})g'(z^{(3)})\frac{\partial z^{(3)}}{\partial W^{(1)}}$ $=\delta^{(3)} \frac{\partial z^{(3)}}{\partial W^{(1)}}$ $= \delta^{(3)} \frac{\partial z^{(3)}}{\partial a^{(2)}}\frac{\partial a^{(2)}}{\partial W^{(1)}}$$ = \delta^{(3)} (W^{(2)})^T\frac{\partial a^{(2)}}{\partial W^{(1)}}$$= \delta^{(3)} (W^{(2)})^T g'(z^{(2)})a^{(1)}$$=\delta^{(3)}(W^{(2)})^Tg'(z^{(2)})X^T$$=\delta^{(2)}X^T$
정리해보면 아래와 같다.
$$\frac{\partial J}{\partial W^{(2)}}=(a^{(2)})^T\delta^{(3)}$$ $$\delta^{(3)}=-(y-\hat{y})g'(z^{(3)})$$
$$\frac{\partial J}{\partial W^{(1)}}=\delta^{(2)}X^T$$ $$\delta^{(2)}=\delta^{(3)}(W^{(2)})^Tg'(z^{(2)})$$
그렇다면 초기값은 어떻게 설정해야 할까? 모든 parameters 값을 0으로 초기화하면? 모든 bias는 0으로 초기화해도 되지만 모든 weights를 0으로 초기화하면 같은 layer에서 activation 값이 같아지면서 hidden units이 의미가 없어진다. 이는 linear model보다 더 안좋을 수 있다. 그의 해결책으로 랜덤으로 초기화한다. 그냥 아예 랜덤으로 초기화할 수도 있지만 이미 잘 사용하고 있는 pretrend model의 weight를 가져와서 초기화하는 방법이 많이 쓰인다.
Non-Linearity Function
만약 deep neural network에서 linear function을 activation function으로 사용한다면? 여러 hidden layer를 거쳐도 input data에 대한 linear function이다. 그렇다면 hidden layer 수를 늘려 multi-layer perceptron을 사용하는 의미가 없어진다. 따라서 multi-layer perceptron에서 activation function은 nonlinear function을 사용해야한다. nonlinear function 중 자주 사용되는 함수들의 종류와 장단점을 알아보자.
- Sigmoid function
- 장점 : neuron의 mechanism과 유사하다.
- 단점 : vanishing gradient 문제가 발생한다.
- Tanh function
- 장점 : 빠르게 optimization이 이루어진다.
- 단점 : vanishing gradient 문제가 발생한다.
- ReLU
- 장점 : 빠르게 수렴하고 exponential function을 사용하지 않아도 되며, vanishing gradient 문제가 발생하지 않는다.
- 단점 : negative 방향의 weight(neuron)은 그냥 죽여버리므로 사용할 수 없다. 이를 해결하기 위해 leaky ReLU도 등장하였다.
[출처] 한양대학교 장준혁 교수님 인공지능개론 수업
'인공지능' 카테고리의 다른 글
[인공지능개론] CNN① (0) | 2024.05.08 |
---|---|
[인공지능개론] Regularization (0) | 2024.05.08 |
[인공지능개론] Neural Networks① (0) | 2024.05.07 |
[인공지능개론] Regression④ (0) | 2024.05.07 |
[인공지능개론] Regression③ (0) | 2024.05.06 |
댓글