ส่วนที่ 1: โมเดลกลับลำดับข้อความ - Encoder
การสร้างโมเดลกลับลำดับข้อความอย่างง่ายเป็นวิธีที่ดีในการทำความเข้าใจกลไกของโมเดล encoder-decoder และวิธีที่ทั้งสองส่วนเชื่อมต่อกัน ตอนนี้จะมาสร้างส่วน encoder ของโมเดลนี้กัน
การสร้าง encoder แบ่งออกเป็นสองแบบฝึกหัด ในแบบฝึกหัดนี้ จะเป็นการกำหนดฟังก์ชันช่วย words2onehot() โดยฟังก์ชัน words2onehot() รับ list ของคำและ dictionary word2index แล้วแปลง list ของคำนั้นให้เป็น array ของ one-hot vector ทั้งนี้ dictionary word2index พร้อมใช้งานใน workspace แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Translation ด้วย Keras
คำแนะนำการฝึกหัด
- แปลงคำเป็น ID โดยใช้ dictionary
word2indexในฟังก์ชันwords2onehot() - แปลง word ID เป็น onehot vector ที่มีความยาว
3(โดยใช้ argumentnum_classes) แล้ว return array ที่ได้ - เรียกใช้ฟังก์ชัน
words2onehot()โดยส่งคำI,likeและcatsเข้าไป แล้วกำหนดผลลัพธ์ให้กับตัวแปรonehot - แสดงผลคำและ onehot vector ที่สอดคล้องกันโดยใช้ฟังก์ชัน
print()และzip()ซึ่งฟังก์ชันzip()ช่วยให้วนซ้ำหลาย list พร้อมกันได้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
import numpy as np
def words2onehot(word_list, word2index):
# Convert words to word IDs
word_ids = [____[w] for w in ____]
# Convert word IDs to onehot vectors and return the onehot array
onehot = ____(____, num_classes=3)
return ____
words = ["I", "like", "cats"]
# Convert words to onehot vectors using words2onehot
onehot = ____(____, ____)
# Print the result as (, ) tuples
print([(w,ohe.tolist()) for ____,____ in zip(words, ____)])