Advertisement
pnoq

Conspiracy Theory

May 21st, 2012
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon May 21 12:04:35 2012
  4.  
  5. Feel free to change and republish this file and its generated figures.
  6. Just give a link to the original post at:
  7.     http://pnoq.blogspot.com/2012/05/conspiracy-theory.html
  8. For start, you can change the srings at lines:
  9.     20, 21 and 22
  10. Have fun!
  11. The original file was taken from:
  12.     http://www.scipy.org/Cookbook/LinearRegression
  13. """
  14.  
  15. # -*- coding: utf-8 -*-
  16.  
  17. from scipy import linspace, polyval, polyfit, sqrt, randn
  18. from pylab import plot, title, show , legend, gca, savefig
  19.  
  20. data='Observations'
  21. lfit='Theory'
  22. pfit='Conspiracy Theory'
  23. # These strings are used to produce legends and output filename.
  24. # The output file name will be like:
  25. #   lfit-pfit.png
  26.  
  27. #Linear regression example
  28. # This is a very simple example of using two scipy tools
  29. # for linear regression, polyfit and stats.linregress
  30.  
  31. #Sample data creation
  32. #number of points
  33. n=10    #number of data points to be created.
  34. nplot=1000  #number of points to be plotted.
  35. t=linspace(-5,5,n)
  36. tplot=linspace(-5.1,5.1,nplot)  #plotting range.
  37.  
  38.  
  39. #parameters
  40. a=0.8; b=-4
  41. x=polyval([a,b],t) #This is artificial data points, taken from a line.
  42. #add some noise
  43. xn=x+randn(n)
  44.  
  45. #Linear regressison -polyfit - polyfit can be used other orders polys
  46.  
  47. pr=polyfit(t,xn,10) #fit a 10 degree polinomial.
  48. xpr=polyval(pr,t)       #calculate the data point according to above fit.
  49. xpr_plot=polyval(pr,tplot)
  50.  
  51. lr=polyfit(t,xn,1)  #fit a line
  52. xlr=polyval(lr,t)       #calculate the data point according to above fit.
  53. xlr_plot=polyval(lr,tplot)
  54.  
  55. #compute the mean square error
  56. err_line=sqrt(sum((xlr-xn)**2)/n)
  57. err_poly=sqrt(sum((xpr-xn)**2)/n)
  58. print('Linear regression using polyfit')
  59. print('Linear fit error= %.3f, Polynomial fit error= %.3f' % (err_line,err_poly))
  60.  
  61. #matplotlib ploting
  62. title('%s vs %s' % (lfit,pfit))
  63. plot(t,xn,'ko')
  64. plot(tplot,xlr_plot,'g-')
  65. plot(tplot,xpr_plot,'r-')
  66.  
  67. l1=legend([data, lfit, pfit],loc=2)
  68.  
  69. # You can remove following two lines if you don't want the error legend.
  70. 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.
  71. gca().add_artist(l1) # add l1 as a separate artist to the axes.
  72.  
  73. savefig('%s-%s.png' % (lfit, pfit))
  74. show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement