lolamontes69

Ch8 Ex1-Programming Collective Intelligence

Aug 12th, 2013
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. """ Chapter 8 Exercise 1: Optimizing the number of neighbors.
  2.  
  3.    Create a cost function for optimization that determines the ideal number of neighbors for a sample dataset
  4.  
  5.    Seems as though we are only optimizing one value. I just wrote a function that goes through a range of values for k and returns a dictionary of the best k's from the trials
  6.    See end for usage.
  7. """
  8.  
  9. def best_k(min_k,max_k,trials,costf):
  10.     dic={}
  11.     for f in range(trials):
  12.         best=1000000
  13.         bestx=0
  14.         for x in range(min_k,max_k+1):
  15.             def knn_est(d,v): return costf(d,v,k=x)
  16.             cost = numpredict.crossvalidate(knn_est,data)
  17.             if cost<best:
  18.                 best=cost
  19.                 bestx=x
  20.         print 'best cost =',best,' and best k =',bestx
  21.         if bestx not in dic: dic[bestx]=0
  22.         dic[bestx]+=1
  23.     return dic
  24.  
  25. """
  26.    Usage:
  27.    import best_k as best_k
  28.    import numpredict as numpredict
  29.    data = numpredict.wineset1()
  30.    best_k.best_k(1,5,100,numpredict.knnestimate)
  31.    best_k.best_k(6,12,20,numpredict.weightedknn)
  32. """
Advertisement
Add Comment
Please, Sign In to add comment