library(data.table)
library(ggplot2)
library(dplyr)
library(jiebaR)
library(tidytext)
library(stringr)
library(tm)
library(topicmodels)
library(purrr)
library(ggpubr)
require(RColorBrewer)
library(reshape2)
library(tidyr)
library(readr)
library(scales)
require(jiebaR)
library(plotly)
library(googleVis)
library(highcharter)
mycolors <- colorRampPalette(brewer.pal(8, "Set3"))(20)
metadata <- fread("chen_articleMetaData.csv", encoding = "UTF-8")
metadata %>%
mutate(artDate = as.Date(artDate)) %>%
group_by(artDate) %>%
summarise(count = n())%>%
ggplot(aes(artDate,count))+
geom_line(color="royalblue")+
geom_point()->post_plot
ggplotly(post_plot)
#Ch1. Document Term Matrix (DTM)
使用默認參數初始化一個斷詞引擎
jieba_tokenizer = worker()
news_tokenizer <- function(t) {
lapply(t, function(x) {
if(nchar(x)>1){
tokens <- segment(x, jieba_tokenizer)
# 去掉字串長度爲1的詞彙
tokens <- tokens[nchar(tokens)>1]
return(tokens)
}
})
}
計算每篇文章各token出現次數
tokens <- metadata %>%
unnest_tokens(word, sentence, token=news_tokenizer) %>%
filter(!str_detect(word, regex("[0-9a-zA-Z]"))) %>%
count(artUrl, word) %>%
rename(count=n)
tokens %>% head(20)
dtm <-tokens %>% cast_dtm(artUrl, word, count)
dtm
## <<DocumentTermMatrix (documents: 5181, terms: 51348)>>
## Non-/sparse entries: 580522/265453466
## Sparsity : 100%
## Maximal term length: 9
## Weighting : term frequency (tf)
inspect(dtm[1:10,1:10])
## <<DocumentTermMatrix (documents: 10, terms: 10)>>
## Non-/sparse entries: 26/74
## Sparsity : 74%
## Maximal term length: 2
## Weighting : term frequency (tf)
## Sample :
## Terms
## Docs 一下 一出 一定 一個
## https://www.ptt.cc/bbs/Gossiping/M.1580201716.A.D4A.html 1 1 1 1
## https://www.ptt.cc/bbs/Gossiping/M.1580218136.A.251.html 1 0 1 0
## https://www.ptt.cc/bbs/Gossiping/M.1580228124.A.03A.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580473375.A.390.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580473872.A.066.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580621894.A.4DE.html 0 0 1 0
## https://www.ptt.cc/bbs/Gossiping/M.1580632630.A.857.html 0 0 1 0
## https://www.ptt.cc/bbs/Gossiping/M.1580637593.A.E42.html 0 0 0 3
## https://www.ptt.cc/bbs/Gossiping/M.1580638519.A.26D.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580641092.A.CD8.html 0 0 0 0
## Terms
## Docs 人口 人物 上午 口罩
## https://www.ptt.cc/bbs/Gossiping/M.1580201716.A.D4A.html 1 2 1 10
## https://www.ptt.cc/bbs/Gossiping/M.1580218136.A.251.html 0 2 0 10
## https://www.ptt.cc/bbs/Gossiping/M.1580228124.A.03A.html 0 0 0 10
## https://www.ptt.cc/bbs/Gossiping/M.1580473375.A.390.html 0 0 0 1
## https://www.ptt.cc/bbs/Gossiping/M.1580473872.A.066.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580621894.A.4DE.html 0 0 0 16
## https://www.ptt.cc/bbs/Gossiping/M.1580632630.A.857.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580637593.A.E42.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580638519.A.26D.html 0 0 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580641092.A.CD8.html 0 0 0 0
## Terms
## Docs 大家 工作
## https://www.ptt.cc/bbs/Gossiping/M.1580201716.A.D4A.html 5 1
## https://www.ptt.cc/bbs/Gossiping/M.1580218136.A.251.html 1 0
## https://www.ptt.cc/bbs/Gossiping/M.1580228124.A.03A.html 0 1
## https://www.ptt.cc/bbs/Gossiping/M.1580473375.A.390.html 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580473872.A.066.html 1 0
## https://www.ptt.cc/bbs/Gossiping/M.1580621894.A.4DE.html 2 1
## https://www.ptt.cc/bbs/Gossiping/M.1580632630.A.857.html 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580637593.A.E42.html 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580638519.A.26D.html 0 0
## https://www.ptt.cc/bbs/Gossiping/M.1580641092.A.CD8.html 1 0
lda <- LDA(dtm, k = 2, control = list(seed = 2021))
# lda <- LDA(dtm, k = 2, control = list(seed = 2021,alpha = 2,delta=0.1),method = "Gibbs") #調整alpha即delta
lda
## A LDA_VEM topic model with 2 topics.
topics_words <- tidy(lda, matrix = "beta") # 注意,在tidy function裡面要使用"beta"來取出Phi矩陣。
colnames(topics_words) <- c("topic", "term", "phi")
topics_words
terms依照各主題的phi值由大到小排序,列出前10大
topics_words %>%
group_by(topic) %>%
top_n(10, phi) %>%
ungroup() %>%
mutate(top_words = reorder_within(term,phi,topic)) %>%
ggplot(aes(x = top_words, y = phi, fill = as.factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free") +
coord_flip() +
scale_x_reordered()
#ch3. 尋找最佳主題數
嘗試3,5,10,15,20,將結果存起來,再做進一步分析。 此部分需要跑一段時間,已經將跑完的檔案存成ldas_result.rdata,可以直接載入
#ldas = c()
#topics = c(3,5,10,15,20)
#for(topic in topics){
#start_time <- Sys.time()
#lda <- LDA(dtm, k = topic, control = list(seed = 2021))
#ldas =c(ldas,lda)
#print(paste(topic ,paste("topic(s) and use time is ", Sys.time() -start_time)))
#save(ldas,file = "ldas_result.rdata") # 將模型輸出成檔案
# }
載入每個主題的LDA結果
load("ldas_result.rdata")
topics = c(3,5,10,15,20)
data_frame(k = topics, perplex = map_dbl(ldas, topicmodels::perplexity)) %>%
ggplot(aes(k, perplex)) +
geom_point() +
geom_line() +
labs(title = "Evaluating LDA topic models",
subtitle = "Optimal number of topics (smaller is better)",
x = "Number of topics",
y = "Perplexity")
## Warning: `data_frame()` was deprecated in tibble 1.1.0.
## Please use `tibble()` instead.
create LDAvis所需的json function 此function是將前面使用 “LDA function”所建立的model,轉換為“LDAVis”套件的input格式。
topicmodels_json_ldavis <- function(fitted, doc_term){
require(LDAvis)
require(slam)
###以下function 用來解決,主題數多會出現NA的問題
### 參考 https://github.com/cpsievert/LDAvis/commit/c7234d71168b1e946a361bc00593bc5c4bf8e57e
ls_LDA = function (phi){
jensenShannon <- function(x, y) {
m <- 0.5 * (x + y)
lhs <- ifelse(x == 0, 0, x * (log(x) - log(m+1e-16)))
rhs <- ifelse(y == 0, 0, y * (log(y) - log(m+1e-16)))
0.5 * sum(lhs) + 0.5 * sum(rhs)
}
dist.mat <- proxy::dist(x = phi, method = jensenShannon)
pca.fit <- stats::cmdscale(dist.mat, k = 2)
data.frame(x = pca.fit[, 1], y = pca.fit[, 2])
}
# Find required quantities
phi <- as.matrix(posterior(fitted)$terms)
theta <- as.matrix(posterior(fitted)$topics)
vocab <- colnames(phi)
term_freq <- slam::col_sums(doc_term)
# Convert to json
json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
vocab = vocab,
doc.length = as.vector(table(doc_term$i)),
term.frequency = term_freq, mds.method = ls_LDA)
return(json_lda)
}
the_lda = ldas[[1]]
json_res <- topicmodels_json_ldavis(the_lda,dtm)
serVis(json_res, out.dir = "vis", open.browser = T)
serVis(json_res, out.dir = "vis", open.browser = T)
writeLines(iconv(readLines("./vis/lda.json"), to = "UTF8"))
the_lda = ldas[[1]] ## 選定topic 為 3 的結果
topics_words <- tidy(the_lda, matrix = "beta") # 注意,在tidy function裡面要使用"beta"來取出Phi矩陣。
colnames(topics_words) <- c("topic", "term", "phi")
topics_words %>% arrange(desc(phi)) %>% head(10)
terms依照各主題的phi值由大到小排序
topics_words %>%
group_by(topic) %>%
top_n(10, phi) %>%
ungroup() %>%
ggplot(aes(x = reorder_within(term,phi,topic), y = phi, fill = as.factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free") +
coord_flip() +
scale_x_reordered()
去除共通詞彙
removed_word = c("肺炎","新冠","疫苗","接種","目前","表示","沒有","新聞","不是")
topics_words %>%
filter(!term %in% removed_word) %>%
group_by(topic) %>%
top_n(15, phi) %>%
ungroup() %>%
ggplot(aes(x = reorder_within(term,phi,topic), y = phi, fill = as.factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free") +
coord_flip() +
scale_x_reordered()
topics_name = c("疫調狀況","美豬事件","陳時中相關回應")
# for every document we have a probability distribution of its contained topics
tmResult <- posterior(the_lda)
doc_pro <- tmResult$topics
document_topics <- doc_pro[metadata$artUrl,]
document_topics_df =data.frame(document_topics)
colnames(document_topics_df) = topics_name
rownames(document_topics_df) = NULL
news_topic = cbind(metadata,document_topics_df)
news_topic %>%
arrange(desc(`陳時中相關回應`)) %>% head(40)
news_topic=subset (news_topic, select = c(-commentNum, -push, -boo))
news_topic %>%
mutate(artDate = as.Date(artDate)) %>%
group_by(artDate = format(artDate,'%Y%m')) %>%
summarise_if(is.numeric, sum, na.rm = TRUE) %>%
melt(id.vars = "artDate")%>%
ggplot( aes(x=artDate, y=value, fill=variable)) +
geom_bar(stat = "identity") + ylab("value") +
scale_fill_manual(values=mycolors[c(11, 12, 13)])+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
news_topic %>%
mutate(artDate = as.Date(artDate)) %>%
filter( !format(artDate,'%Y%m') %in% c(202007,202001))%>%
group_by(artDate = format(artDate,'%Y%m')) %>%
summarise_if(is.numeric, sum, na.rm = TRUE) %>%
melt(id.vars = "artDate")%>%
ggplot( aes(x=artDate, y=value, fill=variable)) +
geom_bar(stat = "identity") + ylab("value") +
scale_fill_manual(values=mycolors[c(1,5,8,12)])+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
news_topic %>%
mutate(artDate = as.Date(artDate)) %>%
filter( !format(artDate,'%Y%m') %in% c(202007,202001))%>%
group_by(artDate = format(artDate,'%Y%m')) %>%
summarise_if(is.numeric, sum, na.rm = TRUE) %>%
melt(id.vars = "artDate")%>%
group_by(artDate)%>%
mutate(total_value =sum(value))%>%
ggplot( aes(x=artDate, y=value/total_value, fill=variable)) +
geom_bar(stat = "identity") + ylab("proportion") +
scale_fill_manual(values=mycolors[c(11,12,13,14)])+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
參考 http://text2vec.org/topic_modeling.html#latent_dirichlet_allocation
library(text2vec)
##
## Attaching package: 'text2vec'
## The following object is masked from 'package:topicmodels':
##
## perplexity
library(udpipe)
tokens <- metadata %>%
unnest_tokens(word, sentence, token=news_tokenizer)
dtf <- document_term_frequencies(tokens, document = "artUrl", term = "word")
dtm <- document_term_matrix(x = dtf)
dtm_clean <- dtm_remove_lowfreq(dtm, minfreq = 30)
dim(dtm_clean)
## [1] 5181 3669
set.seed(2019)
topic_n = 3
lda_model =text2vec::LDA$new(n_topics = topic_n,doc_topic_prior = 0.1, topic_word_prior = 0.001)
doc_topic_distr =lda_model$fit_transform(dtm_clean, n_iter = 1000, convergence_tol = 1e-5,check_convergence_every_n = 100)
## INFO [14:59:01.446] early stopping at 200 iteration
## INFO [14:59:02.403] early stopping at 20 iteration
這個比topicmodels的package跑快超多倍
lda_model$get_top_words(n = 10, lambda = 0.5) ## 查看 前10主題字
## [,1] [,2] [,3]
## [1,] "疫苗" "柯文" "開放"
## [2,] "疫情" "防疫" "美豬"
## [3,] "指揮中心" "市長" "進口"
## [4,] "確診" "就是" "標示"
## [5,] "肺炎" "自己" "衛福部"
## [6,] "檢疫" "什麼" "表示"
## [7,] "感染" "現在" "部長"
## [8,] "完整" "不是" "完整"
## [9,] "流行" "台灣" "衛福"
## [10,] "表示" "一個" "新聞"
lda_model$plot()
## Loading required namespace: servr
# lda_model$plot(out.dir ="lda_result", open.browser = TRUE)