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

TensorFlow多输出模型训练时无法显示各输出损失的问题

多输出模型训练仅显示总loss,无法查看各输出细分loss的解决方案

问题背景

运行Geron《Hands-On Machine Learning with Scikit Learn, Keras, and Tensorflow》(第三版)第10章WideAndDeepModel示例代码时:

  • 初始因metrics参数长度不匹配抛出ValueError,添加RootMeanSquaredError后解决;
  • 训练过程仅显示总loss和val_loss,无法看到各输出对应的output_1_loss、output_2_loss等细分指标,与文档预期不符。

已尝试的无效操作:移除metrics参数、更换子类模型实现、改用Functional API、设置verbose=2、调整输入形式、用字典配置loss/metrics、传入loss对象列表。

环境信息

  • Python 3.9
  • TensorFlow 2.17.0
  • Keras 3.4.1

核心原因与解决方案

问题出在Keras 3(TensorFlow 2.17绑定的Keras版本)对多输出模型的日志输出逻辑做了调整,默认不展示细分loss/metrics,需针对性配置:

1. 编译时明确为每个命名输出配置loss和metrics

确保输出层有唯一名称,编译时用字典映射每个输出对应的loss和metrics,示例:

# 子类模型中给输出层命名
class WideAndDeepModel(keras.Model):
    def __init__(self, units=30, activation="relu", **kwargs):
        super().__init__(**kwargs)
        self.hidden1 = keras.layers.Dense(units, activation=activation)
        self.hidden2 = keras.layers.Dense(units, activation=activation)
        self.main_output = keras.layers.Dense(1, name="main_pred")  # 命名输出
        self.aux_output = keras.layers.Dense(1, name="aux_pred")    # 命名输出

    def call(self, inputs):
        input_A, input_B = inputs
        hidden1 = self.hidden1(input_B)
        hidden2 = self.hidden2(hidden1)
        concat = keras.layers.concatenate([input_A, hidden2])
        return self.main_output(concat), self.aux_output(hidden2)

# 编译时用字典指定每个输出的loss和metrics
model.compile(
    optimizer="adam",
    loss={
        "main_pred": "mse",
        "aux_pred": "binary_crossentropy"
    },
    metrics={
        "main_pred": [keras.metrics.RootMeanSquaredError()],
        "aux_pred": [keras.metrics.Accuracy()]
    },
    loss_weights={"main_pred": 0.7, "aux_pred": 0.3}  # 可选,加权总loss
)

2. 关闭JIT编译并设置正确的verbose级别

Keras 3默认启用jit_compile=True,会压制细分指标的日志输出,训练时需关闭该选项:

model.fit(
    X_train, (y_main_train, y_aux_train),
    validation_data=(X_val, (y_main_val, y_aux_val)),
    epochs=10,
    verbose=1,  # verbose=1/2均可,1为进度条模式,2为epoch详情模式
    jit_compile=False
)

3. 确认模型输出结构

确保模型call方法返回的是多个独立张量(而非合并后的单一张量),若返回的是列表或元组,Keras会识别为多输出;若返回字典,需对应编译时的名称映射。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:40:14