import numpy as npy import cmath def computecorrelation(x,y): x_bar=npy.mean(x) y_bar=npy.mean(y) SSR=0 Varx=0 Vary=0 for i in range(0,len(x)): SSR+=(x[i]-x_bar)*(y[i]-y_bar) Varx+=(x[i]-x_bar)**2 Vary+=(y[i]-y_bar)**2 SST=cmath.sqrt(Varx*Vary) return SSR/SST def polyfot(x,y,degree): result={} coef=npy.polyfit(x,y,degree)#算出各个回归系数 result["polynomial"]=coef.tolist() p=npy.poly1d(coef)#拟合一条线 y_hat=p(x) y_bar=npy.mean(y) SSR=npy.sum((y_hat-y_bar)**2) SST=npy.sum((y-y_bar)**2) result["determination"]=SSR/SST return result test_x=[1,3,8,7,9] test_y=[10,12,24,21,34] print(polyfot(test_x,test_y,1)["determination"]) print(computecorrelation(test_x,test_y)**2) print(polyfot(test_x,test_y,1))