在数据集Cora上应用文本分析
首先还是要安装并加载需要使用的包
require("ggplot2")
install.packages("reshape2")
install.packages("lda")
require("reshape2")
require("lda")
#加载文档和词汇表数据(cora.documents)
data(cora.documents)
data(cora.vocab)
# 当前/活动主题将自动应用于您绘制的每个绘图
theme_set(theme_bw())
加载得到的cora documents 如下所示
# 显示的主题集群数量
K <- 10
# 要显示的文档数量
N <- 9
result <- lda.collapsed.gibbs.sampler(cora.documents,
K,
cora.vocab,
25,
0.1,
0.1,
compute.log.likelihood=TRUE)
得到的result如图:
# 获取集群中的顶部单词
top.words <- top.topic.words(result$topics, 5, by.score=TRUE)
# 构建主题的比例
topic.props <- t(result$document_sums) / colSums(result$document_sums)
document.samples <- sample(1:dim(topic.props)[1], N)
topic.props <- topic.props[document.samples,]
topic.props[is.na(topic.props)] <- 1 / K
colnames(topic.props) <- apply(top.words, 2, paste, collapse=" ")
topic.props.df <- melt(cbind(data.frame(topic.props),
document=factor(1:N)),
variable.name="topic",
id.vars = "document")
qplot(topic, value*100, fill=topic, stat="identity",
ylab="proportion (%)", data=topic.props.df,
geom="histogram") +
theme(axis.text.x = element_text(angle=0, hjust=1, size=12)) +
coord_flip() +
facet_wrap(~ document, ncol=3)
最终我们得到了下图:
参考书目
- Data Science and Big Data Analytics: Discovering, Analyzing, Visualizing and Presenting Data, EMC Education Services, John Wiley & Sons, 27 Jan. 2015