I need to calculate the coefficient of determination for a linear regression model.
And I got a strange thing, result of calculation using definition and numpy functions differs to sklearn.metrics.r2_score result.
This code presents the difference :
import numpy as np
from sklearn.metrics import r2_score
y_true = np.array([2, -0.5, 2.5, 3, 0])
y_pred = np.array([2.5, 0.0, 3, 8, 0])
r2_score(y_true, y_pred)
>>> -1.6546391752577323
def my_r2_score(y_true, y_pred):
return 1 - np.sum((y_true - y_pred) ** 2) / np.sum((np.average(y_true) - y_true) ** 2)
def my_r2_score_var(y_true, y_pred):
return 1 - np.var(y_true - y_pred) / np.var(y_true)
print(my_r2_score(y_true, y_pred))
print(my_r2_score_var(y_true, y_pred))
>>>-1.6546391752577323
>>>-0.7835051546391754
Can any body explain this difference ?