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

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

    You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.

    from scipy.stats import linregress
    import numpy as np
    
    x = np.array([1,2,3,4,5,6])
    y = np.array([2,3,5,6,7,8])
    
    p3 = np.polyfit(x,y,3) # 3rd degree polynomial, you can change it to any degree you want
    xp = np.linspace(1,6,6)  # 6 means the length of the line
    poly_arr = np.polyval(p3,xp)
    
    poly_list = [round(num, 3) for num in list(poly_arr)]
    slope, intercept, r_value, p_value, std_err = linregress(x, poly_list)
    print(r_value**2)
    

提交回复
热议问题