我正在尝试使用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: Error when checking model input: expected input_1 to have 3 dimensions, but got array with shape (1150, 50)
有没有人对这个问题有解决方案?
回答:
在定义模型之前使用data1 = np.expand_dims(data1, axis=2)
。LSTM期望输入的维度为(batch_size, timesteps, features)
,所以在你的情况下,我猜你有一个特征,50个时间步和1150个样本,你需要在你的向量末尾添加一个维度。
这需要在你定义模型之前完成,否则当你设置input_1 = Input(shape=data_1.shape)
时,你是在告诉Keras你的输入有1150个时间步和50个特征,所以它会期望输入的形状为(None, 1150, 50)
(这里的None表示“任何维度都可以接受”)。
对于input_2
也同样适用。
希望这对你有帮助。