開始使用免費開始

句子補齊(Padding)

你現在要實作一個名為 sents2seqs() 的函式,之後會用它把資料轉成神經機器翻譯(NMT)模型可接受的格式。sents2seqs() 會接收一句句子的字串清單,並且:

  • 將句子轉換成由 ID 組成的序列清單,
  • 將句子補齊到相同長度,以及
  • (可選)把這些 ID 轉換為 one-hot 向量。

你已獲得 en_tok,這是一個已在資料上訓練好的 Tokenizer。另外要注意的是,在實作 sents2seqs() 函式時,你會看到一個尚未使用的引數 input_type。之後,這個 input_type 會用來調整與語言相關的參數,例如序列長度與詞彙表大小。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • 使用 en_tok Tokenizer 將 sentences 轉為序列。
  • 以指定的 pad_type 進行補齊,並使用 post 截斷,將序列補齊為固定的 en_len 長度。
  • 使用 to_categorical() 函式,將 preproc_text 的詞 ID 轉換為長度為 en_vocab 的 one-hot 向量。
  • 使用 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=____)
編輯並執行程式碼