Biểu diễn túi từ (bag-of-words)

Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Kasey Jones

Research Data Scientist

Ví dụ trước đó

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
 ...
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Biểu diễn túi từ (bag-of-words)

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

Từ duy nhất:

  • few: chỉ trong text1
  • all: chỉ trong text2
  • most: chỉ trong text3
  • words, are, important
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Các biểu diễn vector điển hình

# Chuyển thường, bỏ stop word
word_vector <- c("few", "all", "most", "words", "important")
# Biểu diễn cho text1
text1 <- c("Few words are important.")
text1_vector <- c(1, 0, 0, 1, 1)
# Biểu diễn cho text2
text2 <- c("All words are important.")
text2_vector <- c(0, 1, 0, 1, 1)
# Biểu diễn cho text3
text3 <- c("Most words are important.")
text3_vector <- c(0, 0, 1, 1, 1)
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Biểu diễn 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
...
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Ví dụ một từ

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
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Ma trận thưa

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
...
Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Ma trận thưa (tiếp)

Ma trận thưa

  • 20.000 hàng (tweet)
  • 43.000 cột (từ)
  • 20.000 * 43.000 = 860.000.000
  • Chỉ 177.000 phần tử khác 0. Khoảng 0,02%

Ví dụ ma trận thưa: Ma trận thưa có rất ít phần tử khác 0. Xem ma trận thưa trông như toàn số 0.

Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Luyện BoW

Nhập môn Xử lý Ngôn ngữ Tự nhiên với R

Preparing Video For Download...