Keras 中的 LSTM 输入维度问题

Issue in LSTM Input Dimensions in Keras

我正在尝试使用 keras 实现多输入 LSTM 模型。代码如下:

data_1 -> shape (1150,50) 
data_2 -> shape (1150,50)
y_train -> shape (1150,50)

input_1 = Input(shape=data_1.shape)
LSTM_1 = LSTM(100)(input_1)

input_2 = Input(shape=data_2.shape)
LSTM_2 = LSTM(100)(input_2)

concat = Concatenate(axis=-1)
x = concat([LSTM_1, LSTM_2])
dense_layer = Dense(1, activation='sigmoid')(x)
model = keras.models.Model(inputs=[input_1, input_2], outputs=[dense_layer])

model.compile(loss='binary_crossentropy',
                      optimizer='adam',
                      metrics=['acc'])

model.fit([data_1, data_2], y_train, epochs=10)

当我 运行 这段代码时,我得到一个 ValueError:

ValueError:检查模型输入时出错:预期 input_1 有 3 个维度,但得到的数组形状为 (1150, 50)

有人有办法解决这个问题吗?

在定义模型之前使用 data1 = np.expand_dims(data1, axis=2)LSTM 期望输入的维度为 (batch_size, timesteps, features),因此,在您的情况下,我猜您有 1 个特征、50 个时间步长和 1150 个样本,您需要在向量末尾添加一个维度。

这需要在定义模型之前完成,否则当您设置 input_1 = Input(shape=data_1.shape) 时,您是在告诉 keras 您的输入有 1150 个时间步长和 50 个特征,因此它期望输入的形状为 (None, 1150, 50) (非代表 "any dimension will be accepted")。

input_2

也是如此

希望对您有所帮助