0

使用gensim word2vec模型来计算两个词之间的相似度。用 250mb 的维基百科文本训练模型得到了很好的结果——相关词对的相似度得分约为 0.7-0.8。

问题是,当我使用该Phraser模型将短语相加时,相同单词的相似度得分几乎为零。

短语模型的结果:

speed - velocity - 0.0203503432178
high - low - -0.0435703782446
tall - high - -0.0076987978333
nice - good - 0.0368784716958
computer - computational - 0.00487748035808

这可能意味着我没有正确使用 Phraser 模型。

我的代码:

    data_set_location = **
    sentences = SentenceIterator(data_set_location)

    # Train phrase locator model
    self.phraser = Phraser(Phrases(sentences))

    # Renewing the iterator because its empty
    sentences = SentenceIterator(data_set_location)

    # Train word to vector model or load it from disk
    self.model = Word2Vec(self.phraser[sentences], size=256, min_count=10, workers=10)



class SentenceIterator(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):
        for fname in os.listdir(self.dirname):
            for line in open(os.path.join(self.dirname, fname), 'r', encoding='utf-8', errors='ignore'):
                yield line.lower().split()

单独尝试 pharser 模型看起来效果很好:

>>>vectorizer.phraser['new', 'york', 'city', 'the', 'san', 'francisco'] ['new_york', 'city', 'the', 'san_francisco']

什么会导致这种行为?

试图找出解决方案:

根据 gojomo 的回答,我尝试创建一个PhraserIterator

import os

class PhraseIterator(object):
def __init__(self, dirname, phraser):
    self.dirname = dirname
    self.phraser = phraser

def __iter__(self):
    for fname in os.listdir(self.dirname):
        for line in open(os.path.join(self.dirname, fname), 'r', encoding='utf-8', errors='ignore'):
            yield self.phraser[line.lower()]

使用这个迭代器我试图训练我的Word2vec模型。

phrase_iterator = PhraseIterator(text_dir, self.phraser)
self.model = Word2Vec(phrase_iterator, size=256, min_count=10, workers=10

Word2vec 训练日志:

    Using TensorFlow backend.
2017-06-30 19:19:05,388 : INFO : collecting all words and their counts
2017-06-30 19:19:05,456 : INFO : PROGRESS: at sentence #0, processed 0 words and 0 word types
2017-06-30 19:20:30,787 : INFO : collected 6227763 word types from a corpus of 28508701 words (unigram + bigrams) and 84 sentences
2017-06-30 19:20:30,793 : INFO : using 6227763 counts as vocab in Phrases<0 vocab, min_count=5, threshold=10.0, max_vocab_size=40000000>
2017-06-30 19:20:30,793 : INFO : source_vocab length 6227763
2017-06-30 19:21:46,573 : INFO : Phraser added 50000 phrasegrams
2017-06-30 19:22:22,015 : INFO : Phraser built with 70065 70065 phrasegrams
2017-06-30 19:22:23,089 : INFO : saving Phraser object under **/Models/word2vec/phrases_model, separately None
2017-06-30 19:22:23,441 : INFO : saved **/Models/word2vec/phrases_model
2017-06-30 19:22:23,442 : INFO : collecting all words and their counts
2017-06-30 19:22:29,347 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types
2017-06-30 19:33:06,667 : INFO : collected 143 word types from a corpus of 163438509 raw words and 84 sentences
2017-06-30 19:33:06,677 : INFO : Loading a fresh vocabulary
2017-06-30 19:33:06,678 : INFO : min_count=10 retains 95 unique words (66% of original 143, drops 48)
2017-06-30 19:33:06,679 : INFO : min_count=10 leaves 163438412 word corpus (99% of original 163438509, drops 97)
2017-06-30 19:33:06,683 : INFO : deleting the raw counts dictionary of 143 items
2017-06-30 19:33:06,683 : INFO : sample=0.001 downsamples 27 most-common words
2017-06-30 19:33:06,683 : INFO : downsampling leaves estimated 30341972 word corpus (18.6% of prior 163438412)
2017-06-30 19:33:06,684 : INFO : estimated required memory for 95 words and 256 dimensions: 242060 bytes
2017-06-30 19:33:06,685 : INFO : resetting layer weights
2017-06-30 19:33:06,724 : INFO : training model with 10 workers on 95 vocabulary and 256 features, using sg=0 hs=0 sample=0.001 negative=5 window=5
2017-06-30 19:33:14,974 : INFO : PROGRESS: at 0.00% examples, 0 words/s, in_qsize 0, out_qsize 0
2017-06-30 19:33:23,229 : INFO : PROGRESS: at 0.24% examples, 607 words/s, in_qsize 0, out_qsize 0
2017-06-30 19:33:31,445 : INFO : PROGRESS: at 0.48% examples, 810 words/s, 
...
2017-06-30 20:19:00,864 : INFO : PROGRESS: at 98.57% examples, 1436 words/s, in_qsize 0, out_qsize 1
2017-06-30 20:19:06,193 : INFO : PROGRESS: at 99.05% examples, 1437 words/s, in_qsize 0, out_qsize 0
2017-06-30 20:19:11,886 : INFO : PROGRESS: at 99.29% examples, 1437 words/s, in_qsize 0, out_qsize 0
2017-06-30 20:19:17,648 : INFO : PROGRESS: at 99.52% examples, 1438 words/s, in_qsize 0, out_qsize 0
2017-06-30 20:19:22,870 : INFO : worker thread finished; awaiting finish of 9 more threads
2017-06-30 20:19:22,908 : INFO : worker thread finished; awaiting finish of 8 more threads
2017-06-30 20:19:22,947 : INFO : worker thread finished; awaiting finish of 7 more threads
2017-06-30 20:19:22,947 : INFO : PROGRESS: at 99.76% examples, 1439 words/s, in_qsize 0, out_qsize 8
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 6 more threads
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 5 more threads
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 4 more threads
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 3 more threads
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 2 more threads
2017-06-30 20:19:22,948 : INFO : worker thread finished; awaiting finish of 1 more threads
2017-06-30 20:19:22,949 : INFO : worker thread finished; awaiting finish of 0 more threads
2017-06-30 20:19:22,949 : INFO : training on 817192545 raw words (4004752 effective words) took 2776.2s, 1443 effective words/s
2017-06-30 20:19:22,950 : INFO : saving Word2Vec object under **/Models/word2vec/word2vec_model, separately None
2017-06-30 20:19:22,951 : INFO : not storing attribute syn0norm
2017-06-30 20:19:22,951 : INFO : not storing attribute cum_table
2017-06-30 20:19:22,958 : INFO : saved **/Models/word2vec/word2vec_model

经过这次训练 - 任何两个相似度计算产生零:

speed - velocity - 0
high - low - 0

所以似乎迭代器运行不正常,所以我使用 gojomo 技巧检查了它:

print(sum(1 for _ in s))
1

print(sum(1 for _ in s))
1

及其工作。

可能是什么问题?

4

2 回答 2

1

首先,如果您的可迭代类工作正常——而且在我看来没问题——你将不需要“更新迭代器,因为它是空的”。相反,它将能够被迭代多次。您可以使用以下代码测试它是否作为可迭代对象而不是单个迭代正常工作:

sentences = SentencesIterator(mypath)
print(sum(1 for _ in sentences))
print(sum(1 for _ in sentences))

如果相同的长度打印两次,恭喜,你有一个真正的可迭代对象。(您可能需要更新类名以反映这一点。)如果第二个长度是0,则您只有一个迭代器:它可以被使用一次,然后在后续尝试中为空。(如果是这样,请调整类代码,以便每次调用都重新__iter__()开始。但如上所述,我认为您的代码已经正确。)

这个题外话很重要,因为你的问题的真正原因是它self.phraser[sentences]只是返回一个一次性的迭代器对象,而不是一个可重复的可迭代对象。因此,Word2Vec 的第一个词汇发现步骤在它的一次传递中消耗了整个语料库,然后所有训练传递都看不到任何东西——并且没有训练发生。(如果您有 INFO 级别的登录,这在输出中应该很明显,显示没有示例的即时训练。)

尝试创建一个PhraserIterable类,它需要 aphraser和 a sentences,并在每次调用时__iter__()开始一个新的、新的对 setences 的传递。提供一个(确认重启)实例作为 Word2Vec 的语料库。您应该会看到训练需要更长的时间,因为它默认的 5 次通过 - 然后在以后的令牌比较中看到真正的结果。

sentences另外:将原始unigram即时升级为短语计算的 bigram 在计算上可能会很昂贵。上面建议的方法意味着发生 6 次——词汇扫描,然后是 5 次训练通过。如果需要考虑运行时间,最好执行一次短语组合,将结果保存到内存中的对象(如果您的语料库很容易放入 RAM)或新的简单空格分隔的临时结果文件,然后将该文件用作 Word2Vec 模型的输入。

于 2017-06-30T09:35:20.187 回答
0

使用它的帮助gojomo是有效的代码:

短语迭代器:

class PhraseIterator(object):
def __init__(self, phraser, sentences_iterator):
    self.phraser = phraser
    self.sentences_iterator = sentences_iterator

def __iter__(self):
        yield self.phraser[self.sentences_iterator]

使用此迭代器会产生错误:

不可散列的类型列表

所以我找到了一个以这种方式使用它的解决方案:

from itertools import chain

phrase_iterator = PhraseIterator(self.phraser, sentences)
self.model = Word2Vec(list(chain(*phrase_iterator)), size=256, min_count=10, workers=10)

现在相似度计算工作得很好(比以前更好,没有措辞):

speed - velocity - 0.950267364305
high - low - 0.933983275802
tall - high - 0.858025875923
nice - good - 0.878882061037
computer - computational - 0.972395648333
于 2017-07-01T15:57:13.243 回答