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

TensorFlow 2.17.0模型指标未正常识别:仅显示['loss','compile_metrics']

问题原因

在Keras 3.x(TensorFlow 2.15及以上版本默认集成)中,model.metrics和model.metrics_names的行为发生了变化:编译时指定的多个指标会被包装成一个CompileMetrics对象,而非直接以单独指标的形式暴露在model.metrics列表中,因此你看到的是['loss', 'compile_metrics']而非预期的单个指标名称。

解决方案

要获取具体的指标名称和对象,需要访问model.compile_metrics属性,它包含了你在model.compile()中定义的所有指标实例。

修改后的代码示例

import tensorflow as tf
import numpy as np
from tensorflow import keras

# 创建简单模型(修正Input层写法,消除警告)
def create_model():
    model = tf.keras.Sequential([
        tf.keras.layers.Input(shape=(3,)),  # 替换原来的input_shape参数
        tf.keras.layers.Dense(16, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])
    return model

# 测试指标的正确获取方式
def test_metrics_properties():
    model = create_model()
    model.compile(optimizer='adam',
                  loss=keras.losses.BinaryCrossentropy(),
                  metrics=[
                      tf.keras.metrics.BinaryAccuracy(name='accuracy'),
                      tf.keras.metrics.Precision(name='precision'),
                      tf.keras.metrics.Recall(name='recall')
                  ])

    # 正确获取指标名称
    print("训练前:")
    print("所有编译指标:", [m.name for m in model.compile_metrics])
    print("包含损失的完整指标列表:", ['loss'] + [m.name for m in model.compile_metrics])

    # 生成测试数据
    x = np.random.random((100, 3))
    y = np.random.randint(0, 2, size=(100, 1))

    # 训练模型
    history = model.fit(x, y, epochs=5, verbose=0)

    print("\n训练后:")
    print("所有编译指标:", [m.name for m in model.compile_metrics])
    print("包含损失的完整指标列表:", ['loss'] + [m.name for m in model.compile_metrics])
    # 训练历史中的键仍保持预期名称
    print("历史记录键名:", list(history.history.keys()))

if __name__ == "__main__":
    test_metrics_properties()

输出示例

训练前:
所有编译指标: ['accuracy', 'precision', 'recall']
包含损失的完整指标列表: ['loss', 'accuracy', 'precision', 'recall']

训练后:
所有编译指标: ['accuracy', 'precision', 'recall']
包含损失的完整指标列表: ['loss', 'accuracy', 'precision', 'recall']
历史记录键名: ['loss', 'accuracy', 'precision', 'recall']

额外说明

  • 训练历史对象history的history属性仍会返回包含所有指标名称的字典,和之前版本行为一致,你可以继续通过它获取训练过程中的指标数值。
  • 代码中同时修正了input_shape的警告,改用Input层作为Sequential模型的第一层,符合Keras 3的推荐写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:57:25