TF-IDF

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

Kasey Jones

Research Data Scientist

Bag-of-words의 함정

t1 <- "My name is John. My best friend is Joe. We like tacos."
t2 <- "Two common best friend names are John and Joe."
t3 <- "Tacos are my favorite food. I eat them with my buddy Joe."
clean_t1 <- "john friend joe tacos"
clean_t2 <- "common friend john joe names"
clean_t3 <- "tacos favorite food eat buddy joe"
R로 배우는 자연어 처리 입문

공통 단어 공유

clean_t1 <- "john friend joe tacos"
clean_t2 <- "common friend john joe names"
clean_t3 <- "tacos favorite food eat buddy joe"

t1과 t2 비교

  • t1의 3/4 단어가 t2에 있음
  • t2의 3/5 단어가 t1에 있음

t1과 t3 비교

  • t1의 2/4 단어가 t3에 있음
  • t3의 2/6 단어가 t1에 있음
R로 배우는 자연어 처리 입문

Tacos의 중요성

t1 <- "My name is John. My best friend is Joe. We like tacos."
t2 <- "Two common best friend names are John and Joe."
t3 <- "Tacos are my favorite food. I eat them with my friend Joe."

각 텍스트의 단어:

  • John: t1, t2
  • Joe: t1, t2, t3
  • Tacos: t1, t3
R로 배우는 자연어 처리 입문

TF-IDF

clean_t1 <- "john friend joe tacos"
clean_t2 <- "common friend john joe names"
clean_t3 <- "tacos favorite food eat buddy joe"
  • TF: Term Frequency
    • 한 텍스트에서 해당 용어가 차지하는 비율
    • john은 clean_t1의 1/4, tf = .25
  • IDF: Inverse Document Frequency
    • 전체 문서에서 해당 용어의 흔함에 대한 가중치
    • john은 3/3 문서에 존재, IDF = 0
R로 배우는 자연어 처리 입문

IDF 식

 

$ IDF = log \frac{N}{n_{t}} $

  • N: 말뭉치의 전체 문서 수
  • $n_{t}$: 해당 용어가 나타나는 문서 수

예:

  • Taco IDF: $log (\frac{3}{2}) = .405$
  • Buddy IDF: $log (\frac{3}{1}) = 1.10$
  • John IDF: $log (\frac{3}{3}) = 0$
R로 배우는 자연어 처리 입문

TF + IDF

clean_t1 <- "john friend joe tacos"
clean_t2 <- "common friend john joe names"
clean_t3 <- "tacos favorite food eat buddy joe"

"tacos"의 TF-IDF:

  • clean_t1: TF * IDF = (1/4) * (.405) = 0.101
  • clean_t2: TF * IDF = (0/4) * (.405) = 0
  • clean_t3: TF * IDF = (1/6) * (.405) = 0.068
R로 배우는 자연어 처리 입문

TF-IDF 행렬 계산

# Create a data.frame
df <- data.frame('text' = c(t1, t2, t3), 'ID' = c(1, 2, 3))
df %>%
  unnest_tokens(output = "word", token = "words", input = text) %>%
  anti_join(stop_words) %>%
  count(ID, word, sort = TRUE) %>%
  bind_tf_idf(word, ID, n)
  • word: 용어가 있는 열
  • ID: 문서 ID가 있는 열
  • n: count()가 만든 단어 수
R로 배우는 자연어 처리 입문

bind_tf_idf 출력

# A tibble: 15 x 6
       X word         n    tf   idf tf_idf
   <dbl> <chr>    <int> <dbl> <dbl>  <dbl>
 1     1 friend       1 0.25  0.405 0.101 
 2     1 joe          1 0.25  0     0     
 3     1 john         1 0.25  0.405 0.101 
 4     1 tacos        1 0.25  0.405 0.101 
 5     2 common       1 0.2   1.10  0.220 
 6     2 friend       1 0.2   0.405 0.0811
 ...
R로 배우는 자연어 처리 입문

TF-IDF 연습

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

Preparing Video For Download...