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...