tensorflow2.10版本使用R2Score这个metrics

文章讲述了如何在TensorFlow2.10版本中使用R2Score,一种在2.15版本中新增的评估指标。作者提供了两种方法:一是自定义KerasMetric类,二是直接从2.15版本的GitHub源码复制。注意可能需要调整导入和装饰器以适应2.10版本的环境。
摘要由CSDN通过智能技术生成

问题描述:在tensorflow官网2.15版本中是有R2Score这个metrics的,但2.10版本中没有,如何在2.10版本中也能使用这个R2Score呢?

方法1:万能的GPT,通过GPT检索得到如下代码,实测可用

class R_squared(tf.keras.metrics.Metric):
    def __init__(self, name='r_squared', **kwargs):
        super(R_squared, self).__init__(name=name, **kwargs)
        self.total_samples = self.add_weight(name='total_samples', initializer='zeros')
        self.sum_of_squares = self.add_weight(name='sum_of_squares', initializer='zeros')
        self.sum_of_residuals = self.add_weight(name='sum_of_residuals', 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)

        # Calculate sum of squares of y_true
        total_samples = tf.cast(tf.size(y_true), tf.float32)
        self.total_samples.assign_add(total_samples)
        self.sum_of_squares.assign_add(tf.reduce_sum(tf.square(y_true - tf.reduce_mean(y_true))))

        # Calculate sum of residuals
        self.sum_of_residuals.assign_add(tf.reduce_sum(tf.square(y_true - y_pred)))

    def result(self):
        mean_y_true = self.sum_of_squares / self.total_samples
        r_squared = 1 - (self.sum_of_residuals / self.sum_of_squares)
        return r_squared

    def reset_state(self):
        # Reset the internal state of the metric
        self.total_samples.assign(0)
        self.sum_of_squares.assign(0)
        self.sum_of_residuals.assign(0)

在使用的时候,方式如下:

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),metrics=[R_squared()])

方法2:查看tensorflow中2.15中关于R2Score在github中的源码,链接如下:

keras/keras/metrics/regression_metrics.py at v2.15.0 · keras-team/keras · GitHub

也可以通过tensorflow官网中提示的链接进入,如第一张图片所示。

然后,将R2Score这个类,暴力的copy过来就行,哈哈哈哈,如果有报错的话,按提示导入包或者删掉装饰器 @,注意到这个R2Score只能接受二维数据。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值