使用 NMT 生成翻译

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

动机

  • 您已有训练完成的模型
  • 需要辅助人工完成翻译任务
  • 在未见数据上测试模型

  • 如何进行?

    • 使用保留测试集评估模型
    • 通过让模型为一句话预测翻译来测试。
使用 Keras 的机器翻译

转换输入

  • 英文句子
en_st = ['the united states is sometimes chilly during december , but it is sometimes freezing in june .']
  • 转换编码器输入句子
en_seq = sents2seqs('source', en_st, onehot=True, reverse=True)
print(np.argmax(en_seq, axis=-1)
English: ['the united states is sometimes chilly during december , 
           but it is sometimes freezing in june .']
Reversed sentence: ['june in freezing sometimes is it ...'] 
Reversed sequence: [[34   3  54       10        2  4  7 45  5 69 10  2 23 22  6]]
使用 Keras 的机器翻译

生成译文

  • 生成预测

    fr_pred = model.predict(en_seq)
    
  • fr_pred.shape

    • [sentences, seq len, vocab size]
  • 获取预测类别
fr_seq = np.argmax(fr_pred, axis=-1)[0]
[[ 3  7 35 34  2 ...  5  4  4  0  0]] # <= fr_seq
  • fr_seq.shape
    • [num sentences, sequence len]

使用 Keras 的机器翻译

将预测转换为句子

  • 使用列表推导将词 ID 转为句子
fr_sentence = ' '.join([fr_id2word[i] for i in fr_seq if i != 0])
English: the united states is sometimes chilly during december , but it is sometimes freezing in june .

French: les états unis est parfois froid en décembre mais il est parfois le gel en
French (Google Translate): les etats-unis sont parfois froids en décembre, mais parfois gelés en juin
使用 Keras 的机器翻译

深入了解列表推导

  • 列表推导
word_list = [fr_tok.index_word[i] for i in fr_seq if i != 0]
  • For 循环
word_list = []
for i in fr_seq:
  if i != 0:
    word_list.append(fr_tok.index_word[i])
使用 Keras 的机器翻译

开始练习!

使用 Keras 的机器翻译

Preparing Video For Download...