神经机器翻译

使用 Keras 构建语言建模的循环神经网络(RNN)

David Cecchini

Data Scientist

编码器与解码器

神经机器翻译架构。该架构分为输入语言的编码器和输出语言的解码器。编码器学习输入语言的语言模型,解码器学习输出语言的语言模型。编码器的最终状态传递给没有其他输入的解码器。

使用 Keras 构建语言建模的循环神经网络(RNN)

编码器示例

# 实例化模型
model = Sequential()

# 输入语言的嵌入层 model.add(Embedding(input_language_size, input_wordvec_dim, input_length=input_language_len, mask_zero=True))
# 添加 LSTM 层 model.add(LSTM(128))
# 重复最后一个向量 model.add(RepeatVector(output_language_len))
使用 Keras 构建语言建模的循环神经网络(RNN)

解码器示例

# 紧接编码器之后
model.add(LSTM(128, return_sequences=True))

# 添加 TimeDistributed model.add(TimeDistributed(Dense(eng_vocab_size, activation='softmax')))
使用 Keras 构建语言建模的循环神经网络(RNN)

数据准备

编码器与解码器的文本准备。在编码器侧需将输入语言转为数值索引序列;在解码器侧同样处理输出语言,并对每个索引做 one-hot 编码

使用 Keras 构建语言建模的循环神经网络(RNN)

输入语言的数据准备

# 导入模块
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# 使用 Tokenizer 类
tokenizer = Tokenizer()
tokenizer.fit_on_texts(input_texts_list)

# 文本转为数值索引序列 X = tokenizer.texts_to_sequences(input_texts_list)
# 序列填充 X = pad_sequences(X, maxlen=length, padding='post')
使用 Keras 构建语言建模的循环神经网络(RNN)

对输出语言进行分词

# 使用 Tokenizer 类
tokenizer = Tokenizer()
tokenizer.fit_on_texts(output_texts_list)

# 文本转为数值索引序列 Y = tokenizer.texts_to_sequences(output_texts_list)
# 序列填充 Y = pad_sequences(Y, maxlen=length, padding='post')
使用 Keras 构建语言建模的循环神经网络(RNN)

对输出语言做 one-hot 编码

# 创建临时变量
ylist = list()

# 遍历数值索引序列 for sequence in Y:
# 对当前句子的每个索引做 one-hot 编码 encoded = to_categorical(sequence, num_classes=vocab_size)
# 将 one-hot 结果加入列表 ylist.append(encoded)
# 转为 np.array 并重塑 Y = np.array(ylist).reshape(Y.shape[0], Y.shape[1], vocab_size)
使用 Keras 构建语言建模的循环神经网络(RNN)

关于训练与评估

训练模型:

model.fit(X, Y, epochs=N)

评估:

  • 使用 BLEU
    • nltk.translate.bleu_score
使用 Keras 构建语言建模的循环神经网络(RNN)

Passons à la pratique !

使用 Keras 构建语言建模的循环神经网络(RNN)

Preparing Video For Download...