R로 태국 음식 텍스트 마이닝

26496 단어 datasciencetextminingr
이것은 태국 음식 요리 시리즈의 3부입니다.

텍스트 마이닝



가장 인기 있는 원료는 무엇입니까?



이 질문에 대답하는 한 가지 방법은 텍스트 마이닝을 사용하여 두 단어 중 하나로 토큰화하고 빈도별로 단어를 인기 척도로 계산하는 것입니다.

아래 막대 차트에서 모든 태국 요리의 단어 빈도를 볼 수 있습니다. 태국어로 돼지고기를 의미하는 Mu(หมู)는 모든 요리 유형과 하위 그룹에서 가장 자주 나타납니다. 다음으로 카레를 의미하는 kaeng(แกง)이 있습니다. Phat (ผัด)은 "볶음"이 인기 있는 요리 모드임을 시사하며 3위를 차지했습니다.

모든 단어가 원자재를 가리키는 것은 아니므로 이 질문에 직접 답할 수 없을 수도 있습니다.



library(tidytext)
library(scales)

# new csv file after data cleaning (see above)
df <- read_csv("../web_scraping/edit_thai_dishes.csv")

df %>%
    select(Thai_name, Thai_script) %>%
    # can substitute 'word' for ngrams, sentences, lines
    unnest_tokens(ngrams, Thai_name) %>%  
    # to reference thai spelling: group_by(Thai_script)
    group_by(ngrams) %>%  
    tally(sort = TRUE) %>%  # alt: count(sort = TRUE)
    filter(n > 9) %>%
# visualize
# pipe directly into ggplot2, because using tidytools
    ggplot(aes(x = n, y = reorder(ngrams, n))) + 
    geom_col(aes(fill = ngrams)) +
    scale_fill_manual(values = c(
        "#c3d66b",
        "#70290a",
        "#2f1c0b",
        "#ba9d8f",
        "#dda37b",
        "#8f5e23",
        "#96b224",
        "#dbcac9",
        "#626817",
        "#a67e5f",
        "#be7825",
        "#446206",
        "#c8910b",
        "#88821b",
        "#313d5f",
        "#73869a",
        "#6f370f",
        "#c0580d",
        "#e0d639",
        "#c9d0ce",
        "#ebf1f0",
        "#50607b"
    )) +
    theme_minimal() +
    theme(legend.position = "none") +
    labs(
        x = "Frequency",
        y = "Words",
        title = "Frequency of Words in Thai Cuisine",
        subtitle = "Words appearing at least 10 times in Individual or Shared Dishes",
        caption = "Data: Wikipedia | Graphic: @paulapivat"
    )


개별 및 공유 요리 모두에 공통된 단어도 볼 수 있습니다. nuea(쇠고기), phrik(칠리), kaphrao(바질 잎)과 같은 다른 단어도 볼 수 있습니다.



# frequency for Thai_dishes (Major Grouping) ----

# comparing Individual and Shared Dishes (Major Grouping)
thai_name_freq <- df %>%
    select(Thai_name, Thai_script, major_grouping) %>%
    unnest_tokens(ngrams, Thai_name) %>% 
    count(ngrams, major_grouping) %>%
    group_by(major_grouping) %>%
    mutate(proportion = n / sum(n)) %>%
    select(major_grouping, ngrams, proportion) %>%
    spread(major_grouping, proportion) %>%
    gather(major_grouping, proportion, c(`Shared dishes`)) %>%
    select(ngrams, `Individual dishes`, major_grouping, proportion)


# Expect warming message about missing values
ggplot(thai_name_freq, aes(x = proportion, y = `Individual dishes`,
       color = abs(`Individual dishes` - proportion))) +
    geom_abline(color = 'gray40', lty = 2) +
    geom_jitter(alpha = 0.1, size = 2.5, width = 0.3, height = 0.3) +
    geom_text(aes(label = ngrams), check_overlap = TRUE, vjust = 1.5) +
    scale_x_log10(labels = percent_format()) +
    scale_y_log10(labels = percent_format()) +
    scale_color_gradient(limits = c(0, 0.01), 
                         low = "red", high = "blue") +    # low = "darkslategray4", high = "gray75"
    theme_minimal() +
    theme(legend.position = "none",
          legend.text = element_text(angle = 45, hjust = 1)) +
    labs(y = "Individual Dishes",
         x = "Shared Dishes",
         color = NULL,
         title = "Comparing Word Frequencies in the names Thai Dishes",
         subtitle = "Individual and Shared Dishes",
         caption = "Data: Wikipedia | Graphics: @paulapivat")


어떤 원료가 가장 중요합니까?



우리는 빈도에서 많은 것을 배울 수 있기 때문에 텍스트 마이닝 실무자는 단어가 문서 또는 말뭉치에서 얼마나 중요한지를 더 잘 반영하기 위해 용어 빈도 - 역 문서 빈도를 만들었습니다(자세한 내용here ).

다시 말하지만, 이 단어가 반드시 원자재를 가리키는 것은 아니므로 이 질문에 대한 직접적인 답변은 여기에서 할 수 없습니다.



요리 이름만 봐도 태국 음식에 대해 알 수 있나요?



짧은 대답은 "예"입니다.

우리는 빈도와 "단어 빈도 - 역 문서 빈도"에서 가장 빈번한 단어뿐만 아니라 토큰화한 현재 단어 세트 내에서 상대적인 중요성을 배웠습니다tidytext . 이는 인기 있는 원재료(돼지고기)뿐만 아니라 요리 유형(카레) 및 기타 인기 있는 준비 모드(볶음)를 알려줍니다.

단어 사이의 관계 네트워크를 조사할 수도 있습니다. 어두운 화살표는 단어 쌍 사이의 관계가 더 강함을 나타냅니다. 예를 들어 "nam phrik"은 강한 쌍입니다. 이것은 태국어로 "칠리 소스"를 의미하며 다양한 종류의 요리에서 칠리 소스가 중요한 역할을 한다는 것을 암시합니다.

위에서 "mu"(돼지고기)가 자주 등장한다는 것을 배웠습니다. 이제 "mu"와 "krop"이 다른 쌍보다 더 관련이 있음을 알 수 있습니다(참고: "mu krop"은 "바삭한 돼지고기"를 의미함). 우리는 또한 위에서 "카오"가 밥 요리에 자주 등장하는 것을 보았습니다. "카오"가 태국어로 쌀을 의미하므로 이것만으로도 놀라운 일이 아니지만 여기서 "카오 팟"은 볶음밥("카오 팟")이 상당히 인기가 있음을 암시하는 밀접한 관련이 있음을 알 수 있습니다.



# Visualizing a network of Bi-grams with {ggraph} ----
library(igraph)
library(ggraph)
set.seed(2021)

thai_dish_bigram_counts <- df %>%
    select(Thai_name, minor_grouping) %>%
    unnest_tokens(bigram, Thai_name, token = "ngrams", n = 2) %>%
    separate(bigram, c("word1", "word2"), sep = " ") %>%
    count(word1, word2, sort = TRUE)


# filter for relatively common combinations (n > 2)
thai_dish_bigram_graph <- thai_dish_bigram_counts %>%
    filter(n > 2) %>%
    graph_from_data_frame()


# polishing operations to make a better looking graph
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))

set.seed(2021)
ggraph(thai_dish_bigram_graph, layout = "fr") +
    geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
                   arrow = a, end_cap = circle(.07, 'inches')) +
    geom_node_point(color = "dodgerblue", size = 5, alpha = 0.7) +
    geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
    labs(
        title = "Network of Relations between Word Pairs",
        subtitle = "{ggraph}: common nodes in Thai food",
        caption = "Data: Wikipedia | Graphics: @paulapivat"
    ) +
    theme_void()


마지막으로 개별 요리 내 단어 관계에 관심이 있을 수 있습니다.

아래 그래프는 중간에서 높은 상관 관계가 있는 단어 쌍의 네트워크를 보여줍니다. kaeng(카레), pet(매운), wan(달콤한), khiao(그린 카레), phrik(칠리) 및 mu(돼지 고기)와 같은 특정 단어가 상대적으로 어두운 선으로 모여 있는 것을 볼 수 있습니다. 이 단어들은 일반적으로 결합된 재료, 요리 방식 및 설명의 모음을 나타냅니다.



set.seed(2021)

# Individual Dishes
individual_dish_words <- df %>%
    select(major_grouping, Thai_name) %>%
    filter(major_grouping == 'Individual dishes') %>%
    mutate(section = row_number() %/% 10) %>%
    filter(section > 0) %>%
    unnest_tokens(word, Thai_name)  # assume no stop words

individual_dish_cors <- individual_dish_words %>%
    group_by(word) %>% 
    filter(n() >= 2) %>%     # looking for co-occuring words, so must be 2 or greater
    pairwise_cor(word, section, sort = TRUE) 


individual_dish_cors %>%
    filter(correlation < -0.40) %>%
    graph_from_data_frame() %>%
    ggraph(layout = "fr") +
    geom_edge_link(aes(edge_alpha = correlation, size = correlation), show.legend = TRUE) +
    geom_node_point(color = "green", size = 5, alpha = 0.5) +
    geom_node_text(aes(label = name), repel = TRUE) +
    labs(
        title = "Word Pairs in Individual Dishes",
        subtitle = "{ggraph}: Negatively correlated (r = -0.4)",
        caption = "Data: Wikipedia | Graphics: @paulapivat"
    ) +
    theme_void()


요약



Python과 R의 조합을 사용하여 데이터를 스크랩, 정리, 조작 및 시각화하는 탐색 데이터 프로젝트를 완료했습니다. 또한 기본 텍스트 마이닝 작업에 tidytext 패키지를 사용하여 다음을 사용하여 태국 요리에 대한 통찰력을 얻을 수 있는지 확인했습니다. Wikipedia에서 긁어낸 요리 이름의 단어.

데이터 과학, R, Python, SQL 등에 대한 자세한 내용은 .

좋은 웹페이지 즐겨찾기