การเตรียมข้อความ output
ในแบบฝึกหัดนี้ คุณจะเตรียมข้อความ output เพื่อนำไปใช้กับโมเดลแปลภาษา นอกจากการแปลงข้อความให้เป็นลำดับของ index แล้ว ยังต้องทำ one-hot encoding กับแต่ละ index ด้วย
ข้อความภาษาอังกฤษถูกโหลดไว้ในตัวแปร en_sentences ส่วน tokenizer ที่ผ่านการ fit แล้วอยู่ในตัวแปร output_tokenizer และขนาดของคลังคำศัพท์ภาษาอังกฤษอยู่ในตัวแปร en_vocab_size
นอกจากนี้ ได้สร้างฟังก์ชันสำหรับขั้นตอนแรกของการแปลงภาษา output (การแปลงข้อความให้เป็นลำดับของ index) ไว้แล้ว ฟังก์ชันนี้โหลดอยู่ในสภาพแวดล้อมในชื่อ transform_text_to_sequences() และมีพารามิเตอร์ 2 ตัว ได้แก่ sentences ที่รับรายการประโยคภาษาอังกฤษ และ tokenizer ที่รับออบเจกต์ Tokenizer ที่ผ่านการ fit แล้วจากโมดูล keras.preprocessing.text
numpy โหลดไว้ในชื่อ np
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Recurrent Neural Networks (RNNs) สำหรับ Language Modeling ด้วย Keras
คำแนะนำการฝึกหัด
- ส่งตัวแปร
en_sentencesและoutput_tokenizerให้กับฟังก์ชันtransform_text_to_sequences()เพื่อกำหนดค่าตัวแปรY - ใช้ฟังก์ชัน
to_categorical()เพื่อทำ one-hot encoding กับประโยค โดยใช้ตัวแปรen_vocab_sizeเป็นจำนวน class - แปลง list ชั่วคราวให้เป็น numpy array แล้ว reshape ให้มีรูปร่างเท่ากับ
(num_sentences, sentences_len, en_vocab_size) - แสดงข้อความดิบและข้อความที่แปลงแล้ว
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Initialize the variable
Y = transform_text_to_sequences(____, ____)
# Temporary list
ylist = list()
for sequence in Y:
# One-hot encode sentence and append to list
ylist.append(____(sequence, num_classes=____))
# Update the variable
Y = np.array(ylist).reshape(____, Y.shape[1], en_vocab_size)
# Print the raw sentence and its transformed version
print("Raw sentence: {0}\nTransformed: {1}".format(____, Y[0]))