Word2vec跳过图代码

时间:2018-09-19 05:33:18

标签: python word2vec

我构建了一个程序,程序的一部分具有使用window_size = 2

查找windowData的功能。

我的代码:

string = [['I', 'have', 'a', 'pen', 'to', 'use']]

window_size = 2
windowData = []
for lines in string:
    for index,word in enumerate(lines):
        for words in lines[max(index-window_size,0):min(index+window_size,len(string)+1)]:
            if words != word:
                windowData.append([word,words])

print(windowData)

当前输出:

[['I', 'have'], ['have', 'I'], ['a', 'I'], ['a', 'have'], ['pen', 'have']]

根据我对跳过语法的理解,应该是这样的,对吧? (如果我错了,请纠正我)

预期输出:

[['I', 'have'], ['I', 'a'], ['have', 'I'], ['have', 'a'], ['have', 'pen'], ['a', 'have'], ['a', 'I'], ['a', 'pen'],['a', 'to'],  ['pen', 'a'], ['pen', 'have'], ['pen', 'to'], ['pen', 'use'], ['to', 'pen'], ['to', 'a'],['to', 'use'], ['use', 'pen'],['use', 'to']]

我了解仅学习编程语言是不够的,但是我应该更加专注于解决问题。如果可能的话,也请建议我一些网站。谢谢。

2 个答案:

答案 0 :(得分:2)

一些观察结果:

  • 用变量名'string'调用字符串列表是一个坏主意;如果实际上这是Word2Vec中常用的令牌列表文本,那么诸如“句子”或“文本”之类的名称就更清楚了。

  • 您不想重新枚举每个嵌套循环的lines,而是要处理外部循环的当前项目。因此,在sentences上循环将得到一个sentence。您将遍历sentence以获取每个word

  • 这些上下文词到目标词对实际上是使用Python的 tuples 的好地方,它们是在需要时创建的微小的不可变列表-只需使用括号而不是方括号即可。括号。

  • 在切出末端截断的窗口时,无需在sentence的长度上增加一个,因为该长度已经是元素的实际数量,比元素的实际数量多一个。最后位置。但是您确实需要向index + window_size添加一个,因为切片操作([x:y])是第二个值( y )的排他性

  • 实际上,如果您打算让此循环处理许多文本,则可能不希望将所有对返回为来自所有文本的一对巨大列表。相反,您可能想为输入中的每个单词列表返回一个对列表。

  • 刚开始并努力理解时,使用描述性很强的变量名称会很有帮助,并可以将临时结果分成命名变量中的单独行,以使内容更加清晰。

请尝试使用反映了这些更改的最小更改版本:

sentences = [['I', 'have', 'a', 'pen', 'to', 'use']]

window_size = 2
pairs_for_all_sentences = []

for sentence in sentences:
    this_sentence_pairs = []

    for index, target_word in enumerate(sentence): 
        window_words = sentence[max(index - window_size, 0) : min(index + window_size + 1, len(sentence))]

        for window_word in window_words:
            if window_word != target_word:
                this_sentence_pairs.append((window_word, target_word))

    pairs_for_all_sentences.append(this_sentence_pairs)

 print(pairs_for_all_sentences)

最后一点:与如何创建真实的跳过语法对相比,这并不完全正确。虽然没有单词本身生成任何对,但是如果同一单词出现在窗口中,则会创建一个单词对单词对。因此,在句子“我非常非常高兴”中,实际上将训练两对('very', 'very')

答案 1 :(得分:1)

使用itertools:

from itertools import combinations

string = ['I', 'have', 'a', 'pen', 'to', 'use']
window_size = 2
print(list(combinations(string, window_size)))

输出:

[('I', 'have'), ('I', 'a'), ('I', 'pen'), ('I', 'to'), ('I', 'use'), ('have', 'a'), ('have', 'pen'), ('have', 'to'), ('have', 'use'), ('a', 'pen'), ('a', 'to'), ('a', 'use'), ('pen', 'to'), ('pen', 'use'), ('to', 'use')]