You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将额外数据拼接至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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:07:38