训练 NMT 模型

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

回顾模型

  • 编码器 GRU
    • 处理英文词
    • 输出上下文向量
  • 解码器 GRU
    • 接收上下文向量
    • 输出一串 GRU 隐状态
  • 解码器预测层
    • 接收该隐状态序列
    • 输出法语词的预测概率

使用 Keras 的机器翻译

参数优化

  • GRU 层与 Dense 层包含参数
  • 常用 W(权重)和 b(偏置)表示(随机初始化)
  • 负责将输入映射为有用输出
  • 通过优化器最小化损失而逐步更新
    • 损失:预测(模型生成的法语词)与真实输出(实际法语词)的差异
  • 在模型编译时指定

`

使用 Keras 的机器翻译

训练模型

  • 训练迭代
    for ei in range(n_epochs): # 数据集单次遍历
      for i in range(0,data_size,bsize): # 处理一个批次
    
  • 获取一个训练批次
      en_x = sents2seqs('source', en_text[i:i+bsize], onehot=True, reverse=True)
      de_y = sents2seqs('target', en_text[i:i+bsize], onehot=True)
    
  • 在单个批次上训练
      nmt.train_on_batch(en_x, de_y)
    
  • 评估模型
      res = nmt.evaluate(en_x, de_y, batch_size=bsize, verbose=0)
    
使用 Keras 的机器翻译

训练模型

  • 获取训练损失与准确率
      res = nmt.evaluate(en_x, de_y, batch_size=bsize, verbose=0)
      print("Epoch {} => Train Loss:{}, Train Acc: {}".format(
        ei+1,res[0], res[1]*100.0))
    
Epoch 1 => Train Loss:4.8036723136901855, Train Acc: 5.215999856591225
...
Epoch 1 => Train Loss:4.718592643737793, Train Acc: 47.0880001783371
...
Epoch 5 => Train Loss:2.8161656856536865, Train Acc: 56.40000104904175
Epoch 5 => Train Loss:2.527724266052246, Train Acc: 54.368001222610474
Epoch 5 => Train Loss:2.2689621448516846, Train Acc: 54.57599759101868
Epoch 5 => Train Loss:1.9934935569763184, Train Acc: 56.51199817657471
Epoch 5 => Train Loss:1.7581449747085571, Train Acc: 55.184000730514526
Epoch 5 => Train Loss:1.5613118410110474, Train Acc: 55.11999726295471
使用 Keras 的机器翻译

避免过拟合

  • 将数据集分成两部分
    • 训练集——用于训练模型
    • 验证集——用于监控模型准确率
  • 当验证准确率不再提升时,停止训练。

过拟合拐点

使用 Keras 的机器翻译

划分数据集

  • 定义训练集和验证集大小

    train_size, valid_size = 800, 200
    
  • 随机打乱数据索引

    inds = np.arange(len(en_text))
    np.random.shuffle(inds)
    
  • 获取训练与验证索引

    train_inds = inds[:train_size]
    valid_inds = inds[train_size:train_size+valid_size]
    
使用 Keras 的机器翻译

划分数据集

  • 按索引划分数据:
    • 训练索引对应的数据放入训练集
    • 验证索引对应的数据放入验证集
tr_en = [en_text[ti] for ti in train_inds]
tr_fr = [fr_text[ti] for ti in train_inds]

v_en = [en_text[ti] for ti in valid_inds]
v_fr = [fr_text[ti] for ti in valid_inds]
使用 Keras 的机器翻译

结合验证训练模型

n_epochs, bsize = 5, 250
for ei in range(n_epochs):

for i in range(0,train_size,bsize): en_x = sents2seqs('source', tr_en[i:i+bsize], onehot=True, pad_type='pre') de_y = sents2seqs('target', tr_fr[i:i+bsize], onehot=True) nmt.train_on_batch(en_x, de_y)
v_en_x = sents2seqs('source', v_en, onehot=True, pad_type='pre') v_de_y = sents2seqs('target', v_fr, onehot=True)
res = nmt.evaluate(v_en_x, v_de_y, batch_size=valid_size, verbose=0) print("Epoch: {} => Loss:{}, Val Acc: {}".format(ei+1,res[0], res[1]*100.0))
Epoch 1 => Train Loss:4.8036723136901855, Train Acc: 5.215999856591225
使用 Keras 的机器翻译

Passons à la pratique !

使用 Keras 的机器翻译

Preparing Video For Download...