Why the results of 2 approaches to calculate R2 score are different

Viewed 38

In the linear model, SST(total sum of squares) = SSR (residual sum of squares) + SSE (explained sum of squares), right? So I calculated the R2 score with 2 different methods.

The shape of data is (n_sample, n_feature), and I want to calculate the R2 score by each feature.

1st: R2 = SSE/SST

def r2score(y_pred, y_true):
    SSE = np.sum((y_pred - y_true.mean(axis=0)) ** 2, axis=0)
    SST = np.sum((y_true - y_true.mean(axis=0)) ** 2, axis=0)
    return SSE / SST

array([0.3903272 , 0.61556043, 0.79316815, 0.27477445, 0.76132449,
       0.37335292, 0.67222515, 0.56178136, 0.37840461, 0.48753905,
       0.48425204, 0.40274203, 0.32436666, 0.73934064, 0.67582176,
       0.65503309, 0.74719551, 0.42158567, 0.35102711, 0.52308956,
       0.22078698, 0.30651726, 0.28614789, 0.43199096])

2st: R2 = 1 - SSR/SST

def r2score_same(y_pred, y_true):
    SSR = np.sum((y_true - y_pred) ** 2, axis=0)
    SST = np.sum((y_true - y_true.mean(axis=0)) ** 2, axis=0)
    return 1 - (SSR / SST)

array([0.43137207, 0.58980204, 0.75270556, 0.31230454, 0.80313592,
       0.2881272 , 0.68314465, 0.61986317, 0.36847796, 0.456864  ,
       0.35585449, 0.4385286 , 0.35472905, 0.66386517, 0.59598209,
       0.65243417, 0.70413723, 0.42801639, 0.43712039, 0.56682037,
       0.23902448, 0.34432634, 0.33884071, 0.42886742])

I can't understand why the results are not the same.

Please help me!

0 Answers
Related