Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Mon May 21 12:04:35 2012
- Feel free to change and republish this file and its generated figures.
- Just give a link to the original post at:
- http://pnoq.blogspot.com/2012/05/conspiracy-theory.html
- For start, you can change the srings at lines:
- 20, 21 and 22
- Have fun!
- The original file was taken from:
- http://www.scipy.org/Cookbook/LinearRegression
- """
- # -*- coding: utf-8 -*-
- from scipy import linspace, polyval, polyfit, sqrt, randn
- from pylab import plot, title, show , legend, gca, savefig
- data='Observations'
- lfit='Theory'
- pfit='Conspiracy Theory'
- # These strings are used to produce legends and output filename.
- # The output file name will be like:
- # lfit-pfit.png
- #Linear regression example
- # This is a very simple example of using two scipy tools
- # for linear regression, polyfit and stats.linregress
- #Sample data creation
- #number of points
- n=10 #number of data points to be created.
- nplot=1000 #number of points to be plotted.
- t=linspace(-5,5,n)
- tplot=linspace(-5.1,5.1,nplot) #plotting range.
- #parameters
- a=0.8; b=-4
- x=polyval([a,b],t) #This is artificial data points, taken from a line.
- #add some noise
- xn=x+randn(n)
- #Linear regressison -polyfit - polyfit can be used other orders polys
- pr=polyfit(t,xn,10) #fit a 10 degree polinomial.
- xpr=polyval(pr,t) #calculate the data point according to above fit.
- xpr_plot=polyval(pr,tplot)
- lr=polyfit(t,xn,1) #fit a line
- xlr=polyval(lr,t) #calculate the data point according to above fit.
- xlr_plot=polyval(lr,tplot)
- #compute the mean square error
- err_line=sqrt(sum((xlr-xn)**2)/n)
- err_poly=sqrt(sum((xpr-xn)**2)/n)
- print('Linear regression using polyfit')
- print('Linear fit error= %.3f, Polynomial fit error= %.3f' % (err_line,err_poly))
- #matplotlib ploting
- title('%s vs %s' % (lfit,pfit))
- plot(t,xn,'ko')
- plot(tplot,xlr_plot,'g-')
- plot(tplot,xpr_plot,'r-')
- l1=legend([data, lfit, pfit],loc=2)
- # You can remove following two lines if you don't want the error legend.
- l2=legend([ 'Error of %s is %.3f' % (lfit,err_line) , 'Error of %s is %.3f' % (pfit,err_poly)],loc=4) # this removes l1 from the axes.
- gca().add_artist(l1) # add l1 as a separate artist to the axes.
- savefig('%s-%s.png' % (lfit, pfit))
- show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement