LinearRegression - SciPy wiki dump (original) (raw)

Linear Regression Example

1 from scipy import linspace, polyval, polyfit, sqrt, stats, randn 2 from pylab import plot, title, show , legend 3 4 5 6 7 8 9 10 n=50 11 t=linspace(-5,5,n) 12 13 a=0.8; b=-4 14 x=polyval([a,b],t) 15 16 xn=x+randn(n) 17 18 19 (ar,br)=polyfit(t,xn,1) 20 xr=polyval([ar,br],t) 21 22 err=sqrt(sum((xr-xn)**2)/n) 23 24 print('Linear regression using polyfit') 25 print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, ms error= %.3f' % (a,b,ar,br,err)) 26 27 28 title('Linear Regression Example') 29 plot(t,x,'g.--') 30 plot(t,xn,'k.') 31 plot(t,xr,'r.-') 32 legend(['original','plus noise', 'regression']) 33 34 show() 35 36 37 (a_s,b_s,r,tt,stderr)=stats.linregress(t,xn) 38 print('Linear regression using stats.linregress') 39 print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, std error= %.3f' % (a,b,a_s,b_s,stderr))

linregress.png

Another example: using scipy (and R) to calculate Linear Regressions