在 Keras 中使用 RNN 简介

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

David Cecchini

Data Scientist

什么是 Keras?

  • 高层 API

  • 运行于 TensorFlow 2 之上

  • 安装和使用简单

$pip install tensorflow

快速试验:

from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
使用 Keras 构建语言建模的循环神经网络(RNN)

keras.models

keras.models.Sequential

展示 Keras Sequential 类的宏观示意。各层按顺序从输入到输出堆叠。

keras.models.Model

展示 Keras Model 类的宏观示意。可有多个输入和输出,支持更复杂的架构。

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

keras.layers

  1. LSTM
  2. GRU
  3. Dense
  4. Dropout
  5. Embedding
  6. Bidirectional
使用 Keras 构建语言建模的循环神经网络(RNN)

keras.preprocessing

keras.preprocessing.sequence.pad_sequences(texts, maxlen=3)

填充文本示例。若文本少于填充长度,会在开头补"0";若多于长度,将截去句子末尾多余词。

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

keras.datasets

许多有用的数据集

  • IMDB 影评
  • Reuters 新闻稿

以及更多!

完整列表和用法示例见 Keras 文档

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

创建模型

# Import required modules
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Instantiate the model class
model = Sequential()
# Add the layers
model.add(Dense(64, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
使用 Keras 构建语言建模的循环神经网络(RNN)

训练模型

.fit() 方法在训练集上训练模型

model.fit(X_train, y_train, epochs=10, batch_size=32)
  1. epochs:模型权重更新次数
  2. batch_size:每步的数据量
使用 Keras 构建语言建模的循环神经网络(RNN)

模型评估与使用

评估模型

model.evaluate(X_test, y_test)
[0.3916562925338745, 0.89324]

对新数据预测

model.predict(new_data)
array([[0.91483957],[0.47130653]], dtype=float32)
使用 Keras 构建语言建模的循环神经网络(RNN)

完整示例:IMDB 情感分类

# Build and compile the model
model = Sequential()

model.add(Embedding(10000, 128)) model.add(LSTM(128, dropout=0.2)) model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Training
model.fit(x_train, y_train, epochs=5)
# Evaluation
score, acc = model.evaluate(x_test, y_test)
使用 Keras 构建语言建模的循环神经网络(RNN)

该练习了!

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

Preparing Video For Download...