使用 Tokenizer 控制词汇表
让我们更深入地了解 Tokenizer 的工作方式。本练习中,您将学习如何使用已经训练好的 Tokenizer 将任意句子转换为序列。此外,您还将学习如何控制 Tokenizer 的词汇表大小。您也会观察当限制 Tokenizer 的词汇表大小时,超出词汇表(OOV)词会发生什么情况。
在本练习中,已为您提供之前实现的 en_tok Tokenizer。该 Tokenizer 已为您导入。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 使用之前的
en_tokTokenizer 将下面的句子转换为序列:she likes grapefruit , peaches , and lemons . - 新建一个
Tokenizer,命名为en_tok_new,将词汇表大小设为 50,并将超出词汇表的词标记设为UNK。 - 在
en_text数据上拟合新的 tokenizer。 - 使用
en_tok_new将句子she likes grapefruit , peaches , and lemons .转换为序列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Convert the sentence to a word ID sequence
seq = ____.____(['she likes grapefruit , peaches , and lemons .'])
print('Word ID sequence: ', seq)
# Define a tokenizer with vocabulary size 50 and oov_token 'UNK'
en_tok_new = ____(num_words=____, ____=____)
# Fit the tokenizer on en_text
en_tok_new.____(____)
# Convert the sentence to a word ID sequence
seq_new = en_tok_new.____(['she likes grapefruit , peaches , and lemons .'])
print('Word ID sequence (with UNK): ', seq_new)
print('The ID 1 represents the word: ', en_tok_new.index_word[1])