ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [부캠] NLP #1
    AI 부캠 2021. 2. 15. 15:55
    • NLP
    • Trends of NLP
    • Naiive Bayes classifier
    • Word embedding

    NLP(Natural Langauage Processing) 

    Low-level parsing

    • Tokenize : 데이터를 최소 의미 단의로 나누는 과정 (최소 의미란, tokenizer에 따라 다르다.)
    • Stemming : 동사, 형용사와 같은 용언에서 문장에 쓰일 때 형태가 변하지 않는 부분을 추출
    def make_tokenized(data):
      tokenized = []
      for sent in tqdm(data):
        tokens = tokenizer.morphs(sent, stem=True) #tokenize with stemming
        tokenized.append(tokens)
    
      return tokenized
      
      
      train_tokenized = make_tokenized(["정말 맛있습니다. 추천합니다."])
    #[['정말', '맛있다', '.', '추천', '하다', '.']]
    
    
    • Lemmetiztion : 단어들의 원형을 사용
    from konlpy.tag import Komoran
    
    def lemmatize(word):
        morphtags = komoran.pos(word)
        if morphtags[0][1] == 'VA' or morphtags[0][1] == 'VV':
            return morphtags[0][0] + '다'
            
    lemmatize('했다')
    #하다
    

     

     

    Word and phrase level

    Named Entity Recognition (NER) : 고유 명사를 인식하는 task

    Part of Speech (POS) tagging : word들의 품사가 무엇인지 구분

     

    Sentence Level

    Sentimental analysis

    Machine translation

     

    Multi sentence and paragraph level

    Entailment prediction : 문장들간의 관계성을 파악

    Question answering

     

    Trends of NLP

    Word embedding

    word를 vector로 표현하는 방법

    ex) Word2Vec, Glove

     

    RNN family models

    RNN, LSTM, GRU 등의 recurrent input 을 이용한 모델

     

    Attention modules & transformer model

    attention model을 활용한 모델

    ex) BERT, GPT-3

    Naiive Bayes Classifier (BOW)

    naiive bayes classifier

    • bayse rule

    • naive bayse 

    data의 모든 feature 가 서로 독립적이라고 가정한다.

     

    bag of words example ( naiive bayes classifier)

    bag of words

    단어들의 순서는 전혀 고려하지 않고, 단어들의 출현 빈도(frequency)에만 집중하는 텍스트 데이터의 수치화 표현 방법

    특징

    1. 문장간 cosine similarity가 0

    2. 문장간 거리는 sqrt(2)

     

    bag of words using naiive bayse classifier

    2개의 class CV, NLP에 속하는 4개의 train 문장이 있다고 하자.

     

     

    그때, "Classification task uses transformer"가 어느 class에 속하는지 naiive bayse classifier로 구할 수 있다.

    다음과 같이 구하면, Classification task uses transformer 문장은 NLP에 속한다.

    Word Embedding

    word2vec

    word2vec

    단어의 ‘의미’를 다차원 공간에 벡터화하는 방법 중 하나

    이러한 방법을 통해 단어간의 유사성을 파악할 수 있다.

    CBOW

    주변에 있는 단어들을 가지고, 중간에 있는 단어들을 예측하는 방법

    예를들어, 윈도우 크기를 2라한다면, 중심단어 앞/뒤로 2개씩 4개가 인풋으로 사용된다.

    (단, 없으면 pass)

    출처 ㅣ 딥러닝을 이용한 자연어 처리 입문

    주변 단어들의 원-핫 벡터에 대해 가중치 W가 곱해서 생길 결과를 구하고, 이 벡터들의 평균을 구한다.

    그 값을 통해 중심단어를 예측하는 방향으로 W를 학습시킨다.

    Loss function은  Softmax error 즉, cross entropy error를 사용한다.

     

    class CBOW(nn.Module):
      def __init__(self, vocab_size, dim):
        super(CBOW, self).__init__()
        self.embedding = nn.Embedding(vocab_size, dim, sparse=True)
        self.linear = nn.Linear(dim, vocab_size)
    
      # B: batch size, W: window size, d_w: word embedding size, V: vocab size
      def forward(self, x):  # x: (B, 2W)
        embeddings = self.embedding(x)  # (B, 2W, d_w)
        embeddings = torch.mean(embeddings, dim=1)  # (B, d_w)##이걸 더하고 평균.
        output = self.linear(embeddings)  # (B, V)
        return output

     

    Skip gram

    CBOW와 다르게 중심단어를 통해서 주변단어를 예측하는 방식이다.

    신경망을 도식화해보면 다음과 같다.

     

    class SkipGram(nn.Module):
      def __init__(self, vocab_size, dim):
        super(SkipGram, self).__init__()
        self.embedding = nn.Embedding(vocab_size, dim, sparse=True)
        self.linear = nn.Linear(dim, vocab_size)
    
      # B: batch size, W: window size, d_w: word embedding size, V: vocab size
      def forward(self, x): # x: (B)
        embeddings = self.embedding(x)  # (B, d_w)
        output = self.linear(embeddings)  # (B, V)
        return output

    전반적으로 Skip-gram이 CBOW보다 성능이 좋다고 알려져 있다.

     

    GloVe

    [ratsgo 님의 블로그를 요약한 내용]

    GloVe는 2014년도에 개발된 워드 임베딩 기법으로 word2vec의 문장내 한정된 정보로만 임베딩이 되는 방식을 개선시켰다.

     

    즉, GloVe는 임베딩된 단어벡터 간 유사도 측정을 수월하게 하면서도 말뭉치 전체의 통계 정보를 좀 더 잘 반영해보고자 한것이다.

    이를 위해 GloVe 연구팀은 임베딩된 두 단어벡터의 내적이 말뭉치 전체에서의 동시 등장확률 로그값이 되도록 목적함수를 정의했다.

     

     


    오늘은 NLP의 전반적인 내용과 word embedding에 대해 배웠다.

     

    word2vec.kr/search/?query=%EC%97%AC%EC%99%95-%EC%97%AC%EC%9E%90%2B%EB%82%A8%EC%9E%90

     

    Korean Word2Vec

    QUERY +여왕/Noun +남자/Noun -여자/Noun RESULT 왕/Noun

    word2vec.kr

    wikidocs.net/22660

     

    위키독스

    온라인 책을 제작 공유하는 플랫폼 서비스

    wikidocs.net

    ratsgo.github.io/from%20frequency%20to%20semantics/2017/04/09/glove/

     

    GloVe를 이해해보자! · ratsgo's blog

    이번 포스팅에서는 미국 스탠포드대학에서 2014년 개발한 워드 임베딩 방법론인 GloVe에 대해 알아보도록 하겠습니다. 이번 글은 고려대 강필성 교수님 강의를 참고로 했는데요. 저도 완벽히 이해

    ratsgo.github.io

     

    'AI 부캠' 카테고리의 다른 글

    [부캠] NLP03  (0) 2021.02.17
    [부캠]NLP2  (0) 2021.02.16
    [부캠]Genreative model  (0) 2021.02.13
    [부캠] Sequential model  (0) 2021.02.05
    [부캠] CNN 파헤치기  (0) 2021.02.04
Designed by Tistory.