lolamontes69

Ch7 Ex1-Programming Collective Intelligence

Jul 25th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. """ Chapter 7 Exercise 1: Result probabilities.
  2.  
  3.    Currently, the classify and mdclassify functions give their results as total counts.
  4.    Modify them to give the probabilities of the results being one of the categories.
  5. """
  6.  
  7. def classify(observation,tree):
  8.     if tree.results!=None:
  9.         for a in tree.results:
  10.             tree.results[a] = tree.results[a]/float(len(my_data))  # Returns Probability using...
  11.         return tree.results                                        # totalcounts / totalrows
  12.     else:
  13.         v=observation[tree.col]
  14.         branch=None
  15.         if isinstance(v,int) or isinstance(v,float):
  16.             if v>=tree.value: branch=tree.tb
  17.             else: branch=tree.fb
  18.         else:
  19.             if v==tree.value: branch=tree.tb
  20.             else: branch=tree.fb
  21.         return classify(observation,branch)
  22.  
  23.  
  24. def mdclassify(observation,tree):
  25.     if tree.results!=None:
  26.         return tree.results
  27.     else:
  28.         v=observation[tree.col]
  29.         if v==None:
  30.             tr,fr=mdclassify(observation,tree.tb),mdclassify(observation,tree.fb)
  31.             tcount=sum(tr.values())
  32.             fcount=sum(fr.values())
  33.             tw=float(tcount)/(tcount+fcount)
  34.             fw=float(fcount)/(tcount+fcount)
  35.             result={}
  36.             for k,v in tr.items(): result[k]=v*tw
  37.             for k,v in fr.items(): result[k]=v*fw
  38.             return result
  39.         else:
  40.             if isinstance(v,int) or isinstance(v,float):
  41.                 if v>tree.value: branch=tree.tb
  42.                 else: branch=tree.fb
  43.             else:
  44.                 if v==tree.value: branch=tree.tb
  45.                 else: branch=tree.fb
  46.             return mdclassify(observation,branch)
Advertisement
Add Comment
Please, Sign In to add comment