标签'Text_4'在培训语料库中看不到/无效

时间:2018-03-31 08:07:33

标签: python python-3.x gensim doc2vec

我需要一些帮助来诊断我遇到的一些文本向量过程中遇到的问题。实际上,我正在尝试应用doc2vec字嵌入来获取分类任务的向量。在我运行代码之后,我得到了一些很难弄清楚的错误,因为我很新。以下是代码和输出

    def constructLabeledSentences(data):
    sentences=[]
    for index, row in data.iteritems():
        sentences.append(TaggedDocument(utils.to_unicode(row).split(), ['Text' + '_%s' % str(index)]))
    return sentences

    x_raw_doc_sentences = constructLabeledSentences(x_raw_train['Text'])
x_raw_doc_model = Doc2Vec(min_count=5, window=5, vector_size=300, sample=0.001, negative=5, workers=4, epochs=10,seed=1)
x_raw_doc_model.build_vocab(x_raw_doc_sentences)
x_raw_doc_model.train(x_raw_doc_sentences, total_examples=x_raw_doc_model.corpus_count, epochs=x_raw_doc_model.epochs)

运行模型后,我尝试用以下方法提取向量:

x_raw_doc_train_arrays = np.zeros((x_raw_train.shape[0], 300))
for i in range (x_raw_train.shape[0]):
    x_raw_doc_train_arrays[i]=x_raw_doc_model.docvecs['Text_'+str(i)]

这是我得到的输出:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-106-bc0222fef295> in <module>()
      1 x_raw_doc_train_arrays = np.zeros((x_raw_train.shape[0], 300))
      2 for i in range (x_raw_train.shape[0]):
----> 3     x_raw_doc_train_arrays[i]=x_raw_doc_model.docvecs['Text_'+str(i)]
      4 
      5 

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py in __getitem__(self, index)
   1197                 return self.vectors_docs[self._int_index(index, self.doctags, self.max_rawint)]
   1198             return vstack([self[i] for i in index])
-> 1199         raise KeyError("tag '%s' not seen in training corpus/invalid" % index)
   1200 
   1201     def __contains__(self, index):

KeyError: "tag 'Text_4' not seen in training corpus/invalid"

我做错了什么,或者应该这样做我没有?

1 个答案:

答案 0 :(得分:1)

您是否看过sentences以确保TaggedDocument的{​​{1}}包含tags

如果是这样,该文件是否有任何特殊情况可能阻止其提供标签?例如,最初是否为空,或者在应用'Text_4'个单词后忽略所有稀有单词(这通常是矢量质量的好主意)?

另请注意,您可以使用原始整数作为min_count中的单个标记值。 (在这种情况下,tags数组被初始化为包含所有索引的向量,直到您使用的最高索引 - 所以像docvecs这样的值对应于无操作示例 获取一个向量,但在训练期间根本没有调整过,保持其初始化的随机值。)