首页 > 解决方案 > RNN 输入的哪个轴被用作 Keras 中的“时间”轴?

问题描述

当使用 SimpleRNN 或 LSTM 进行经典情感分析算法时(此处适用于长度 <= 250 个单词/标记的句子):

model = Sequential()
model.add(Embedding(5000, 32, input_length=250))   # Output shape: (None, 250, 32)
model.add(SimpleRNN(100))                          # Output shape: (None, 100)
model.add(Dense(1, activation='sigmoid'))          # Output shape: (None, 1)

在哪里指定RNN输入的哪个轴作为“时间”轴?

更准确地说,在 Embedding 层之后,给定的输入句子,例如“the cat sat on the mat”,被编码为形状为 (250, 32) 的矩阵 x,其中 250 是最大长度(以单词为单位)输入文本,以及 32 嵌入的维度。然后,在 Keras 中的哪个位置指定是否使用它:

h[t] = activation( W_h * x[:, t] + U_h * h[t-1] + b_h )

或这个:

h[t] = activation( W_h * x[t, :] + U_h * h[t-1] + b_h )

(在这两种情况下,y[t] = activation( W_y * h[t] + b_y )

TL;DR:如果 RNN Keras 层的输入大小为 (250, 32),默认情况下它使用哪个轴作为时间轴?Keras 或 Tensorflow 文档中的详细说明在哪里?

标签: classificationtensorflowkerasmodel

解决方案


该方程式h[t] = activation( W_h * x[t, :] + U_h * h[t-1] + b_h )将由Keras或使用Tensorflow

在这个Tensorflow 文档中,提到了

inputs: A 3D tensor, with shape [batch, timesteps, feature].

我们将忽略第一个参数,batch并在一段时间内考虑其余的两个参数。

在情感分析的情况下,我们可以将每个word/token(转换为向量)视为一个Timestep,如下面的屏幕截图所示。

如果您的示例使用形状为 (250, 32) 的编码矩阵,则意味着每个 Review 或 Instance 有 250words/tokensTimesteps.

所以,方程,h[t] = activation( W_h * x[t, :] + U_h * h[t-1] + b_h )可以翻译为

h[t] = activation( W_h * x[Each Time Step/Word, All Features] + U_h * h[Previous Time Step/Word] + b_h )

在此处输入图像描述

希望这能澄清你的问题。快乐学习!


推荐阅读