Keras 中的循环神经网络 (RNN)

在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 上查看源代码 下载笔记本

简介

循环神经网络 (RNN) 是一类神经网络,它们在序列数据(如时间序列或自然语言)建模方面非常强大。

简单来说,RNN 层会使用 for 循环对序列的时间步骤进行迭代,同时维持一个内部状态,对截至目前所看到的时间步骤信息进行编码。

Keras RNN API 的设计重点如下:

  • 易于使用:您可以使用内置 keras.layers.RNNkeras.layers.LSTMkeras.layers.GRU 层快速构建循环模型,而无需进行艰难的配置选择。

  • 易于自定义:您还可以通过自定义行为来定义您自己的 RNN 单元层(for 循环的内部),并将其用于通用的 keras.layers.RNN 层(for 循环本身)。这使您能够以最少的代码和灵活的方式快速为不同研究思路设计原型。

设置

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
2022-12-14 21:28:27.340713: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 21:28:27.340807: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 21:28:27.340816: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

内置 RNN 层:简单示例

Keras 中有三种内置 RNN 层:

  1. keras.layers.SimpleRNN,一个全连接 RNN,其中前一个时间步骤的输出会被馈送至下一个时间步骤。

  2. keras.layers.GRU,最初由 Cho 等人于 2014 年提出。

  3. keras.layers.LSTM,最初由 Hochreiter 和 Schmidhuber 于 1997 年提出。

2015 年初,Keras 首次具有了 LSTM 和 GRU 的可重用开源 Python 实现。

下面是一个 Sequential 模型的简单示例,该模型可以处理整数序列,将每个整数嵌入 64 维向量中,然后使用 LSTM 层处理向量序列。

model = keras.Sequential()
# Add an Embedding layer expecting input vocab of size 1000, and
# output embedding dimension of size 64.
model.add(layers.Embedding(input_dim=1000, output_dim=64))

# Add a LSTM layer with 128 internal units.
model.add(layers.LSTM(128))

# Add a Dense layer with 10 units.
model.add(layers.Dense(10))

model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 embedding (Embedding)       (None, None, 64)          64000     
                                                                 
 lstm (LSTM)                 (None, 128)               98816     
                                                                 
 dense (Dense)               (None, 10)                1290      
                                                                 
=================================================================
Total params: 164,106
Trainable params: 164,106
Non-trainable params: 0
_________________________________________________________________

内置 RNN 支持许多实用功能:

  • 通过 dropoutrecurrent_dropout 参数进行循环随机失活
  • 能够通过 go_backwards 参数反向处理输入序列
  • 通过 unroll 参数进行循环展开(这会大幅提升在 CPU 上处理短序列的速度)
  • …以及更多功能。

有关详情,请参阅 RNN API 文档

输出和状态

默认情况下,RNN 层的输出为每个样本包含一个向量。此向量是与最后一个时间步骤相对应的 RNN 单元输出,包含关于整个输入序列的信息。此输出的形状为 (batch_size, units),其中 units 对应于传递给层构造函数的 units 参数。

如果您设置了 return_sequences=True,RNN 层还能返回每个样本的整个输出序列(每个样本的每个时间步骤一个向量)。此输出的形状为 (batch_size, timesteps, units)

model = keras.Sequential()
model.add(layers.Embedding(input_dim=1000, output_dim=64))

# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)
model.add(layers.GRU(256, return_sequences=True))

# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)
model.add(layers.SimpleRNN(128))

model.add(layers.Dense(10))

model.summary()
Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 embedding_1 (Embedding)     (None, None, 64)          64000     
                                                                 
 gru (GRU)                   (None, None, 256)         247296    
                                                                 
 simple_rnn (SimpleRNN)      (None, 128)               49280     
                                                                 
 dense_1 (Dense)             (None, 10)                1290      
                                                                 
=================================================================
Total params: 361,866
Trainable params: 361,866
Non-trainable params: 0
_________________________________________________________________

此外,RNN 层还可以返回其最终内部状态。返回的状态可用于稍后恢复 RNN 执行,或初始化另一个 RNN。此设置常用于编码器-解码器序列到序列模型,其中编码器的最终状态被用作解码器的初始状态。

要配置 RNN 层以返回其内部状态,请在创建该层时将