Keras中LSTM层的输入维度

The input dimension of the LSTM layer in Keras

我正在尝试 keras.layers.LSTM。 以下代码有效。

#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow import keras

data = np.array([1, 2, 3]).reshape((1, 3, 1)) 
x = keras.layers.Input(shape=(3, 1)) 
y = keras.layers.LSTM(10)(x)
model = keras.Model(inputs=x, outputs=y)

print (model.predict(data))

如上图,输入数据shape为(1, 3, 1),Input层实际输入shape为(3, 1)。我对维度的这种不一致感到有点困惑。 如果我在输入层中使用以下形状,它不起作用:

x = keras.layers.Input(shape=(1, 3, 1)) 

报错信息如下:

ValueError: Input 0 of layer lstm is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: [None, 1, 3, 1]

好像输入的rank必须是3,但是为什么要在Input层使用rank-2的形状呢?

查看 tf.keras.Input 的文档。语法为-

tf.keras.Input(
    shape=None,
    batch_size=None,
    name=None,
    dtype=None,
    sparse=False,
    tensor=None,
    **kwargs
)

shape: 定义单个样本的形状,批量大小可变。

注意,它期望第一个值为 batch_size 否则将 batch_size 作为参数显式传递

Keras 使用 "batches" 个 "samples"。由于大多数模型使用您仅在拟合时定义的可变批量大小,为方便起见,您无需关心批量维度,而只需关心样本维度。

也就是说,当您使用 shape = (3,1) 时,这与定义 batch_shape = (None, 3, 1)batch_input_shape = (None, 3, 1) 相同。

三个选项的意思是:

  • 可变批量大小:None
  • 具有形状 (3, 1) 的样本。

了解这种区别很重要,尤其是当您要创建自定义层、损失或指标时。实际的张量都有批量维度,在使用张量进行操作时应该考虑到这一点。