关于R2的定义这里不进行叙述,维基百科上有很详细的解释。https://en.wikipedia.org/wiki/Coefficient_of_determination
这里记录一下几种Python实现:
1.从sklearn.metric中调用
from sklearn.metrics import r2_score
2.
# 均方误差根
def rmse(y_test, y):
return sp.sqrt(sp.mean((y_test - y) ** 2))
def R2_0(y_test,y_pred):
SStot=np.sum((y_test-np.mean(y_test))**2)
SSres=np.sum((y_test-y_pred)**2)
r2=1-SSres/SStot
return r2
def R2_1_(y_pred, y_test):
y_mean = np.array(y_test)
y_mean[:] = y_mean.mean()
return 1 - rmse(y_pred, y_test) / rmse(y_mean, y_test)
def R2_2_(y_pred,y_test):
SStot=np.sum((y_test-np.mean(y_test))**2)
SSres=np.sum((y_test-y_pred)**2)
r2=SSres/SStot
return r2