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

Keras多输出ResNet模型训练:损失字典匹配异常问题

问题解决:Keras多输出ResNet模型报错修复

错误原因

你用Sequential模型构建多输出任务是错误的——Sequential是线性层堆叠结构,只能生成单个输出张量。你定义的前三个输出层(Boredom、Engagement、Confusion)的结果会被后续层覆盖,最终模型仅保留最后一个输出Frustration,所以编译时指定其他三个输出的损失函数就会提示“找不到对应输出”。

修正方案:改用函数式API

多输出模型必须用Keras函数式API构建,它支持从一个特征分支生成多个输出。修正后的代码如下:

from tensorflow import keras
from tensorflow.keras.applications import ResNet50
from tensorflow.keras import layers, models

# 加载预训练ResNet50作为基础模型
base_model = ResNet50(input_shape=(128, 128, 3),
                      include_top=False,
                      weights='imagenet')

# 构建特征提取部分
x = base_model.output
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dense(64, activation='relu')(x)

# 为四个标签分别创建输出分支
boredom_output = layers.Dense(4, activation='softmax', name='Boredom')(x)
engagement_output = layers.Dense(4, activation='softmax', name='Engagement')(x)
confusion_output = layers.Dense(4, activation='softmax', name='Confusion')(x)
frustration_output = layers.Dense(4, activation='softmax', name='Frustration')(x)

# 定义多输出模型
model = models.Model(inputs=base_model.input, 
                     outputs=[boredom_output, engagement_output, confusion_output, frustration_output])

# 编译模型,损失函数与输出对应
model.compile(optimizer='adam',
              loss={'Boredom': 'categorical_crossentropy',
                    'Engagement': 'categorical_crossentropy',
                    'Confusion': 'categorical_crossentropy',
                    'Frustration': 'categorical_crossentropy'},
              metrics={'Boredom': 'accuracy',
                       'Engagement': 'accuracy',
                       'Confusion': 'accuracy',
                       'Frustration': 'accuracy'})

model.summary()

额外注意事项

  • 你的标签是1-4的整数,训练前需要用keras.utils.to_categorical()转成one-hot编码,否则categorical_crossentropy损失会计算错误。
  • 如果需要冻结ResNet50的预训练权重,可以在加载后添加base_model.trainable = False,后续按需解冻部分层做微调。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:55:16