R 中的 LDAvis 包使用 LDA 和 serVis 函数创建主题建模分析的可视化。如果保存此可视化,您最终会得到一个包含 css 和 html 文件的文件夹。
json <- createJSON(
phi = tmResult$terms,
theta = tmResult$topics,
doc.length = rowSums(as.matrix(dtm)),
vocab = colnames(as.matrix(dtm)),
term.frequency = colSums(as.matrix(dtm)),
plot.opts = list(xlab = "", ylab = "")
serVis(json, out.dir = 'LDAvis', open.browser = FALSE)
如果打开index.html文件,由于浏览器限制,您会看到一个空白页面。如需更详细的描述,请阅读:
最简单的解决方案是更改浏览器限制。然而,我想与 100 多人分享这个视觉效果。要求他们全部更改浏览器设置是不可行的。
在Python版本(PyDavis)中,可以通过创建一个独立的html页面轻松解决,该页面可以轻松共享。
有没有办法使用 R 获取独立的 html 版本的 serVis 视觉效果?
编辑: 可重现的数据/脚本:
# Install and load required packages
library(LDAvis)
library(tm)
library(topicmodels)
# Set seed for reproducibility
set.seed(123)
# Create fake data
documents <- c("This is the first document.",
"The second document is here.",
"And this is the third one.",
"Is this the first document?")
# Create a Document-Term Matrix
corpus <- Corpus(VectorSource(documents))
dtm <- DocumentTermMatrix(corpus)
#lda
num_topics <- 3
topicModel <- LDA(dtm, k = num_topics, control = list(seed = 9999))
tmResult <- posterior(topicModel)
# Create fake JSON data
json <- createJSON(
phi = tmResult$terms,
theta = tmResult$topics,
doc.length = rowSums(as.matrix(dtm)),
vocab = colnames(as.matrix(dtm)),
term.frequency = colSums(as.matrix(dtm)),
plot.opts = list(xlab = "", ylab = "")
)
# Save fake visualization to a folder
serVis(json, out.dir = 'test', open.browser = TRUE)
我认为你有四个选择:
指示您的收件人在其浏览器中启用 CORS。但是,不建议这样做:
将 R 输出文件托管在某处。一些选项包括:
重新工具 {LDAvis} 包文件。
您可以运行以下 R 代码将数据导出到 json 文件:
jsonlite::write_json(
list(
phi = tmResult$terms,
theta = tmResult$topics,
doc.length = rowSums(as.matrix(dtm)),
vocab = colnames(as.matrix(dtm)),
term.frequency = colSums(as.matrix(dtm))
),
"test/pylda.json"
)
然后使用Python读取该json文件并保存独立的html:
import json
import numpy as np
import pyLDAvis
def load_R_model(filename):
with open(filename, 'r') as j:
data_input = json.load(j)
data = {'topic_term_dists': data_input['phi'],
'doc_topic_dists': data_input['theta'],
'doc_lengths': data_input['doc.length'],
'vocab': data_input['vocab'],
'term_frequency': data_input['term.frequency']}
return data
d = load_R_model('test/pylda.json')
v = pyLDAvis.prepare(**d)
pyLDAvis.save_html(v, "test/pyindex.html")