使用窗口数据集训练LSTM模型时出现错误

以下是我处理数据的代码:

WINDOW_SIZE = 8 # 前7天作为输入,接下来的第8天作为预期输出
BATCH_SIZE = 16
SHUFFLE_BUFFER = 10
dataset = Dataset.from_tensor_slices(israel_new)
# 输出 (167, )
dataset = dataset.window(WINDOW_SIZE, 1, drop_remainder=True)
dataset = dataset.flat_map(lambda x: x.batch(WINDOW_SIZE)) # 用于将窗口类型转换为张量类型
# 输出: (160, 8)
dataset = dataset.shuffle(SHUFFLE_BUFFER)
dataset = dataset.map(lambda x: (x[:-1], x[-1]))
# 输出 (160, 2)
dataset = dataset.batch(32).prefetch(1)
for x, y in dataset:
    print(x.numpy().shape, y.numpy().shape)
# >>> (32, 7) (32,)
# >>> (32, 7) (32,)
# >>> (32, 7) (32,)
# >>> (32, 7) (32,)
# >>> (32, 7) (32,)

这是我的模型:

inputs = Input((None, 7))
x = LSTM(64, return_sequences=True)(inputs)
x = LSTM(64)(x)
x = Dense(32, activation='relu')(x)
outputs = Dense(1)(x)
model = Model(inputs=inputs, outputs=outputs)
model.compile('adam', 'mse', metrics=['acc'])
model.fit(dataset, epochs=5)

当我尝试拟合模型时,出现了以下错误: Input 0 of layer lstm_43 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, None]

为什么会发生这种情况?


回答:

我找到了解决方案:

inputs = Input(7)
x = keras.layers.Reshape((7, 1))(inputs)

模型之前接收的输入是 (None, 7),这与数据集的形状 (32, 7) 不匹配,因为LSTM层需要在末尾增加一个额外的维度 (32, 7, 1),并且我们在指定输入形状时不指定批量大小,所以我们只是将输入从 (32, 7) 重塑为 (32, 7, 1),其中 32(批量大小)由Keras在后台处理。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注