无法将额外数据拼接至CNN+LSTM架构的技术求助
CNN + LSTM 网络拼接额外输入的问题修正
你的代码存在三个核心问题,直接导致拼接失败:
- Concatenate层调用错误:Keras中需要先实例化
Concatenate()层,再传入待拼接的张量列表,而非直接将张量作为参数传入 - 形状不匹配:CNN输出经过
TimeDistributed(Flatten())后带有时序维度,而气象数据输入是一维张量,需要扩展为相同的时序维度才能拼接 - 模型输入未包含额外输入:构建Model时需要同时传入
cnn_input和weather_input作为输入源
以下是修正后的完整代码:
from tensorflow.keras.layers import ( Input, Conv2D, MaxPooling2D, TimeDistributed, Flatten, Dense, Concatenate, LSTM, RepeatVector ) from tensorflow.keras.models import Model # CNN 分支 cnn_input = Input(shape=(256, 256, 3), name="cnn_input") cnn_layer1 = Conv2D(32, (3, 3), strides=1, padding="same", activation="relu")(cnn_input) cnn_layer1_pooling = MaxPooling2D((2, 2), strides=2, padding="same")(cnn_layer1) cnn_layer2 = Conv2D(64, (3, 3), strides=1, padding="same", activation="relu")(cnn_layer1_pooling) cnn_layer2_pooling = MaxPooling2D((2, 2), strides=2, padding="same")(cnn_layer2) cnn_layer3 = Conv2D(128, (3, 3), strides=1, padding="same", activation="relu")(cnn_layer2_pooling) cnn_layer3_pooling = MaxPooling2D((2, 2), strides=2, padding="same")(cnn_layer3) cnn_layer4 = Conv2D(256, (3, 3), strides=1, padding="same", activation="relu")(cnn_layer3_pooling) # 经3次池化后,特征图尺寸为32×32,TimeDistributed展平后得到时序维度为32的张量 cnn_output = TimeDistributed(Flatten())(cnn_layer4) cnn_output_dense = Dense(700, activation="relu")(cnn_output) # 气象数据输入分支 weather_input = Input(shape=(4,), name="weather_input") # 将气象数据扩展为与CNN输出相同的时序维度(32),形状变为(None, 32, 4) weather_repeated = RepeatVector(32)(weather_input) # 可选:将气象数据映射到和CNN输出一致的特征维度 weather_processed = Dense(700, activation="relu")(weather_repeated) # 拼接两个分支的输出 merged = Concatenate()([cnn_output_dense, weather_processed]) # LSTM 分支 lstm_layer1 = LSTM(64, return_sequences=True)(merged) lstm_layer2 = LSTM(32, return_sequences=True)(lstm_layer1) lstm_output = LSTM(32)(lstm_layer2) # 最终输出层 dense_output = Dense(2, activation="softmax")(lstm_output) # 构建模型,包含两个输入源 model = Model(inputs=[cnn_input, weather_input], outputs=dense_output) model.compile( loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"] ) model.summary()
补充说明:
- 如果你的时序维度来自其他设置(而非特征图尺寸),需要调整
RepeatVector的参数为对应的时序长度 - 将气象数据映射到和CNN输出相同的特征维度,能让拼接后的特征分布更统一,有助于模型收敛
内容的提问来源于stack exchange,提问作者GentleNam
相关产品推荐
相关产品推荐

