การ Pad ประโยค
ในแบบฝึกหัดนี้จะได้สร้างฟังก์ชันชื่อ sents2seqs() ซึ่งจะนำไปใช้แปลงข้อมูลให้อยู่ในรูปแบบที่โมเดลแปลภาษาด้วยโครงข่ายประสาทเทียม (NMT) ยอมรับได้ sents2seqs() รับ list ของ string ที่เป็นประโยค แล้ว
- แปลงประโยคให้เป็น list ของ sequence ที่ประกอบด้วย ID
- Pad ประโยคให้มีความยาวเท่ากัน และ
- แปลง ID ให้เป็น onehot vector (เป็น option ที่เลือกได้)
มีการจัดเตรียม en_tok ซึ่งเป็น Tokenizer ที่ฝึกจากข้อมูลแล้วให้พร้อมใช้งาน นอกจากนี้ ในการสร้างฟังก์ชัน sents2seqs() จะพบอาร์กิวเมนต์ชื่อ input_type ที่ยังไม่ได้ใช้งาน ซึ่งภายหลังจะนำ input_type มาใช้เพื่อปรับพารามิเตอร์ที่ขึ้นอยู่กับภาษา เช่น ความยาวของ sequence และขนาดของ vocabulary
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Translation ด้วย Keras
คำแนะนำการฝึกหัด
- แปลง
sentencesให้เป็น sequence โดยใช้en_tokTokenizer - Pad sequence ให้มีความยาวคงที่ตาม
en_lenโดยระบุประเภทของ padding เป็นpad_typeและใช้การตัดทอนแบบpost - แปลง word ID ใน
preproc_textให้เป็น onehot vector ที่มีความยาวen_vocabโดยใช้ฟังก์ชันto_categorical() - แปลง
sentenceให้เป็น padded sequence โดยใช้เมธอดsents2seqs()พร้อมกำหนด padding แบบpre
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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=____)