使用窗口数据集训练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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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