用gensim的fasttext的wrapper训练word embedding后,如何嵌入新的句子?

After training word embedding with gensim's fasttext's wrapper, how to embed new sentences?

阅读 gensim docs 上的教程后,我不明白从训练模型生成新嵌入的正确方法是什么。到目前为止,我已经像这样训练了 gensim 的快速文本嵌入:

from gensim.models.fasttext import FastText as FT_gensim

model_gensim = FT_gensim(size=100)

# build the vocabulary
model_gensim.build_vocab(corpus_file=corpus_file)

# train the model
model_gensim.train(
    corpus_file=corpus_file, epochs=model_gensim.epochs,
    total_examples=model_gensim.corpus_count, total_words=model_gensim.corpus_total_words
)

然后,假设我想获取与这句话相关联的嵌入向量:

sentence_obama = 'Obama speaks to the media in Illinois'.lower().split()
sentence_president = 'The president greets the press in Chicago'.lower().split()

如何使用我之前训练的 model_gensim 获得它们?

您可以依次查找每个词的向量:

wordvecs_obama = [model_gensim[word] for word in sentence_obama]

对于您的 7 字输入句子,您将在 wordvecs_obama 中得到 7 word-vectors 个列表。

由于其固有功能,所有 FastText 模型都不会将较长的文本转换为单个向量。 (具体来说,您训练的模型没有默认的方法。)

原始 Facebook FastText 代码中有一个 "classification mode" 涉及不同风格的训练,其中文本在训练时与已知标签相关联,并且句子的所有 word-vectors在训练期间结合,以及稍后要求模型对新文本进行分类时。但是,FastText 的 gensim 实现目前不支持这种模式,因为 gensim 的目标是提供无监督算法而不是监督算法。

您可以通过对 word-vectors:

进行平均来估算 FastText 模式的作用
import numpy as np
meanvec_obama = np.array(wordvecs_obama).mean(axis=0)

根据您的最终目的,类似的东西可能仍然有用。 (但是,该平均值对于分类没有那么有用,就好像 word-vectors 最初是在 FastText 模式下使用已知标签针对该目标进行训练一样。)