How do I calculate r-squared using Python and Numpy?

后端 未结 11 1884
春和景丽
春和景丽 2020-11-28 19:29

I\'m using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (lin

11条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 20:24

    Here's a very simple python function to compute R^2 from the actual and predicted values assuming y and y_hat are pandas series:

    def r_squared(y, y_hat):
        y_bar = y.mean()
        ss_tot = ((y-y_bar)**2).sum()
        ss_res = ((y-y_hat)**2).sum()
        return 1 - (ss_res/ss_tot)
    

提交回复
热议问题