以下是我处理数据的代码:
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在后台处理。