keras LSTM,维度必须相等,不同的窗口大小

14ifxucb  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(86)

我正在训练LSTM模型来预测时间序列数据。我的模型的输出形状有问题。我的模型在输入窗口大小小于或等于输出窗口大小时有效。但是,当输出窗口大小大于输入窗口大小时,它不起作用。
这是什么意思?假设我有x和y。

# shape = (# of samples, Window Size, # of Features)
x = np.random.random((100, 5, 8))
y = np.random.random((100, 15, 8))

在我的数据集中,我用之前的5个数据点预测接下来的15个数据点。x0 ~ x4 -> x5 ~ x19。形状与上面的numpy数组相同。
我的LSTM架构看起来像这样。

my_model = Sequential(
        [
            tf.keras.layers.LSTM(
                32,
                input_shape=x.shape[-2:], # (N, # of features)
                return_sequences=True,
            ),
            tf.keras.layers.Dropout(0.1),
            tf.keras.layers.LSTM(18, return_sequences=True),
            tf.keras.layers.Dropout(0.1),
            tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(x.shape[-1])),
            tf.keras.layers.Lambda(lambda x: x[:, -y.shape[-1]:, :])  # Adjust output shape
        ]
    )

当X的窗口大小小于或等于Y的窗口大小时,模型可以完美地工作。但是,使用提供的x和y,模型给出(None,5,8)作为其输出,我不知道为什么会这样。如何调整我的LSTM模型,以适应任何类型的输入和输出窗口大小?
非常感谢。
我试着在这里查找先前的问题,但我找不到我的解决方案。我试着删除一些层,但基本上我不能使输出窗口的大小大于输入窗口的大小。

2mbi3lxu

2mbi3lxu1#

正如我所理解的,你需要调整你的模型层以获得最终的输出形状(15,8),这可以通过添加一些新的Dense层来扩展第二个LSTM的输出,然后将其重塑为(15,8)。

my_model = Sequential(
        [
            tf.keras.layers.LSTM(
                32,
                input_shape=x.shape[-2:], # (N, # of features)
                return_sequences=True,
            ),
            tf.keras.layers.Dropout(0.1),
            tf.keras.layers.LSTM(18, return_sequences=True),
            tf.keras.layers.Dropout(0.1),
            tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(x.shape[-1])),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(15 * 8),
            tf.keras.layers.Reshape((15, 8)),
            tf.keras.layers.Dense(8)
        ]
    )

虽然输出形状现在匹配你的y数组,但我不确定这个架构是否会被有效地训练,但至少你可以稍后再次修改它。

相关问题