Bag-of-Words 表現

Rで学ぶ自然言語処理入門

Kasey Jones

Research Data Scientist

前の例

animal_farm %>%
  unnest_tokens(output = "word", token = "words",
                input = text_column) %>%
  anti_join(stop_words) %>%
  count(word, sort = TRUE)
# A tibble: 3,611 x 2
   word         n
   <chr>    <int>
 1 animals    248
 2 farm       163
 ...
Rで学ぶ自然言語処理入門

Bag-of-Words 表現

text1 <- c("Few words are important.")
text2 <- c("All words are important.")
text3 <- c("Most words are important.")

固有の単語:

  • few: text1 のみに出現
  • all: text2 のみに出現
  • most: text3 のみに出現
  • words, are, important
Rで学ぶ自然言語処理入門

典型的なベクトル表現

# 小文字化、ストップワード除去後
word_vector <- c("few", "all", "most", "words", "important")
# text1 の表現
text1 <- c("Few words are important.")
text1_vector <- c(1, 0, 0, 1, 1)
# text2 の表現
text2 <- c("All words are important.")
text2_vector <- c(0, 1, 0, 1, 1)
# text3 の表現
text3 <- c("Most words are important.")
text3_vector <- c(0, 0, 1, 1, 1)
Rで学ぶ自然言語処理入門

tidytext の表現

words <- animal_farm %>%
    unnest_tokens(output = "word", token = "words", input = text_column) %>%
    anti_join(stop_words) %>%
    count(chapter, word, sort = TRUE)
words
# A tibble: 6,807 x 3
   chapter    word         n
   <chr>      <chr>    <int>
 1 Chapter 8  napoleon    43
 2 Chapter 8  animals     41
 3 Chapter 9  boxer       34
...
Rで学ぶ自然言語処理入門

単語ひとつの例

words %>%
  filter(word == 'napoleon') %>%
  arrange(desc(n))
# A tibble: 9 x 3
  chapter    word         n
  <chr>      <chr>    <int>
1 Chapter 8  napoleon    43
2 Chapter 7  napoleon    24
3 Chapter 5  napoleon    22
...
8 Chapter 3  napoleon     3
9 Chapter 4  napoleon     1
Rで学ぶ自然言語処理入門

スパース行列

library(tidytext); library(dplyr)
russian_tweets <- read.csv("russian_1.csv")
russian_tweets <- as_tibble(russian_tweets)

tidy_tweets <- russian_tweets %>%
  unnest_tokens(word, content) %>%
  anti_join(stop_words)
tidy_tweets %>%
  count(word, sort = TRUE)
# A tibble: 43,666 x 2
...
Rで学ぶ自然言語処理入門

スパース行列(続き)

スパース行列

  • 20,000 行(ツイート)
  • 43,000 列(単語)
  • 20,000 × 43,000 = 860,000,000
  • 非ゼロ要素は 177,000。約 0.02%

スパース行列の例: スパース行列は非ゼロ要素が非常に少ない。表示するとほとんどが 0 に見える。

Rで学ぶ自然言語処理入門

BoW の練習

Rで学ぶ自然言語処理入門

Preparing Video For Download...