This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Linear Regression Example

   1 from scipy import linspace, polyval, polyfit, sqrt, stats, randn
   2 from pylab import plot, title, show , legend
   3 
   4 #Linear regression example
   5 # This is a very simple example of using two scipy tools 
   6 # for linear regression, polyfit and stats.linregress
   7 
   8 #Sample data creation
   9 #number of points 
  10 n=50
  11 t=linspace(-5,5,n)
  12 #parameters
  13 a=0.8; b=-4
  14 x=polyval([a,b],t)
  15 #add some noise
  16 xn=x+randn(n)
  17 
  18 #Linear regressison -polyfit - polyfit can be used other orders polys
  19 (ar,br)=polyfit(t,xn,1)
  20 xr=polyval([ar,br],t)
  21 #compute the mean square error
  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 #matplotlib ploting
  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 #Linear regression using stats.linregress
  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

SciPy: Cookbook/LinearRegression (last edited 2015-10-24 17:48:25 by anonymous)