有没有办法使用 R 获得独立的 html 版本的 serVis 视觉效果?

问题描述 投票:0回答:1

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文件,由于浏览器限制,您会看到一个空白页面。如需更详细的描述,请阅读:

serVis 的 LDAvis HTML 输出为空

最简单的解决方案是更改浏览器限制。然而,我想与 100 多人分享这个视觉效果。要求他们全部更改浏览器设置是不可行的。

在Python版本(PyDavis)中,可以通过创建一个独立的html页面轻松解决,该页面可以轻松共享。

将 pyLDAvis 图表导出为独立网页

有没有办法使用 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)
r lda pyldavis
1个回答
0
投票

我认为你有四个选择:

1.启用 CORS

指示您的收件人在其浏览器中启用 CORS。但是,不建议这样做:

  • 这是技术性的,说明因浏览器而异。
  • 如果收件人启用 CORS,则很容易受到 CORS 攻击。
  • 你已经决定不走这条路了。

2.主持人

将 R 输出文件托管在某处。一些选项包括:

3.重组

重新工具 {LDAvis} 包文件。

  • 但正如 @PBulls 提到的,这将是一项工作,因为这些函数是以从外部 json 文件读取数据的方式编写的,这就是产生空白页 COR 问题的原因。

4.转向 Python

您可以运行以下 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")
© www.soinside.com 2019 - 2024. All rights reserved.