前面讲到seq2seq,网上有很多seq2seq的例子,今天具体解析一下keras的seq2seq(character-level)例子,代码是keras的github上的地址:
https://github.com/keras-team/keras/blob/master/examples/lstm_seq2seq.py
前言
'''
Keras(字符级)中的序列到序列示例。这个脚本演示了如何实现基本的字符级sequence-to-sequence模型。我们把它应用到翻译中英语短句变成法语短句,character-by-character。请注意,这是相当不通常的做character机器翻译,在这个领域更为常见的用word级做模型。
**算法概要**
我们从一个领域的输入序列开始(例如英语句子),以及来自另一个领域的相应目标序列(例如法国的句子)。
编码器LSTM将输入序列转换为两个状态向量(我们保留最后一个LSTM状态并丢弃输出)。
训练解码器LSTM将目标序列转换为相同的序列,但在未来被一个时间步长抵消,在这种情况下,训练过程称为“teacher forcing”。
它使用编码器的状态向量作为初始状态。有效地,解码器学习生成“目标[t+1…]” 给定的目标[…t]’,是输入序列。
-在推理模式下,当我们要解码未知输入序列时,我们:
-将输入序列编码为状态向量
-从大小为1的目标序列开始(只是序列开始的字符)
-将状态向量和1个字符的目标序列输入解码器,以生成下一个字符的预测
-使用这些预测对下一个字符进行采样(我们只使用argmax)。
-将采样的字符追加到目标序列
-重复,直到生成序列结束字符或达到字符限制。
* * * *数据下载
英语到法语的句子对。
)(http://www.manythings.org/anki/fra-eng.zip)
许多简洁的句子对数据集。
)(http://www.manythings.org/anki/)
* * * *参考文献
-使用神经网络进行seq2seq的学习(https://arxiv.org/abs/1409.3215)
-学习短语表达使用于统计机器翻译的RNN编解码器(https://arxiv.org/abs/1406.1078)
'''
注:teacher forcing:最初出自于《deep learning》,在MT && Abstractive Summarization的encoder训练中比较常用,先mark,有空来写。Teacher Forcing是一种用来训练循环神经网络模型的方法,这种方法以上一时刻的输出作为下一时刻的输入。该方法最初被描述和发展,从而作为一种用于训练循环神经网络的反向传播的替代技术。在训练时,Teacher forcing是通过使用第t时刻的来自于训练集的期望输出y(t)作为下一时刻的输入x(t+1),而不是直接使用网络的实际输出。
1.数据预处理,首先下载数据
from __future__ import print_function
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
batch_size = 64 # Batch size for training.训练梯度大小
epochs = 100 # Number of epochs to train for.迭代次数
latent_dim = 256 # Latent dimensionality of the encoding space.编码空间的潜在维数
num_samples = 10000 # Number of samples to train on.样本数
# Path to the data txt file on disk.数据地址
data_path = 'fra-eng/fra.txt'
# Vectorize the data.向量化数据
input_texts = []
target_texts = []
input_characters = set()
target_characters = set()
with open(data_path, 'r', encoding='utf-8') as f:
lines = f.read().split('\n')
for line in lines[: min(num_samples, len(lines) - 1)]:
input_text, target_text = line.split('\t')
# We use "tab" as the "start sequence" character 使用"tab"作为开始
# for the targets, and "\n" as "end sequence" character. 使用"\n"作为结束
target_text = '\t' + target_text + '\n'
input_texts.append(input_text)
target_texts.append(target_text)
for char in input_text:
if char not in input_characters:
input_characters.add(char)
for char in target_text:
if char not in target_characters:
target_characters.add(char)
input_characters = sorted(list(input_characters))
target_characters = sorted(list(target_characters))
num_encoder_tokens = len(input_characters)
num_decoder_tokens = len(target_characters)
max_encoder_seq_length = max([len(txt) for txt in input_texts])
max_decoder_seq_length = max([len(txt) for txt in target_texts])
print('Number of samples:', len(input_texts))
print('Number of unique input tokens:', num_encoder_tokens)
print('Number of unique output tokens:', num_decoder_tokens)
print('Max sequence length for inputs:', max_encoder_seq_length)
print('Max sequence length for outputs:', max_decoder_seq_length)
input_token_index = dict(
[(char, i) for i, char in enumerate(input_characters)])
target_token_index = dict(
[(char, i) for i, char in enumerate(target_characters)])
encoder_input_data = np.zeros(
(len(input_texts), max_encoder_seq_length, num_encoder_tokens),
dtype='float32')
decoder_input_data = np.zeros(
(len(input_texts), max_decoder_seq_length, num_decoder_tokens),
dtype='float32')
decoder_target_data = np.zeros(
(len(input_texts), max_decoder_seq_length, num_decoder_tokens),
dtype='float32')
结果:
Number of samples: 10000
Number of unique input tokens: 70
Number of unique output tokens: 93
Max sequence length for inputs: 16
Max sequence length for outputs: 59
所以encoder_input_data (10000,16,70) decoder_input_data (10000,59,93) decoder_target_data (10000,59,93)
2. 字符向量化(one-hot)
for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):
for t, char in enumerate(input_text):
encoder_input_data[i, t, input_token_index[char]] = 1.
for t, char in enumerate(target_text):
# decoder_target_data is ahead of decoder_input_data by one timestep
# decoder_target_data领先一个时间步长
decoder_input_data[i, t, target_token_index[char]] = 1.
if t > 0:
# decoder_target_data will be ahead by one timestep
# and will not include the start character.
# decoder_target_data不包括开始向量
decoder_target_data[i, t - 1, target_token_index[char]] = 1.
每个target_text都加了两个字符:'\t'和'\n'
而decoder_target_data不包括开始字符
3. encoder-decoder
# Define an input sequence and process it.
# 定义一个输入序列并处理它。
encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
# 丢弃encoder_outputs,只保留states
encoder_states = [state_h, state_c]
# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
# 开始解码,使用encoder_states作为初始状态,我们设置解码器返回完整的输出序列,并返回内部状态。
# 我们在训练模型中不使用返回状态,但我们将在推理中使用它们。
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model that will turn
# 定义将要运行的模型
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
# 使用encoder_input_data和decoder_input_data返回decoder_target_data
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
# Run training 进行训练
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2)
# Save model 保存模型
model.save('s2s.h5')
4. 推理模式
# Next: inference mode (sampling).
# 下一步:推理模式(采样)。
# Here's the drill:
# 练习:
# 1) encode input and retrieve initial decoder state
# 1) 编码输入和检索初始解码器状态
# 2) run one step of decoder with this initial state
# and a "start of sequence" token as target.
# Output will be the next target token
# 2) 以这个初始状态和一个“序列开始”分词为目标运行一步解码器。输出将是下一个目标分词
# 3) Repeat with the current target token and current states
# 3) 重复当前目标分词和当前状态
# Define sampling models
# 定义抽样模型
encoder_model = Model(encoder_inputs, encoder_states)
decoder_state_input_h = Input(shape=(latent_dim,))
decoder_state_input_c = Input(shape=(latent_dim,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(
decoder_inputs, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model(
[decoder_inputs] + decoder_states_inputs,
[decoder_outputs] + decoder_states)
# Reverse-lookup token index to decode sequences back to
# something readable.
# 反向查找分词索引(词的编号)将序列解码为可读的。
reverse_input_char_index = dict(
(i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict(
(i, char) for char, i in target_token_index.items())
5. 定义解码序列
def decode_sequence(input_seq):
# Encode the input as state vectors.
# 将输入编码为状态向量。
states_value = encoder_model.predict(input_seq)
# Generate empty target sequence of length 1.
# 生成长度为1的空目标序列。
target_seq = np.zeros((1, 1, num_decoder_tokens))
# Populate the first character of target sequence with the start character.
# 用开始字符填充目标序列的第一个字符。
target_seq[0, 0, target_token_index['\t']] = 1.
# Sampling loop for a batch of sequences
# (to simplify, here we assume a batch of size 1).
# 对一个批次序列进行采样循环(为了简化,这里我们假设一批序列的大小为1)。
stop_condition = False
decoded_sentence = ''
while not stop_condition:
output_tokens, h, c = decoder_model.predict(
[target_seq] + states_value)
# Sample a token
# 抽样分词
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence += sampled_char
# Exit condition: either hit max length
# or find stop character.
# 退出条件:到最大长度或找到停止字符。
if (sampled_char == '\n' or
len(decoded_sentence) > max_decoder_seq_length):
stop_condition = True
# Update the target sequence (of length 1).
# 更新目标序列(长度1)
target_seq = np.zeros((1, 1, num_decoder_tokens))
target_seq[0, 0, sampled_token_index] = 1.
# Update states
# 更新状态
states_value = [h, c]
return decoded_sentence
for seq_index in range(100):
# Take one sequence (part of the training set)
# for trying out decoding.
# 取一个序列(训练集的一部分)来尝试解码。
input_seq = encoder_input_data[seq_index: seq_index + 1]
decoded_sentence = decode_sequence(input_seq)
print('-')
print('Input sentence:', input_texts[seq_index])
print('Decoded sentence:', decoded_sentence)