lolamontes69

Ch7 Ex3-Programming Collective Intelligence

Jul 28th, 2013
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. """ Chapter 7 Exercise 3: Early Stopping.
  2.  
  3.    Rather than pruning the tree, buildtree can just stop dividing when it reaches a point where the entropy is not reduced enough. This may not be ideal in some cases, but it does save an extra step.
  4.    Modify buildtree to take a minimum gain parameter and stop dividing the branch if this condition is not met.
  5.  
  6.    Example usage: buildtree(rows,mingain=60.0)
  7.    Implemented in a more user-friendly way as a percentage of the first current score. This makes it easier to play with values :)
  8.    (If entropy is not reduced enough this results in a lower percentage)  
  9. """
  10.  
  11. def buildtree(rows,scoref=entropy,mingain=0.0,firstscore=0):
  12.     if len(rows)==0: return decisionnode()
  13.  
  14.     current_score=scoref(rows)
  15.  
  16.     if firstscore==0: firstscore = float(current_score)               # <--Exercise 3 here
  17.     if float((current_score/firstscore)*(100.0/1))<float(mingain):    # <-- " " " " " " "
  18.         return decisionnode(results=uniquecounts(rows))               # <-- " " " " " " "
  19.  
  20.     # set up some variables to track the best criteria
  21.     best_gain=0.0
  22.     best_criteria=None
  23.     best_sets=None
  24.  
  25.     column_count=len(rows[0])-1
  26.     for col in range(0,column_count):
  27.         # Generate the list of different values in this column
  28.         column_values={}
  29.         for row in rows:
  30.             column_values[row[col]]=1
  31.         # Now try dividing the rows up for each value in this column
  32.         for value in column_values.keys():
  33.             (set1,set2)=divideset(rows,col,value)
  34.  
  35.             # Information gain
  36.             p=float(len(set1))/len(rows)
  37.             gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  38.             if gain>best_gain and len(set1)>0 and len(set2)>0:
  39.                 best_gain=gain
  40.                 best_criteria=(col,value)
  41.                 best_sets=(set1,set2)
  42.     # Create the subbranches
  43.     if best_gain>0:
  44.         trueBranch=buildtree(best_sets[0],scoref,mingain,firstscore)                        # corrected adding scoref
  45.         falseBranch=buildtree(best_sets[1],scoref,mingain,firstscore)                       # corrected adding scoref
  46.  
  47.         return decisionnode(col=best_criteria[0],value=best_criteria[1],
  48.                             tb=trueBranch,fb=falseBranch)
  49.     else:
  50.         return decisionnode(results=uniquecounts(rows))
Advertisement
Add Comment
Please, Sign In to add comment