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

后端 未结 11 1898
春和景丽
春和景丽 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:08

    From scipy.stats.linregress source. They use the average sum of squares method.

    import numpy as np
    
    x = np.array(x)
    y = np.array(y)
    
    # average sum of squares:
    ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat
    
    r_num = ssxym
    r_den = np.sqrt(ssxm * ssym)
    r = r_num / r_den
    
    if r_den == 0.0:
        r = 0.0
    else:
        r = r_num / r_den
    
        if r > 1.0:
            r = 1.0
        elif r < -1.0:
            r = -1.0
    

提交回复
热议问题