編碼器-解碼器架構

使用 Keras 進行機器翻譯

Thushan Ganegedara

Data Scientist and Author

編碼器-解碼器模型

機器翻譯模型

使用 Keras 進行機器翻譯

編碼器

編碼器

使用 Keras 進行機器翻譯

編碼器與解碼器

編碼器與解碼器

使用 Keras 進行機器翻譯

類比:編碼器-解碼器架構

編碼器類比

解碼器類比

使用 Keras 進行機器翻譯

句子反轉:編碼器-解碼器模型

編碼器-解碼器文字反轉

使用 Keras 進行機器翻譯

撰寫編碼器

def words2onehot(word_list, word2index):
  word_ids = [word2index[w] for w in word_list]
  onehot = to_categorical(word_ids, 3)
  return onehot
def encoder(onehot):
  word_ids = np.argmax(onehot, axis=1)
  return word_ids
使用 Keras 進行機器翻譯

撰寫編碼器

onehot = words2onehot(["I", "like", "cats"], word2index)
context = encoder(onehot)
print(context)
[0, 1, 2]
使用 Keras 進行機器翻譯

撰寫解碼器

  • 解碼器:Word IDs → 反轉 IDs → one-hot 向量
def decoder(context_vector):
  word_ids_rev = context_vector[::-1]
  onehot_rev = to_categorical(word_ids_rev, 3)
  return onehot_rev
  • 輔助函式:將 one-hot 向量轉成可讀文字
def onehot2words(onehot, index2word):
  ids = np.argmax(onehot, axis=1)
  return [index2word[id] for id in ids]
使用 Keras 進行機器翻譯

撰寫解碼器

onehot_rev = decoder(context)
reversed_words = onehot2words(onehot_rev, index2word)

print(reversed_words)
['cats', 'like', 'I']
使用 Keras 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...