什么是R2分数(决定系数)?
R2分数(Coefficient of Determination)也称为决定系数,是用于评估回归模型拟合优度的一种统计指标。它表示自变量对于因变量的解释程度,即自变量能够解释因变量变异的比例。换句话说,这个系数,通常被称为R平方(R)2 ),评估两个变量之间的线性关系有多强。
R2分数的取值范围在0到1之间,越接近1表示模型拟合效果越好,越接近0表示模型拟合效果越差。具体计算公式为:
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)
通过numpy来推演r2 score的计算过程
综合使用案例
# 导入所需的库和数据集
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()