lolamontes69

Ch9 Ex2- Programming Collective Intelligence

Sep 14th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. """ Chapter 9 Exercise 2: Optimizing a dividing line.
  2.  
  3.    "Do you think it's possible to choose a dividing line using the optimization methods you learned in chapter 5, instead of just using the averages?
  4.    What cost function would you use?"
  5.  
  6.    I created a cost function and a method to create a rescaled avgs for use with dpclassify()
  7.    I cross-validate by checking the result supplied by dpclassify() against agesonly[X].match
  8.     for the entire dataset.
  9. """
  10.  
  11. import optimization as optimization
  12. from copy import deepcopy
  13. import advancedclassify1 as advancedclassify
  14. agesonly=advancedclassify.loadmatch('agesonly.csv',allnum=True)
  15.  
  16. # cost function
  17. def createcostfunction1(data):
  18.     avgs=advancedclassify.lineartrain(data)
  19.     def costf(scale):
  20.         print "scale =",scale
  21.         savgs = deepcopy(avgs)
  22.         for a in savgs:
  23.             for b in range(len(savgs[a])):
  24.                 savgs[a][b]+=scale[b]        # rescale avgs
  25.         error=0                              # calculate error
  26.         for a in range(len(data)):
  27.             pred = advancedclassify.dpclassify(data[a].data,savgs)
  28.             b = data[a].match
  29.             if pred!=b: error +=1
  30.         return error
  31.     return costf
  32.  
  33.  
  34. # function to produce a rescaled avgs after getting the optimized results
  35. def rescale_avgs(data,scale):
  36.     avgs=advancedclassify.lineartrain(data)
  37.     savgs = deepcopy(avgs)
  38.     for a in savgs:
  39.         for b in range(len(savgs[a])):
  40.             savgs[a][b]+=scale[b]
  41.     return savgs
  42.  
  43. """ Usage
  44. domain = [(-14,14)]*2
  45. costf = createcostfunction1(agesonly)
  46. optimization.randomoptimize(domain,costf)
  47. optimization.hillclimb(domain,costf)
  48. optimization.geneticoptimize(domain,costf,step=0.25,maxiter=10)
  49.  
  50. costf([-3,12])
  51. savgs = rescale_avgs(agesonly,[-3,12])
  52. advancedclassify.dpclassify([25,30],savgs)
  53.  
  54. """
Advertisement
Add Comment
Please, Sign In to add comment