การสร้างคำแปล
ในแบบฝึกหัดนี้ จะได้สร้างคำแปลภาษาฝรั่งเศสโดยใช้ inference model ที่ฝึกด้วยเทคนิค Teacher Forcing
โมเดลนี้ (nmt_tf) ผ่านการฝึกมาแล้ว 50 epochs บนประโยค 100,000 ประโยค และทำความแม่นยำได้ประมาณ 98% บนชุด validation ที่มีมากกว่า 35,000 ประโยค แบบฝึกหัดนี้อาจใช้เวลาโหลดนานขึ้นเล็กน้อย เนื่องจากต้องโหลดโมเดลที่ฝึกไว้แล้ว มีฟังก์ชัน sents2seqs() และฟังก์ชันใหม่อีก 2 ตัวให้ใช้งาน:
word2onehot(tokenizer, word, vocab_size) รับพารามิเตอร์ดังนี้:
- tokenizer - ออบเจกต์
Tokenizerของ Keras - word - สตริงที่แทนคำหนึ่งคำในคลังคำศัพท์ (เช่น
'apple') - vocab_size - ขนาดของคลังคำศัพท์
probs2word(probs, tok) รับพารามิเตอร์ดังนี้:
- probs - output จากโมเดลที่มี shape เป็น
[1,<French Vocab Size>] - tok - ออบเจกต์
Tokenizerของ Keras
ดูซอร์สโค้ดของฟังก์ชันเหล่านี้ได้โดยพิมพ์ print(inspect.getsource(word2onehot)) และ print(inspect.getsource(probs2word)) ใน console
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Translation ด้วย Keras
คำแนะนำการฝึกหัด
- ทำนาย decoder state เริ่มต้น (
de_s_t) ด้วย encoder - ทำนาย output และ state ใหม่จาก decoder โดยใช้ผลการทำนายก่อนหน้า (output) และ state ก่อนหน้าเป็น input จากนั้นอัปเดต state แบบวนซ้ำ
- แปลง probability output ให้เป็นสตริงของคำโดยใช้ฟังก์ชัน
probs2word() - แปลงสตริงของคำให้เป็นลำดับ one-hot โดยใช้ฟังก์ชัน
word2onehot()
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
en_sent = ['the united states is sometimes chilly during december , but it is sometimes freezing in june .']
print('English: {}'.format(en_sent))
en_seq = sents2seqs('source', en_sent, onehot=True, reverse=True)
# Predict the initial decoder state with the encoder
de_s_t = ____.predict(____)
de_seq = word2onehot(fr_tok, 'sos', fr_vocab)
fr_sent = ''
for i in range(fr_len):
# Predict from the decoder and recursively assign the new state to de_s_t
de_prob, ____ = ____.predict([____,____])
# Get the word from the probability output using probs2word
de_w = probs2word(____, fr_tok)
# Convert the word to a onehot sequence using word2onehot
de_seq = word2onehot(fr_tok, ____, fr_vocab)
if de_w == 'eos': break
fr_sent += de_w + ' '
print("French (Ours): {}".format(fr_sent))
print("French (Google Translate): les etats-unis sont parfois froids en décembre, mais parfois gelés en juin")