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

TensorFlow回归模型验证阶段如何配置R2分数评估指标?

在TensorFlow回归模型中添加R²验证指标

TensorFlow并没有内置可直接通过字符串(比如'r2_score')调用的R²指标,你需要通过以下两种方式实现:

方法1:自定义R²指标类

通过继承tf.keras.metrics.Metric实现符合TensorFlow规范的R²指标,它会正确累积验证集的整体计算结果,而非按批次计算后取平均:

import tensorflow as tf

class R2Score(tf.keras.metrics.Metric):
    def __init__(self, name='r2_score', **kwargs):
        super().__init__(name=name, **kwargs)
        self.ss_res = self.add_weight(name='ss_res', initializer='zeros')
        self.ss_tot = self.add_weight(name='ss_tot', initializer='zeros')

    def update_state(self, y_true, y_pred, sample_weight=None):
        y_true = tf.cast(y_true, tf.float32)
        y_pred = tf.cast(y_pred, tf.float32)
        
        # 计算残差平方和与总平方和
        ss_res = tf.reduce_sum(tf.square(y_true - y_pred))
        ss_tot = tf.reduce_sum(tf.square(y_true - tf.reduce_mean(y_true)))
        
        self.ss_res.assign_add(ss_res)
        self.ss_tot.assign_add(ss_tot)

    def result(self):
        # 避免真实值全部相同时除以0的错误
        return tf.where(self.ss_tot == 0, 0.0, 1 - (self.ss_res / self.ss_tot))

    def reset_state(self):
        # 重置指标状态,用于新一轮验证计算
        self.ss_res.assign(0.0)
        self.ss_tot.assign(0.0)

使用时直接传入类的实例:

model.compile(loss='mse',
              optimizer='adam',
              metrics=[R2Score()])

方法2:使用TensorFlow Addons预实现的R²指标

TensorFlow Addons库提供了现成的RSquare指标,先安装依赖:

pip install tensorflow-addons

导入后直接使用:

import tensorflow_addons as tfa

model.compile(loss='mse',
              optimizer='adam',
              metrics=[tfa.metrics.RSquare()])

注意事项

  • 不要用简单的函数式指标(比如直接计算1 - mse/var),这类方式会按批次计算R²后取平均,结果和整个验证集的真实R²存在偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:10:23