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

TensorFlow合并两个并行迁移学习模型时出错求助

解决并行迁移学习模型拼接的TypeError错误

错误原因

你直接将模型实例(base_model1、base_model2)传给了Concatenate层,但该层需要接收的是**张量(Tensor)**而非模型对象。Keras模型的输出张量需通过.output属性获取,直接传模型会触发符号张量转NumPy数组的错误。

修正后的代码

import tensorflow as tf
from tensorflow.keras.layers import Concatenate, Flatten, Dropout, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.applications import ResNet50V2, InceptionResNetV2

# 定义输入张量
input_tensor = tf.keras.layers.Input(shape=(300, 300, 3))

# 加载第一个预训练模型并冻结部分层
base_model1 = InceptionResNetV2(weights='imagenet', include_top=False, input_tensor=input_tensor)
for layer in base_model1.layers[:90]:
    layer.trainable = False

# 加载第二个预训练模型并冻结部分层
base_model2 = ResNet50V2(weights='imagenet', include_top=False, input_tensor=input_tensor)
for layer in base_model2.layers[:90]:
    layer.trainable = False

# 拼接两个模型的输出张量(关键修正:使用.output获取张量)
concat_output = Concatenate(axis=-1)([base_model1.output, base_model2.output])
# 展平特征
flatten_output = Flatten()(concat_output)
# Dropout正则化
dropout_output = Dropout(0.8)(flatten_output)
# 分类输出层
final_output = Dense(1, activation='sigmoid')(dropout_output)

# 构建完整模型
combine_model = Model(inputs=input_tensor, outputs=final_output)

关键修改点

  • 显式导入所有需要的Keras层和模型类,避免隐式依赖报错
  • 使用base_model1.output和base_model2.output获取模型的输出张量,替代直接传入模型实例
  • 规范Model类的参数命名:用inputs和outputs(符合Keras API规范)
  • 调整拼接轴为axis=-1(通道维度,更适合特征融合;若需按宽度维度拼接可改回axis=1,根据实际需求调整)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:41:59