【发布时间】:2020-04-30 10:39:00
【问题描述】:
我正在尝试通过 reticulate 在 R 环境中运行 Python 的 gensim 包。更具体地说,我正在尝试构建一个 doc2vec 模型,为此需要准备一个令牌和标签的语料库。
TaggedDocument 函数是我遇到问题的地方。这是我试图在 R 中重现的 python 示例:
import pandas as pd
import numpy as np
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["this is the first sentence",
"running doc2vec via reticulate",
"r and python bff forever",
"this aint working"]
tags = ["a","b","a","c"]
corpus = pd.DataFrame({"sentences": data, "labels": tags})
tagged_data = corpus.apply(
lambda r: TaggedDocument(words=word_tokenize(r['sentences']), tags=[r.labels]), axis=1)
这会产生这样的输出:
0 ([this, is, the, first, sentence], [a])
1 ([running, doc2vec, via, reticulate], [b])
2 ([r, and, python, bff, forever], [a])
3 ([this, aint, working], [c])
dtype: object
可用于构建词汇表和训练 doc2vec 模型。
如何在 R 中得到相同的结果(可能没有循环)?
library(reticulate)
gensim <- import("gensim")
Doc2Vec <- gensim$models$Doc2Vec
TaggedDocument <- gensim$models$doc2vec$TaggedDocument
sentences <- c("this is the first sentence",
"running doc2vec via reticulate",
"r and python bff forever",
"this aint working")
labels <- c("a","b","c","a")
提前致谢!
* 编辑 *
我一直在尝试一个更简单的设置:
library(reticulate)
gensim <- import("gensim")
Doc2Vec <- gensim$models$Doc2Vec
TaggedDocument <- gensim$models$doc2vec$TaggedDocument
sentences <- c("this is the first sentence")
tags <- c("a")
df <- data.frame (tokens= sentences, labels = tags)
tagged_docs <- TaggedDocument(words = df$tokens, tags = df$labels)
但我一直收到相同的错误消息:
块引用 py_call_impl(callable, dots$args, dots$keywords) 中的错误: AttributeError: 'str' object has no attribute 'words' - 详细回溯: 文件“C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py”,第 1184 行,在 build_vocab progress_per=progress_per, trim_rule=trim_rule 文件“C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py”,第 1381 行,在 scan_vocab total_words,corpus_count = self._scan_vocab(文档,docvecs,progress_per,trim_rule) _scan_vocab 中的文件“C:\Anaconda\lib\site-packages\gensim\models\doc2vec.py”,第 1310 行 if isinstance(document.words, string_types):
---
我做错了什么?
【问题讨论】:
标签: r gensim doc2vec reticulate