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

# 实例化模型 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))
# 紧接编码器之后 model.add(LSTM(128, return_sequences=True))# 添加 TimeDistributed model.add(TimeDistributed(Dense(eng_vocab_size, activation='softmax')))

# 导入模块
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')
# 使用 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')
# 创建临时变量 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)
训练模型:
model.fit(X, Y, epochs=N)
评估:
nltk.translate.bleu_score使用 Keras 构建语言建模的循环神经网络(RNN)