เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การ 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_tok Tokenizer
  • 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=____)
แก้ไขและรันโค้ด