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

TensorFlow中拼接含LSTM的双子模型:输入输出定义及代码运行求助

多分支LSTM模型构建修正方案

原代码存在的核心问题

  • sub_model1函数返回值错误:model.add()方法返回None,导致model1、model2无法作为有效层参与后续拼接
  • 未定义模型输入层:多分支模型需为每个分支创建独立Input层,明确输入维度
  • 训练数据传入逻辑错误:多输入模型训练时需传入对应分支的训练数据列表

修正后的完整代码

import numpy as np
import tensorflow as tf
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, Input, concatenate

# 生成模拟训练数据
X_train1 = np.random.randint(10, size=(10, 20, 28))
X_train2 = np.random.randint(10, size=(10, 10, 28))
# 最终输出为28维标签,这里以Y_train作为示例训练目标
Y_train = np.random.randint(10, size=(10, 28))

# 重构子模型:接收输入形状与输出维度,返回完整模型
def build_sub_model(input_shape, output_dim):
    model = Sequential()
    model.add(LSTM(100, activation='linear', input_shape=input_shape, return_sequences=True))
    model.add(LSTM(32, activation='linear', return_sequences=False))
    model.add(Dense(100, activation='linear'))
    model.add(Dense(output_dim, activation='linear'))
    return model

# 定义两个分支的输入层,匹配各自训练数据的维度
input1 = Input(shape=(X_train1.shape[1], X_train1.shape[2]))
input2 = Input(shape=(X_train2.shape[1], X_train2.shape[2]))

# 构建子模型并连接到对应输入层
sub_model1 = build_sub_model((X_train1.shape[1], X_train1.shape[2]), 28)
sub_model2 = build_sub_model((X_train2.shape[1], X_train2.shape[2]), 28)
output1 = sub_model1(input1)
output2 = sub_model2(input2)

# 拼接两个子模型的输出结果
concat_layer = concatenate([output1, output2])
# 定义最终输出层
final_output = Dense(28, activation="linear")(concat_layer)

# 构建完整模型:指定输入集合与最终输出
model = Model(inputs=[input1, input2], outputs=final_output)

# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['MAE'])

# 训练模型:传入两个分支的训练数据与目标标签
history = model.fit([X_train1, X_train2], Y_train, epochs=2, batch_size=10)

关键修正说明

  1. 子模型函数返回完整的Sequential模型,避免返回None导致的拼接错误
  2. 通过Input层明确每个分支的输入形状,符合Keras函数式API的多分支模型构建规范
  3. 训练时传入输入数据列表[X_train1, X_train2],与模型定义的输入层一一对应
  4. 调整batch_size为10(匹配训练数据总量),避免批次大小超出数据量的报错

内容的提问来源于stack exchange,提问作者Sadcow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:02:23