转换新文本
在本练习中,您将把一段新文本转换为基于先前创建的字典的数值索引序列。
当您已经有一个训练好的模型并想把它应用到新数据集时,这非常有用。对训练数据执行过的预处理步骤也应该同样应用到新文本上,这样模型才能进行预测/分类。
这里,您还将使用特殊标记 '<UKN/>' 来表示不在词表中的词。通常,这类特殊标记会放在字典的最前面,即位置 0。
变量 word_to_index、index_to_word 和 vocabulary 已经加载到环境中。包含新文本的变量也已作为 new_text 加载。新文本已为您打印出来,便于查看。
本练习是课程的一部分
使用 Keras 构建语言建模的循环神经网络(RNN)
练习说明
- 遍历包含各个句子的列表
new_text。 - 当某个单词在字典中找不到时,将其索引设为
0。 - 将由索引构成的句子追加到变量
new_text_split中。 - 使用字典
index_to_word将索引转换回文本。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Loop through the sentences and get indexes
new_text_split = []
for sentence in ____:
sent_split = []
for wd in sentence.split(' '):
index = word_to_index.get(wd, ____)
sent_split.append(index)
new_text_split.append(____)
# Print the first sentence's indexes
print(new_text_split[0])
# Print the sentence converted using the dictionary
print(' '.join([index_to_word[____] for index in new_text_split[0]]))