코사인 유사도

R로 배우는 자연어 처리 입문

Kasey Jones

Research Data Scientist

TF‑IDF 출력

# A tibble: 1,498 x 6
       X word         n     tf   idf tf_idf
   <int> <chr>    <int>  <dbl> <dbl>  <dbl>
 1    20 january      4 0.0930  2.30  0.214
 2    15 power        4 0.0690  3.00  0.207
 3    19 futures      9 0.0643  3.00  0.193
 4     8 8            6 0.0619  3.00  0.185
 5     3 canada       2 0.0526  3.00  0.158
 6     3 canadian     2 0.0526  3.00  0.158
R로 배우는 자연어 처리 입문

코사인 유사도

  • 두 벡터 간 유사도 지표
  • 두 벡터가 이루는 각도로 측정

코사인 유사도는 두 벡터가 이루는 각도로 측정합니다. 두 직선이 만드는 각으로 상상해 보세요.

1 https://en.wikipedia.org/wiki/Cosine_similarity
R로 배우는 자연어 처리 입문

코사인 유사도 공식

  • 유사도는 두 벡터의 내적으로 계산합니다

두 벡터의 내적을 계산하면 유사도를 알 수 있습니다.

R로 배우는 자연어 처리 입문

유사도 찾기 I

crude_weights <- crude_tibble %>%
  unnest_tokens(output = "word", token = "words", input = text) %>%
  anti_join(stop_words) %>%
  count(word, X) %>%
  bind_tf_idf(word, X, n)
# A tibble: 1,498 x 6
       X word          n    tf   idf tf_idf
   <int> <chr>     <int> <dbl> <dbl>  <dbl>
 1     1 1.50          1 0.25   3.25  0.812
 2     1 16.00         1 1      3.25  3.25 
 3     1 barrel        2 0.133  3.25  0.433
 ...
R로 배우는 자연어 처리 입문

쌍별 유사도

pairwise_similarity(tbl, item, feature, value, ...)
  • tbl: 테이블 또는 티블
  • item: 비교할 항목(기사, 트윗 등)
  • feature: 항목 간 연결을 나타내는 열(예: 단어)
  • value: 값 열(예: n 또는 tf_idf)
R로 배우는 자연어 처리 입문

유사도 찾기 II

crude_weights %>%
  pairwise_similarity(X, word, tf_idf) %>%
  arrange(desc(similarity))
# A tibble: 380 x 3
   item1 item2 similarity
   <int> <int>      <dbl>
 1    17    16      0.663
 2    16    17      0.663
 3    13    10      0.311
 4    10    13      0.311
 ...
R로 배우는 자연어 처리 입문

코사인 유사도 활용 사례

  • 중복/유사한 텍스트 찾기
  • 클러스터링·분류 분석에 활용
  • ...
R로 배우는 자연어 처리 입문

연습해 봅시다!

R로 배우는 자연어 처리 입문

Preparing Video For Download...