RNN에 대해 잘 설명한 블로그 글 1 : The Unreasonable Effectiveness of Recurrent Neural Networks by Andrej Karpathy (Andrej Karpathy의 깃헙)

RNN에 대해 잘 설명한 블로그 글 2 : Understanding LSTM Networks by colah's blog


RNN이란? 

RNN (Recurrent Neural Network, 순환신경망)은 CNN과 더불어 대표적인 딥러닝 알고리즘으로, 연속된 형태 (sequence type) 데이터를 다루기 유용하다. 예를 들어, 행간에 맥락이 존재하는 텍스트 데이터를 다룰 때 유용한 것! 

CNN과의 비교 : CNN은 정해진 크기(fixed-sized)의 벡터를 인풋으로 받아 정해진 크기의 벡터를 아웃풋으로 돌려주는 제한점을 갖고 있다. 즉 이미지처럼 크기가 고정된 데이터를 다루기에 적합하다. 게다가 모델에 사용된 레이어의 수만큼 정해진 step만 계산할 수 있다. 반면,  RNN에서는 연속형 벡터를 입력값(input) 및 출력값(output)으로 사용할 수 있다. 


source : The Unreasonable Effectiveness of Recurrent Neural Networks by Andrej Karpathy


위 그림에 대한 Andrej Karpathy의 설명 : Each rectangle is a vector and arrows represent functions (e.g. matrix multiply). Input vectors are in red, output vectors are in blue and green vectors hold the RNN's state (more on this soon). From left to right: (1) Vanilla mode of processing without RNN, from fixed-sized input to fixed-sized output (e.g. image classification). (2) Sequence output (e.g. image captioning takes an image and outputs a sentence of words). (3) Sequence input (e.g. sentiment analysis where a given sentence is classified as expressing positive or negative sentiment). (4) Sequence input and sequence output (e.g. Machine Translation: an RNN reads a sentence in English and then outputs a sentence in French). (5) Synced sequence input and output (e.g. video classification where we wish to label each frame of the video). Notice that in every case are no pre-specified constraints on the lengths sequences because the recurrent transformation (green) is fixed and can be applied as many times as we like.

(1) one to one은 고정된 크기의 인풋을 받아 순환적인 부분 없이 고정된 크기의 아웃풋을 뱉기 때문에 RNN 알고리즘이 아니다. 

(2) one to many는 고정된 크기의 인풋을 받아서 순환 과정을 거쳐 시퀀스를 출력한다. 이미지를 입력해서 이미지에 대한 설명을 문장으로 출력하는 이미지 캡션 생성 같은 태스크다. 

(3) many to one은 시퀀스를 입력해 순환 과정을 거쳐 크기가 고정된 아웃풋을 출력한다. 문장이 입력됐을 때 긍정 혹은 부정으로 나누는 감성 분석기가 여기에 해당한다. 

(4) many to many는 시퀀스를 입력받아 순환 과정을 거쳐 시퀀스를 출력한다. 예) 한 --> 영 자동 번역기 

(5) 마지막 many to many는 동기화된 시퀀스를 입력받아 순환 과정을 거쳐 시퀀스를 출력한다. 예) 문장에서 다음에 나올 단어를 예측하는 언어 모델 


How RNN works


source : colah's blog

RNN은 어떻게 작동할까. Recurrent Neural Networks 라는 이름 그대로 작동한다. 즉, RNN은 루프를 도는데, 이를 도식화 하면 위와 같고 루프를 풀어서 표현하면 아래 그림과 같다.


source : colah's blog



 

RNN computation. So how do these things work? At the core, RNNs have a deceptively simple API: They accept an input vector x and give you an output vector y. However, crucially this output vector’s contents are influenced not only by the input you just fed in, but also on the entire history of inputs you’ve fed in in the past. (source : The Unreasonable Effectiveness of Recurrent Neural Networks by Andrej Karpathy)


RNN이 많이 사용되는 텍스트 데이터 분석을 예로 설명해보자.

"I am happy."라는 문장이 있다고 하자. 이 문장을 토크나이징 전처리를 거쳐 100차원 벡터로 변환한 임베딩 정보는 다음과 같다. 

(임베딩 : 텍스트를 토큰화하고, 각 토큰을 연속 벡터 공간(Continuous vector space)에 투영하는 것)


RNN에 각 단어의 임베딩 정보가 순차적으로 입력된다.


source : colah's blog

이 그림에서 다시 보자면, 'I'의 임베딩 정보들이 X0, 'am'의 임베딩 정보가 X1, 'happy'의 임베딩 정보가 X2에 들어가는 식이다. 

한 번 더 자세히 줌인하면, 첫 번째로 입력된 'I'의 100차원 벡터는 RNN 네트워크를 다음과 같이 거친다. 


source : 갓상엽 쌤


보면 알겠지만, 100차원 벡터를 구성하는 원소들이 차례로 node에 입력돼 RNN 레이어를 거친다. 입력층에 있는 노드의 수는 문장의 길이에 따라 달라지겠지만 (? 맞나? 확인 필요), 은닉층인 RNN 레이어에 있는 노드의 수는 하이퍼 파라미터다. 



source : 갓상엽 쌤


RNN을 이용한 텍스트 분석 1 - 언어모델 

RNN은 언어모델(language model)에 적합하다.



 여러 개의 단어들이 동시에 출현할 확률이나 단어들이 주어질 때 그 다음 나올 단어가 무엇인지를 예측하는데 사용되는 것. (give RNN a huge chunk of text and ask it to model the probability distribution of the next character in the sequence given a sequence of previous characters. This will then allow us to generate new text one character at a time.) 


출처: <한국어 임베딩>


다른 워드 임베딩 방법들과 RNN 기반 언어모델의 차이를 알아보자. 

Bag of Words 방법으로 임베딩을 하면, 단순히 단어들의 출현 빈도만을 고려해 단어들간 행간을 읽지 못한다. word2vec 방법은 말뭉치에서 어떤 단어가 함께 쓰였는지까지 반영해 임베딩하지만, 단어들의 순서를 고려할 수 없다는 단점이 있다. word2vec으로 'The movie was not fun' 과 같은 문장에 대한 감성분석을 하면, fun이라는 단어 앞에 'not'이 있어 '재미 없다'는 문맥이라는 것을 읽어내지 못하는 것. RNN 기반 언어모델은 단어의 순서를 반영해 워드 임베딩을 하기 때문에, 이 문제를 해결할 수 있다. 

특히 bi-directional RNN을 사용하면,