对句子进行填充
您现在将实现一个名为 sents2seqs() 的函数,稍后会用它把数据便捷地转换为神经机器翻译(NMT)模型可接受的格式。sents2seqs() 接受一个由句子字符串组成的列表,并且:
- 将句子转换为由 ID 构成的序列列表,
- 对句子进行填充,使其长度相同,
- 可选地将这些 ID 转换为 onehot 向量。
我们已为您提供了 en_tok,这是一个已在数据上训练好的 Tokenizer。另外需要注意的是,在实现 sents2seqs() 函数时,您会看到一个未使用的参数 input_type。之后会用这个 input_type 来调整与语言相关的参数,例如序列长度和词表大小。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 使用
en_tokTokenizer 将sentences转换为序列。 - 以指定的
pad_type作为填充方式,将序列填充到固定长度en_len,并使用post截断。 - 使用
to_categorical()函数将preproc_text的词 ID 转换为长度为en_vocab的 onehot 向量。 - 使用
sents2seqs()方法,采用pre填充,将sentence转换为填充后的序列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
def sents2seqs(input_type, sentences, onehot=False, pad_type='post'):
# Convert sentences to sequences
encoded_text = ____.____(sentences)
# Pad sentences to en_len
preproc_text = ____(____, padding=____, truncating=____, maxlen=____)
if onehot:
# Convert the word IDs to onehot vectors
preproc_text = ____(____, num_classes=____)
return preproc_text
sentence = 'she likes grapefruit , peaches , and lemons .'
# Convert a sentence to sequence by pre-padding the sentence
pad_seq = sents2seqs('source', [____], pad_type=____)