是否可以将单词追溯到 doc2vec 中的原始文档?

Is it possible to trace back words to its original doc in doc2vec?

我很想制作一个能够追溯或记住其原始位置的 doc2vec/word2vec 数据集。现在我很想知道它来自哪一行或 txt 文件,但将来甚至是它的原始段落。例如,我希望能够使用多个 txt 文件或一个 csv 来完成。

搜索类似的代码或类似的想法并不公平。所以我很好奇是否有人知道如何或者是否有可能做到这一点; 嵌入或让文字记住其原始位置(文档)。

示例输入:

        Author    |   Title   |     d2v_text     
———————————————————————————————————————————————————————————————————————————                  
0          Name 1 |  Title 1  | this is the first text. first text paragraph.    
1          Name 2 |  Title 2  | this is the second text. second text paragraph.
2          Name 3 |  Title 3  | this is the thirth text. thirth text paragraph.

Name1Title1.txt  (this is the first text. first text paragraph) 
Name2Title2.txt  (this is the second text. second text paragraph)
Name3Title3.txt  (this is the thirth text. thirth text paragraph)

示例输出:

(‘second’, 0.2384900293, ‘Name2Title2’)
(‘text’,0.34948302,’Name1Title1,Name2Title2,Name3Title3’) 

w1 = [“text”]
model.wv.most_similar (positive=w1,topn=1)

[(‘second’, 0.2384900293, ‘Name2Title2’)]

我想实现的是,当从数据集中加载和打印某个向量时,它会知道其原始文档。有人可以帮我解决这个问题吗?

这些模型不存储它们的训练数据——它们只是在每次训练过程中观察数据,为每个单词或文档构建向量模型。

对于 Doc2Vec 文档向量,传统上使用原始文档的一些唯一键来命名文档向量,例如 ID 号或文件名。因此,对于文档向量,随结果报告的标签可能已经提供了您需要的密钥。

对于单词,当你想要一个单词出现的所有文档的列表时,两种传统方法是:

  • 暴力扫描,与命令行程序 grep 一样,您可以在其中查看每个文档中的每个单词,return 单词所在的文档列表出现了。例如,如果您有一个包含 Name1Title1.txt etc 文件的目录,命令 grep -l -E '(^|\W)second(\W|$)' *.txt 将打印那些包含单词 second 的文件。当然,这在大型语料库上非常慢。

  • 构建一个inverted index,其中文档包含哪些单词。然后,在一次扫描成本和 building/storing 索引之后,找到任何单词的文档列表非常快。这是启用全文搜索引擎的基础技术。

一个简单的倒排索引只需要几行Python:

from collections import defaultdict
docs = (  # tuples of doc-name, words
    ('Name1Title1.txt', "this is the first text. first text paragraph".split()),
    ('Name2Title2.txt', "this is the second text. second text paragraph".split()),
    ('Name3Title3.txt', "this is the thirth text. thirth text paragraph".split()),
)
inv_index = defaultdict(list)
for title, words in docs:
    for word in set(words):
        inv_index[word].append(title)

然后,出现单词的任何文档的列表是一个简单的查找:

>>> inv_index['second']
['Name2Title2.txt']
>>> inv_index['this']
['Name1Title1.txt', 'Name2Title2.txt', 'Name3Title3.txt']

倒排索引可能非常大,因此经常使用其他数据结构来实现紧凑性,包括基于文件的索引——因此如果您的语料库很大,您可能需要研究其他倒排索引库才能构建您的索引并以实用的方式进行查找。