lolamontes69

Ch7 Ex5-Programming Collective Intelligence

Aug 2nd, 2013
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.92 KB | None | 0 0
  1. """ Chapter 7 Exercise 5: Multiway splits. (Hard)
  2.  
  3. >>> All the trees built in this chapter are binary decision trees.
  4.    However, some datasets might be simpler trees if they allowed a node to split into more than two branches.
  5.    How would you represent this? How would you train the tree? <<<
  6.  
  7.    I replaced 'tb' and 'fb' with 'allbranches' which contains a dictionary, holding all of the splits for the node.
  8.    (Example: {'New Zealand': <Ch7Ex5.decisionnode instance at 0x81a2c8c>, 'UK': <Ch7Ex5.decisionnode instance at 0x81a2ccc>})
  9.    Obviously I rewrote buildtree() to make multiple splits, and printtree() to print them.
  10.    divide_set() is replaced with make_set() which makes a single set for the value passed to it.
  11.    make_a_dic() makes a dictionary of {value: set, ...}  for the values in the specified column of the set passed to it.
  12.    I rewrote classify() as two connected functions classify() and main_classify(). classify() can deal with missing data in the observation. The using of this code is the same as for treepredict. (except I haven't implemented prune() or the jpeg creating functions.) See end for example usage.
  13.  
  14.    I had lots of fun with recursion doing this exercise :)
  15. """
  16.  
  17. my_data=[line.split('\t') for line in file('decision_tree_example.txt')]
  18. # Replace '/n' or it taints the data (example:{'Basic\n': 4, 'Premium\n': 1, 'Basic': 1})
  19. for a in range(len(my_data)):
  20.     for b in range(len(my_data[a])):
  21.         my_data[a][b] = my_data[a][b].replace('\n','')
  22.  
  23. class decisionnode:
  24.     def __init__(self,col=-1,results=None,allbranches=None):
  25.         self.col=col
  26.         self.results=results
  27.         self.allbranches=allbranches
  28.  
  29. def uniquecounts(rows):
  30.     results={}
  31.     for row in rows:
  32.         # The result is the last column
  33.         r=row[len(row)-1]
  34.         if r not in results: results[r]=0
  35.         results[r]+=1
  36.     return results
  37.  
  38. def variance(rows):
  39.     if len(rows)==0: return 0
  40.     data=[float(row[len(row)-1]) for row in rows]
  41.     mean=sum(data)/len(data)
  42.     variance=sum([(d-mean)**2 for d in data])/len(data)
  43.     return variance
  44.  
  45. def giniimpurity(rows):
  46.     total=len(rows)
  47.     counts=uniquecounts(rows)
  48.     imp=0
  49.     for k1 in counts:
  50.         p1=float(counts[k1])/total
  51.         for k2 in counts:
  52.             if k1==k2: continue
  53.             p2=float(counts[k2])/total
  54.             imp+=p1*p2
  55.     return imp
  56.  
  57. def entropy(rows):
  58.     from math import log
  59.     log2=lambda x:log(x)/log(2)
  60.     results=uniquecounts(rows)
  61.     # Now calculate the entropy
  62.     ent=0.0
  63.     for r in results.keys():
  64.         p=float(results[r])/len(rows)
  65.         ent=ent-p*log2(p)
  66.     return ent
  67.  
  68. def make_set(rows,column,value):
  69.     split_function=None
  70.     if isinstance(value,int) or isinstance(value,float):
  71.         split_function=lambda row:row[column]>=value
  72.     else:
  73.         split_function=lambda row:row[column]==value
  74.     set1=[row for row in rows if split_function(row)]
  75.     return set1
  76.  
  77. def make_a_dic(rows,column):
  78.     dicus = {}
  79.     for a in range(len(rows)):
  80.         value = rows[a][column]
  81.         set1 = make_set(rows,column,value)
  82.         dicus[value] = set1
  83.     return dicus
  84.  
  85. def buildtree(rows,scoref=entropy):
  86.     if len(rows)==0: return decisionnode()
  87.     current_score=scoref(rows)
  88.     best_gain=0.0
  89.     best_criteria=None                 # Best criteria in multi split is just column number
  90.     best_sets=None                     # because values are contained in the dictionary in bestsets
  91.     column_count=len(rows[0])-1
  92.     for col in range(0,column_count):
  93.         # Generate the dictionary of different values in this column
  94.         dicus = make_a_dic(rows,col)
  95.         # Calculate which dicus is best_dicus here
  96.         gain = current_score
  97.         lensets = 0
  98.         for a in (dicus):
  99.             lena = len(dicus[a])
  100.             lensets += lena
  101.             score = scoref(dicus[a])
  102.             p = float(lena)/len(rows)
  103.             gain-=(p*score)
  104.         if gain>best_gain and lensets>0:
  105.             best_gain=gain
  106.             best_criteria=(col)
  107.             best_sets=dicus
  108.     if best_gain>0:
  109.         branches = {}
  110.         for set in best_sets:
  111.             branch = buildtree(best_sets[set],scoref)
  112.             branches[set]=branch
  113.         return decisionnode(col=best_criteria, allbranches=branches)
  114.     else:
  115.         return decisionnode(results=uniquecounts(rows))
  116.  
  117. def printtree(tree,indent='  '):
  118.     # Is this a leaf node?
  119.     if tree.results!=None:
  120.         print str(tree.results)
  121.     else:
  122.         print str(tree.col)+':'
  123.         for a in tree.allbranches:
  124.             print indent+str(a)+'->',
  125.             printtree(tree.allbranches[a],indent+'  ')
  126.  
  127. def main_classify(observation,tree):
  128.     result_dic={}
  129.     if tree.results!=None: return tree.results
  130.     else:
  131.         v=str(observation[tree.col])
  132.         if v in tree.allbranches: dic_a = main_classify(observation,tree.allbranches[v])
  133.         else:
  134.             for a in tree.allbranches:
  135.                 dic_a = main_classify(observation,tree.allbranches[a])
  136.                 for a in dic_a:
  137.                     if a not in result_dic: result_dic[a]=dic_a[a]
  138.                     else: result_dic[a]=result_dic[a]+dic_a[a]
  139.             return result_dic
  140.     for a in dic_a:
  141.         if a not in result_dic: result_dic[a]=dic_a[a]
  142.         else: result_dic[a]=result_dic[a]+dic_a[a]
  143.     return result_dic
  144.  
  145. def classify(observation,tree):
  146.     count=0     # Variable to divide res scores by the number of results it is made from
  147.     res={}
  148.     v=observation[tree.col]
  149.     if v in tree.allbranches: return main_classify(observation,tree)
  150.     # If v isn't in tree.allbranches move on to the next level of branches
  151.     for a in tree.allbranches:
  152.         v = observation[tree.allbranches[a].col]
  153.         if tree.allbranches[a].allbranches!=None:
  154.             if v in tree.allbranches[a].allbranches:
  155.                 result = main_classify(observation,tree.allbranches[a])
  156.                 count+=1
  157.                 for a in result:
  158.                     if a not in res: res[a]=result[a]
  159.                     else: res[a]=res[a]+result[a]
  160.     if len(res)==0: return main_classify(observation,tree)
  161.     else:
  162.         for a in res:
  163.             res[a]=float(res[a])/count
  164.         return res
  165.  
  166. """
  167. Example usage
  168. *************
  169. >>>import Ch7Ex5 as treepredict
  170. >>>tree = treepredict.buildtree(treepredict.my_data,scoref=treepredict.entropy)
  171. >>>treepredict.printtree(tree)
  172. 0:
  173.  (direct)-> 1:
  174.    New Zealand-> {'None': 1}
  175.    UK-> {'Basic': 1}
  176.  slashdot-> {'None': 3}
  177.  kiwitobes-> 1:
  178.    UK-> {'None': 1}
  179.    France-> {'Basic': 2}
  180.  digg-> 2:
  181.    yes-> {'Basic': 2}
  182.    no-> {'None': 1}
  183.  google-> 3:
  184.    24-> {'Premium': 1}
  185.    18-> 2:
  186.      yes-> {'Basic': 1}
  187.      no-> {'None': 1}
  188.    21-> {'Premium': 1}
  189.    23-> {'Premium': 1}
  190.  
  191. >>> treepredict.classify(['(direct)','USA','yes','5'],tree)
  192. {'None': 1, 'Basic': 1}
  193. >>> treepredict.classify([None,'France','yes','5'],tree)
  194. {'Basic': 2.0}
  195. """
Advertisement
Add Comment
Please, Sign In to add comment