BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Evaluation metrics7 of 33 in topic

158. 计算回归的 R-squared 和 adjusted R-squared

EasyEvaluation metrics

重要性 R-squared 和 adjusted R-squared 是人们在任何回归报告中首先看到的指标,面试官经常会问为什么需要 adjusted R2。

R-squared 表示模型解释了多少比例的方差。Adjusted R-squared 会惩罚额外的 feature,因此你不能仅仅通过增加列来提高分数。

编写 r2_scores(y, yhat, p)。y 和 yhat 是等长的序列,p 是 feature 的数量(不包括 intercept)。R2 = 1 - SS_res / SS_tot,其中 SS_res = sum (y - yhat)^2 且 SS_tot = sum (y - mean(y))^2。如果 SS_tot 为 0,当 SS_res 为 0 时 R2 为 1.0,否则为 0.0。Adjusted R2 = 1 - (1 - R2) * (n - 1) / (n - p - 1)。以 float 类型返回 (r2, adj)。

函数def r2_scores(y, yhat, p)

示例 1

输入: y [3, 5, 7, 9], yhat [2.8, 5.3, 6.9, 9.0], p 1

输出: (0.993, 0.9895)

示例 2

输入: y = [1, 2, 3], yhat = [3, 2, 1], p = 1

输出: (-3.0, -7.0)

示例 3

输入: y = [10, 12, 9, 15, 11, 14], yhat = [10.5, 11.5, 9.5, 14, 11, 13.5], p = 3

输出: (0.925466, 0.813665)

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
提示 1

计算这两个平方和,然后代入两个公式。

提示 2

SS_tot 使用的是 y 的均值,而不是 yhat 的均值。

提示 3

n - p - 1 考虑了 intercept。

提示 4

在除法之前处理常数 y 的情况。

常见错误
  • 认为 R2 不可能是负数。
  • 使用了 n - p 而不是 n - p - 1。
  • 在没有进行调整的情况下,比较具有不同 feature 数量的模型之间的 R2。
理解思路

R-squared 将你的模型与最懒的模型进行比较:即始终预测平均值。如果你的误差相对于懒惰模型的误差非常小,R2 就接近 1。如果两者相等,R2 为 0。如果你的模型比平均值还差,R2 为负数。

Worked example

y = 3, 5, 7, 9 的均值为 6,所以 SS_tot = 9 + 1 + 1 + 9 = 20。预测值 2.8, 5.3, 6.9, 9.0 产生的误差为 0.2, -0.3, 0.1, 0,因此 SS_res = 0.04 + 0.09 + 0.01 + 0 = 0.14。R2 = 1 - 0.14 / 20 = 0.993。当 n = 4 且 p = 1 时,adjusted R2 = 1 - 0.007 * 3 / 2 = 0.9895。

R2 = 1 - SS_res / SS_tot; adjusted R2 = 1 - (1 - R2)(n - 1)/(n - p - 1)

在训练数据上,添加任何 feature(甚至是随机噪声)都不可能降低原始 R2。而 adjusted 版本会对每个 feature 进行惩罚,这使得在比较不同规模的模型时更加公平。

主题
Evaluation metrics
相似题目
  • 根据预测结果计算 precision, recall 和 F1Easy
  • 使用 expected calibration error 衡量分类器的过度自信程度Easy
  • 构建混淆矩阵Easy
  • 计算 mean reciprocal rankEasy
所有 Evaluation metrics 道题目
反馈
158 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def r2_scores(y, yhat, p):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 4 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS