Bag-of-Words

Posted on Mar 29, 2023

Bag-of-Words

  • 단어를 분류하여 Bayes’ Rule를 이용해 문서의 특징을 알아내는것이다.

단계

  1. 문장을 단어별로 구분한다.
    • 다음과 같은 문장이 있다 하자.
    • “John really really loves this movie”, “Jane really likes this song”
    • 이때 두 문장에서 단어만 뽑게되면 다음과 같다.
    • {“John” “really” “loves” “this” “movie” “Jane” “likes” “song”}
  2. 단어들을 one-hot vetor로 변환한다.
    • 가령, John은 [1 0 0 0 0 0 0 0], Jane은 [0 0 0 0 0 1 0 0]으로 변환한다.
    • 이때 각 단어는 거리는 $\sqrt 2$, 유사도는 0인 모두 동일한 조건을 가지고 있다.
    • 이렇게 변환된 단어들을 이용해 이전의 문장을 변환하면 다음과 같다.
      • Sentence 1: [1 2 1 1 1 0 0 0]
      • Sentence 2: [0 1 0 1 0 1 1 1]
  3. 이를 이용하여 NaiveBayes Classification을 해보자.

응용

  • 먼저 Bayes’ Rule에 대해 보고 가자. 아래의 식에서 d는 document, c는 class이다.

$$ c_{MAP}=\argmax_{c\in C}P(c|d) $$

$$ =\argmax_{c\in C}\frac{P(d|c)P(c)}{P(d)} $$

$$ =\argmax_{c\in C}P(d|c)P(c) $$

  • 즉 문서가 들어왔을 때 문서가 해당할수 있는 가능성이 가장 큰 class를 찾는것이다.
  • 이를 조금 더 뜯어서 생각하게 되면 다음과 같다.

$$ P(d|c)P(c)=P(w_1, w_2, …, w_n|c)P(c) \rightarrow P(c)\Pi_{w_{i\in W}}P(w_i|c) $$

예시

  • 다음과 같은 문서들이 있다 하자.
    구분Doc IDDocumentClass
    Train1Image recognition uses convolutional neural networksCV
    2Transformer can be used for image classification taskCV
    3Language modeling uses transformerNLP
    4Document classification task is language taskNLP
    Test5Classification task uses transformer?
  • 이때 각각의 확률은 $P(c_{CV})=\frac24=\frac12$, $P(c_{NLP})=\frac24=\frac12$ 이다.
  • 각 단어별 확률은 다음과 같다.
    WordProbWordProb
    classification in CV1/14classification in NLP1/10
    task in CV1/14task in NLP2/10
    uses in CV1/14uses in NLP1/10
    transformer in CV1/14transformer in NLP1/10
  • 위의 계산된 결과를 이용하면 다음과 같다.

$$ P(c_{CV}|d_5)=\frac12 \times \frac1{14} \times \frac1{14} \times\frac1{14} \times \frac1{14} $$

$$ P(c_{NLP}|d_5)=\frac12 \times \frac1{10} \times \frac2{10} \times\frac1{10} \times \frac1{10} $$

  • 결론적으로 NLP에 해당하는 문서이다.