python - 如何在 Tensorflow 中计算 R^2

标签 python tensorflow regression

我正在尝试在 Tensorflow 中进行回归。我不确定我是否正确计算了 R^2,因为 Tensorflow 给我的答案与 sklearn.metrics.r2_score 不同 有人可以看看我下面的代码,让我知道我是否实现了图中的方程式正确。谢谢

The formula I am attempting to create in TF

total_error = tf.square(tf.sub(y, tf.reduce_mean(y)))
unexplained_error = tf.square(tf.sub(y, prediction))
R_squared = tf.reduce_mean(tf.sub(tf.div(unexplained_error, total_error), 1.0))
R = tf.mul(tf.sign(R_squared),tf.sqrt(tf.abs(R_squared)))

最佳答案

你计算的“R^2”是

R^2_{\text{wrong}} = \operatorname{mean}_i \left( \frac{(y_i-\hat y_i)^2}{(y_i-\mu)^2} - 1\right)1

与给定的表达式相比,您在错误的地方计算平均值。在进行除法之前,您应该在计算误差时取平均值。

unexplained_error = tf.reduce_sum(tf.square(tf.sub(y, prediction)))
total_error = tf.reduce_sum(tf.square(tf.sub(y, tf.reduce_mean(y))))
R_squared = tf.sub(1, tf.div(unexplained_error, total_error))

关于python - 如何在 Tensorflow 中计算 R^2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351184/

相关文章:

python - 检查输入 : expected flatten_input to have 3 dimensions, 但获得形状为 (None, 100, 100, 1) 的数组时出错

r - 为什么使用 Zoo 对象进行回归会产生无法识别的结果

r - 自定义链接功能适用于 GLM 但不适用于 mgcv GAM

r - R 中随机森林回归模型中的 corr.bias 参数

python - 如何使用自定义路径设置自定义字体到 matplotlib 全局字体?

python - 如何按元素应用二元交叉熵,然后在 Keras 中对所有这些损失求和?

python - 在数组 python/flask 中查找值

python - TensorFlow 中 RNN 的两种实现有什么区别?

python - 如何在另一个函数中访问一个python函数中的变量

python - 更改 matplotlib Qt GUI savefig 的默认名称