การเตรียมข้อมูลด้วย Keras
โมดูลที่สำคัญรองลงมาของ Keras คือ keras.preprocessing ในแบบฝึกหัดนี้จะได้เรียนรู้วิธีใช้โมดูลและฟังก์ชันหลักเพื่อเตรียมข้อมูลดิบให้อยู่ในรูปแบบ input ที่ถูกต้อง Keras มีฟังก์ชันที่ทำหน้าที่แทนวิธี dictionary ที่ได้เรียนไปก่อนหน้านี้
จะใช้โมดูล keras.preprocessing.text.Tokenizer เพื่อสร้าง dictionary ของคำโดยใช้เมธอด .fit_on_texts() จากนั้นแปลงข้อความให้เป็น id ตัวเลขที่แทน index ของแต่ละคำใน dictionary ด้วยเมธอด .texts_to_sequences()
แล้วใช้ฟังก์ชัน .pad_sequences() จาก keras.preprocessing.sequence เพื่อทำให้ลำดับทุกชุดมีขนาดเท่ากัน (ซึ่งจำเป็นสำหรับโมเดล) โดยการเติมศูนย์ให้กับข้อความที่สั้นเกินไป และตัดข้อความที่ยาวเกินไป
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Recurrent Neural Networks (RNNs) สำหรับ Language Modeling ด้วย Keras
คำแนะนำการฝึกหัด
- Import
Tokenizerและpad_sequencesจากโมดูลที่เกี่ยวข้อง - Fit ออบเจ็กต์
tokenizerกับข้อมูลตัวอย่างที่เก็บอยู่ในtexts - แปลงข้อความให้เป็นลำดับ index ตัวเลขโดยใช้เมธอด
.texts_to_sequences() - ปรับขนาดของข้อความให้เท่ากันด้วยการ padding
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____
# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)
# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))
# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))