lolamontes69

Ch7 Ex2-Programming Collective Intelligence

Jul 25th, 2013
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. """ Chapter 7 Exercise 2: Missing Data Ranges.
  2.  
  3.    mdclassify allows the use of "None" to specify a missing value. For numerical values the result may not be completely unknown, but may be known to be in a range. Modify mdclassify to allow a tuple such as (20,25) in place of a value and traverse down both branches when necessary.
  4. """
  5.  
  6. def mdclassify(observation,tree):
  7.     if tree.results!=None:
  8.         return tree.results
  9.     else:
  10.         v=observation[tree.col]
  11.         if v==None:
  12.             tr,fr=mdclassify(observation,tree.tb),mdclassify(observation,tree.fb)
  13.             tcount=sum(tr.values())
  14.             fcount=sum(fr.values())
  15.             tw=float(tcount)/(tcount+fcount)
  16.             fw=float(fcount)/(tcount+fcount)
  17.             result={}
  18.             for k,v in tr.items(): result[k]=v*tw
  19.             for k,v in fr.items(): result[k]=v*fw
  20.             return result
  21.         else:
  22.             if isinstance(v,tuple):
  23.                 for a in v:
  24.                     if int(a)>int(tree.value):
  25.                         branch=tree.tb
  26.                         observation[tree.col] = int(a)
  27.                         return mdclassify(observation,branch)  # See if either value from tuple > tree.value
  28.                 branch=tree.fb                                 # If yes branch=tree.tb   else branch=tree.fb
  29.             elif isinstance(v,int) or isinstance(v,float):
  30.                 if v>tree.value: branch=tree.tb
  31.                 else: branch=tree.fb
  32.             else:
  33.                 if v==tree.value: branch=tree.tb
  34.                 else: branch=tree.fb
  35.             return mdclassify(observation,branch)
Advertisement
Add Comment
Please, Sign In to add comment