[Python] `sklearn.metrics.r2_score` is giving wrong R2 value?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to Python and I notice that sklearn.metrics.r2_score is giving wrong R2 value.

    from sklearn.metrics import r2_score

    r2_score(y_true=[2,4,3,34,23], y_pred=[21,12,3,11,17]) # -0.17
    r2_score(y_pred=[21,12,3,11,17], y_true=[2,4,3,34,23]) # -4.36


    However, the true R2 value should be 0.002 according to the rsq function in Excel. R2 should be between 0~1. Also, switching the order of "y_true" and "y_pred" should not affect the final result. I wonder how to fix this issue?

    Also, "In simple linear regression (one predictor), the coefficient of determination is numerically equal to the square of the Pearson correlation coefficient". I wonder why sklearn.metrics.r2_score is different to the squared Pearson correlation coefficient in this case?

    Continue reading...

Compartilhe esta Página