【问题标题】:Error when trying to train LSTM model with windowed dataset尝试使用窗口数据集训练 LSTM 模型时出错
【发布时间】:2020-07-08 12:14:42
【问题描述】:

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

WINDOW_SIZE = 8 # Previous 7 days are inputs and the following day (8th) is the expected output 
BATCH_SIZE = 16
SHUFFLE_BUFFER = 10

dataset = Dataset.from_tensor_slices(israel_new)
# Output (167, )

dataset = dataset.window(WINDOW_SIZE, 1, drop_remainder=True)
dataset = dataset.flat_map(lambda x: x.batch(WINDOW_SIZE)) # Used to change the type from Window to Tensor
# Output: (160, 8)

dataset = dataset.shuffle(SHUFFLE_BUFFER)
dataset = dataset.map(lambda x: (x[:-1], x[-1]))
# Output (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]

为什么会这样?

【问题讨论】:

  • 为什么要Input((None, 7)) 而不是实际尺寸?
  • @mabergerx 你的意思是我为什么使用 Input 对象?和指定 input_shape 一样,只是更容易阅读。
  • 不,我的意思是为什么你把明确的None 放在那里,而不是遵循Input(shape=(32, 7)) 的语法?
  • @mabergerx 我是初学者,但据我所知,您没有在输入形状中指定批量大小,它是由 Keras 在后台推断的,我尝试了 (32, 7) 并且只是(7) 但不幸的是,两者都不起作用。

标签: python tensorflow machine-learning keras artificial-intelligence


【解决方案1】:

我找到了解决办法:

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

模型之前收到(None, 7) 的输入,它与数据集(32, 7) 的形状不对应,因为LSTM 层在末尾需要一个额外的1 维(32, 7, 1),并且我们没有指定批量大小在给出输入形状时,我们只需将输入从 (32, 7) 重塑为 (32, 7, 1),其中 32 (batch size) 由 Keras 在后台处理。

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    • 2018-01-30
    • 2020-12-15
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多