【问题标题】:How to use vectors from Doc2Vec in Tensorflow如何在 TensorFlow 中使用来自 Doc2Vec 的向量
【发布时间】:2018-10-02 17:20:56
【问题描述】:

我正在尝试使用Doc2Vec 将句子转换为向量,然后使用这些向量来训练一个张量流分类器。

我对使用什么标签以及在完成训练后如何从Doc2Vec 中提取所有文档向量感到有些困惑。

到目前为止我的代码如下:

fake_data = pd.read_csv('./sentences/fake.txt', sep='\n')
real_data = pd.read_csv('./sentences/real.txt', sep='\n')
sentences = []

for i, row in fake_data.iterrows():
    sentences.append(TaggedDocument(row['title'].lower().split(), ['fake', len(sentences)]))

for i, row in real_data.iterrows():
    sentences.append(TaggedDocument(row['title'].lower().split(), ['real', len(sentences)]))

model = gensim.models.Doc2Vec(sentences)

当我做print(model.docvecs[1]) 等时,我得到了向量,但每次我重新制作模型时它们都不一样。

首先:我是否正确使用了Doc2Vec? 第二:有没有办法可以抓取所有标记为“真实”或“假”的文档,然后将它们转换为 numpy 数组并将其传递给 tensorflow?

【问题讨论】:

  • gensim包中的Doc2vec不是tensorflow,它是独立的。

标签: python tensorflow nlp word2vec doc2vec


【解决方案1】:

我相信您为每个TaggedDocument 使用的tag 不是您所期望的。 Doc2Vec 算法正在学习指定标签的向量表示(其中一些可以在文档之间共享)。因此,如果您的目标只是将句子转换为向量,则推荐的标签选择是某种唯一的句子标识符,例如句子索引。

然后将学习模型存储在model.docvecs 中。例如,如果您使用句子索引作为标签,那么您可以通过访问model.docvecs 来获取第一个文档向量以获取标签"0",第二个文档 - 获取标签"1",依此类推。

示例代码:

documents = [doc2vec.TaggedDocument(sentence, ['real-%d' % i])
             for i, sentence in enumerate(sentences)]
model = doc2vec.Doc2Vec(documents, vector_size=10)  # 10 is just for illustration

# Raw vectors are stored in `model.docvecs.vectors_docs`.
# It's easier to access each one by the tag, which are stored in `model.docvecs.doctags`.
for tag in model.docvecs.doctags.keys():
  print(tag, model.docvecs[tag])  # Prints the learned numpy array for this tag

顺便说一句,要控制模型的随机性,请使用Doc2Vec类的seed参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多