我构建了一个程序,我的程序的一部分有一个用window_size = 2查找window_size = 2的函数。
我的代码:
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']]我明白,仅仅学习编程语言是不够的,但我应该更多地关注问题的解决。如果可能的话,请向我推荐一些网站。谢谢。
发布于 2018-09-19 17:16:39
几点意见:
Word2Vec中常用的标记列表文本,那么像‘句子’或‘文本’这样的名字就更清晰了。lines,而是处理外部循环的当前项。所以sentences上的循环会给出一个sentence。您将遍历sentence以获得每个word。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')实际上将被训练。
发布于 2018-09-19 06:12:52
使用迭代工具:
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')]https://stackoverflow.com/questions/52398749
复制相似问题