在对数据进行线性回归计算之后,我们能够得出相应函数的系数, 那么我们如何知道得出的这个系数对方程结果的影响有强呢?
所以我们用到了一种方法叫 coefficient of determination (决定系数) 来判断 回归方程 拟合的程度.
- 平均数
y¯=1n∑i=1nyi
y¯=1n∑i=1nyi - THE TOTAL SUM OF SQUARES(总平方和)
SStot=∑(yi−y¯)2
SStot=∑(yi−y¯)2
yiyi表示真实数据,y¯y¯表示平均值
2. THE REGREESION SUM OF SQUARES(回归平方和)
SSreg=∑(fi−y¯)2
SSreg=∑(fi−y¯)2
fifi表示估计数据,y¯y¯表示平均值
3. THE SUM OF SQUARES OF RESIDUALS(残差平方和)
SSres=∑(yi−fi)2
SSres=∑(yi−fi)2
yiyi表示真实数据,fifi表示估算的数据
4. COEFFICIENT OF DETERMINATION(决定系数)
R2=1−SSresSStot
R2=1−SSresSStot
由于SSresSSres是估计数据也就是回归数据与平均值的误差
SStotSStot是真实数据与平均值的误差
SSresSSres一般比SStotSStot小,结果一般在0-1之间,SStotSStot在数据确定后始终是固定值,如果估计的越不准确,那么SSresSSres就越大,那么R2R2就越接近0,所以估计的越准确就越接近1
sklearn实现的R2R2
from sklearn.metrics import r2_score
def performance_metric(y_true, y_predict):
score = r2_score(y_true, y_predict)
return score
score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3])
print “Model has a coefficient of determination, R^2, of {:.3f}.”.format(score)
自己实现的R2R2
def performance_metric2(y_true, y_predict):
“”“计算并返回预测值相比于预测值的分数”""
import numpy as np
arr_true = np.array(y_true)
y_mean = np.mean(arr_true)
ssreg = 0
sstotal = 0
ssres = 0
for item in y_predict:
ssreg += (item - y_mean)**2
for item in y_true:
sstotal += (item - y_mean)**2
for index,item in enumerate(y_true):
ssres += (item - y_predict[index])**2
score = 1-(ssres/sstotal)
return score
score = performance_metric2([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3])
print “Model has a coefficient of determination, R^2, of {:.3f}.”.format(score)