了解在 LSTM(动态 RNN)中使用的张量输入和转换

Understanding Tensor Inputs & Transformations for use in an LSTM (dynamic RNN)

我正在 Tensorflow 中构建一个 LSTM 风格的神经网络,我很难准确理解需要什么输入以及 tf.nn.dynamic_rnn 在输入之前进行的后续转换传递到 sparse_softmax_cross_entropy_with_logits 层。

https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn

理解输入

输入函数正在发送形式为

的特征张量

[batch_size, max_time]

但是手册规定输入张量必须采用

形式

[batch_size, max_time, ...]

因此,我用一维张量扩展了输入,以采用

的形式

[batch_size, max_time, 1]

此时输入没有中断 运行,但我不明白我们在这里做了什么,怀疑它可能会导致计算损失时出现问题(见下文)。

了解转换

这个展开的张量就是下面代码中使用的'features'张量

LSTM_SIZE = 3
lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias=1.0)
outputs, _ = tf.nn.dynamic_rnn(lstm_cell, features, dtype=tf.float64)

#slice to keep only the last cell of the RNN
outputs = outputs[-1]

#softmax layer

with tf.variable_scope('softmax'):
   W = tf.get_variable('W', [LSTM_SIZE, n_classes], dtype=tf.float64)
   b = tf.get_variable('b', [n_classes], initializer=tf.constant_initializer(0.0), dtype=tf.float64)

logits = tf.matmul(outputs, W) + b

loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels))

这会在 loss

处引发值错误

尺寸必须相等,但是 [max_time、num_classes] 和 [batch_size]

来自https://www.tensorflow.org/versions/r0.12/api_docs/python/nn/classification-

一个常见的用例是具有形状 [batch_size、num_classes] 的逻辑和形状 [batch_size] 的标签。但支持更高的维度。

在过程中的某个时刻,max_time 和 batch_size 混淆了,我不确定它是在输入时还是在 LSTM 期间。我很感激任何建议!

那是因为 tf.nn.dynamic_rnn 输出的形状。从其文档 https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn:

输出:RNN 输出张量。

如果 time_major == False(默认),这将是张量形状:[batch_size、max_time、cell.output_size].

如果 time_major == True,这将是张量形状:[max_time、batch_size、cell.output_size].

您处于默认情况下,因此您的 outputs 气体形状 [batch_size, max_time, output_size],并且在执行 outputs[-1] 时您获得形状为 [max_time, output_size] 的张量。可能用 outputs[:, -1] 切片应该可以解决它。