[Python] 什么是R2分数(决定系数)以及通过scikit-learn的r2_score函数计算R2分数

微软技术分享
优质创作者: 编程框架技术领域
领域专家: 操作系统技术领域
2024-02-23 12:25:16

什么是R2分数(决定系数)?

R2分数(Coefficient of Determination)也称为决定系数,是用于评估回归模型拟合优度的一种统计指标。它表示自变量对于因变量的解释程度,即自变量能够解释因变量变异的比例。换句话说,这个系数,通常被称为R平方(R)2 ),评估两个变量之间的线性关系有多强。

R2分数的取值范围在0到1之间,越接近1表示模型拟合效果越好,越接近0表示模型拟合效果越差。具体计算公式为:

https://img-blog.csdnimg.cn/direct/7771d0f182604d3cb0ed6d3fef6cb45b.png

https://img-blog.csdnimg.cn/direct/1f7937888ac844559d81311fe3c6e392.png

R2 = 1 - (SS_res / SS_tot)

其中,SS_res是残差平方和(sum of squared residuals),SS_tot是总平方和(sum of total squares)。

 

使用scikit-learn中r2_score函数来计算2个向量的R2分数

from sklearn.metrics import r2_score
y_true = [1, 2, 4]
y_pred = [1.3, 2.5, 3.7]
# 计算真值 y_true 和 预测值 y_pred 的 R2 Score
r2_score(y_true, y_pred)

https://img-blog.csdnimg.cn/direct/7612c8f77a2d48b2bbbe91d204717240.png

通过numpy来推演r2 score的计算过程

https://img-blog.csdnimg.cn/direct/a4f94e2c998246bcadc43c827e810fc6.png


 综合使用案例

# 导入所需的库和数据集
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# 创建数据集
np.random.seed(0)
x = np.random.rand(100, 1)
y = 2 + 3 * x + np.random.rand(100, 1)

# 绘制数据集
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

# 将数据集分为训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

# 创建线性回归模型并拟合训练数据
regressor = LinearRegression()
regressor.fit(x_train, y_train)

# 打印拟合函数完之后的权重和偏置
print(f'y={regressor.coef_[0]}*x + {regressor.intercept_}')

# 使用模型进行预测
y_pred = regressor.predict(x_test)

# 评估模型的性能
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print('均方误差:', mse)
print('R2分数:', r2)

# 绘制拟合结果
plt.scatter(x_test, y_test, color='blue', label='actual')
plt.plot(x_test, y_pred, color='red', linewidth=2, label='predict')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

文章来源: https://blog.csdn.net/u011775793/article/details/135444960
版权声明: 本文为博主原创文章,遵循CC 4.0 BY-SA 知识共享协议,转载请附上原文出处链接和本声明。


...全文
530 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

6,466

社区成员

发帖
与我相关
我的任务
社区描述
微软技术社区为中国的开发者们提供一个技术干货传播平台,传递微软全球的技术和产品最新动态,分享各大技术方向的学习资源,同时也涵盖针对不同行业和场景的实践案例,希望可以全方位地帮助你获取更多知识和技能。
windowsmicrosoft 企业社区
社区管理员
  • 微软技术分享
  • 郑子铭
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

微软技术社区为中国的开发者们提供一个技术干货传播平台,传递微软全球的技术和产品最新动态,分享各大技术方向的学习资源,同时也涵盖针对不同行业和场景的实践案例,希望可以全方位地帮助你获取更多知识和技能。

予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。

试试用AI创作助手写篇文章吧