【发布时间】:2019-02-10 20:36:20
【问题描述】:
我有一个代码,用于在 sentence_start 之后给定一个单词生成句子
遇到错误的代码:
def generate_sentences(model, n, index_to_word, word_to_index):
for i in range(n):
sent = None
while not sent:
for i in range(len(arr)):
sent = generate_sentence(arr[i], model, index_to_word, word_to_index)
# print (arr[i])
print_sentence(sent, index_to_word)
print("\n")
这里是被调用的函数:
def generate_sentence(anot, model, index_to_word, word_to_index, min_length=5):
# We start the sentence with the start token
new_sentence = [word_to_index[SENTENCE_START_TOKEN], word_to_index[anot]]
# Repeat until we get an end token
while not new_sentence[-1] == word_to_index[SENTENCE_END_TOKEN]:
next_word_probs = model.predict(new_sentence)[-1]
samples = np.random.multinomial(1, next_word_probs)
sampled_word = np.argmax(samples)
new_sentence.append(sampled_word)
# Seomtimes we get stuck if the sentence becomes too long, e.g. "........" :(
# And: We don't want sentences with UNKNOWN_TOKEN's
if len(new_sentence) > 100 or sampled_word == word_to_index[UNKNOWN_TOKEN]:
return None
if len(new_sentence) < min_length:
return None
return new_sentence
def print_sentence(s, index_to_word):
sentence_str = [index_to_word[x] for x in s[1:-1]]
print(" ".join(sentence_str))
sys.stdout.flush()
这是回溯:
Traceback (most recent call last):
File "<ipython-input-10-b9a0a1f5bd04>", line 1, in <module>
runfile('C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py', wdir='C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master')
File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py", line 53, in <module>
generate_sentences(model, 20, index_to_word, word_to_index)
File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 190, in generate_sentences
print_sentence(sent, index_to_word)
File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 179, in print_sentence
sentence_str = [index_to_word[x] for x in s[1:-1]]
TypeError: 'NoneType' object is not subscriptable
我怀疑是函数print_sentence(sent, index_to_word)引起的错误
我试图编辑缩进以从循环中排除 print_sentence 函数。
但输出只读取数组arr的最后一个元素
【问题讨论】:
-
如果
generate_sentence()返回None那么你会得到这个错误,因为你不能迭代None对象。由于您有一些内置标准可以返回None,我怀疑是这种情况。您可能想尝试在print_sentence()中捕获此错误,以查看哪些输入会产生此行为,以便您可以在代码中优雅地处理它们。 -
你故意
return None在某些情况下generate_sentence。但无论该函数返回什么,您都将其分配给sent,然后用sent调用print_sentence。然后,无论你传递给print_sentence,它都会尝试循环。那就是问题所在;正确的修复取决于您想要做什么。你为什么返回 None,当你这样做时你想发生什么?如果你能解释这一点,应该很容易实现你解释的任何内容。