我正在尝试实现一个多输入的 LSTM-DNN 混合模型,其中两个层的输出会被拼接。不幸的是,在开始训练后立即出现了这个问题:
ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with shape (32, 168, 5)
我研究了其他方法,但大多数情况是得到的数组维度比预期的小。我读到使用 flatten 可能会有帮助,但我还不确定如何实现它。
这是我的模型:
# first input modelinput_1 = Input(shape=(5, ))input_1_expand = tf.expand_dims(input_1, axis=-1) dense_1 = Dense(units=64, input_shape=(None, 5,))(input_1_expand)# second input modelinput_2 = Input(shape=(7, ))input_2_expand = tf.expand_dims(input_2, axis=-1)lstm_1 = LSTM(units=64, return_sequences=True, input_shape=(None, 7,))(input_2_expand)# merge input modelsmerge = concatenate([dense_1, lstm_1], axis=1)output = Dense(num_y_signals, activation='sigmoid')(merge)model = Model(inputs=[input_1, input_2], outputs=output)# summarize layersprint(model.summary())
模型训练如下:
%timemodel.fit_generator(generator=generator, epochs=10, steps_per_epoch=30, validation_data=validation_data, callbacks=callbacks)
其中 generator 是一个 batch_generator 函数,产生
[x_batch_1, x_batch_2], y_batch
x_batch_1 shape: (32, 168, 5)x_batch_2 shape: (32, 168, 7)y_batch shape: (32, 168, 1)
其中 32 是批量大小,168 是序列长度
我也不确定我如何实现 tf.expand 和 concatenate 的轴。我只是尝试了能够让模型编译的组合
编辑:我忘了包含验证数据:
validation_data = ([np.expand_dims(x_test1_scaled, axis=0), np.expand_dims(x_test2_scaled, axis=0)], np.expand_dims(y_test_scaled, axis=0))
其中
expanded x_test1_scaled Shape: (1, 5808, 5)expanded x_test2_scaled Shape: (1, 5808, 7)expanded y_test_scaled Shape: (1, 5808, 1)
回答:
你需要将序列长度
也放入输入形状中,形状必须与x_batch.shape[1:]
相同
像这样
input_1 = Input(shape=(168, 5, ))dense_1 = Dense(units=64, input_shape=(None, 5,))(input_1)input_2 = Input(shape=(168, 7, ))lstm_1 = LSTM(units=64, return_sequences=True, input_shape=(None, 7,))(input_2)
我猜你尝试使用expand_dims
来修复这个问题,所以我没有包括那个部分。