lolamontes69

Ch12 App2: Decision Tree Classifier. Prog..Collective Intel.

Sep 26th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.85 KB | None | 0 0
  1. """ Chapter 12 Programming Collective Intelligence: Decision Tree Classifier.
  2.  
  3.   As the chapter has no exercises in it I have decided to create a practical
  4.   application for each of the Algorithms and Methods described.
  5.   Next up the Decision Tree Classifier.
  6.   For this I have created a simple application that reads a dataset,containing
  7.   details for passengers on the Titanic who either died or survived, creates
  8.   a decision tree from the dataset, gets input from the user, classifies with
  9.   the decision tree showing the survival or death of similar passengers to
  10.   the user. I am a survivor. :)
  11.         --lolamontes69
  12. """
  13.  
  14. import titanic_dataset as md
  15. import os as os
  16.  
  17. class decisionnode:
  18.     def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  19.         self.col=col
  20.         self.value=value
  21.         self.results=results
  22.         self.tb=tb
  23.         self.fb=fb
  24.  
  25. # Divides a set on a specific column. Can handle numeric or nominal values
  26. def divideset(rows,column,value):
  27.     try: value = int(value) # The numerical data is saved as strings within my_data
  28.     except: pass
  29.  
  30.     # Make a function that tells us if a row is in the first group (true) or the second (false)
  31.     split_function=None
  32.     if isinstance(value,int) or isinstance(value,float):
  33.         split_function=lambda row: int(row[column])>=value
  34.     else:
  35.         split_function=lambda row:row[column]==value
  36.        
  37.     # Divide the rows into two sets and return them
  38.     set1=[row for row in rows if split_function(row)]
  39.     set2=[row for row in rows if not split_function(row)]
  40.     return (set1,set2)
  41.  
  42. def uniquecounts(rows):
  43.     results={}
  44.     for row in rows:
  45.         # The result is the last column
  46.         r=row[len(row)-1]
  47.         if r not in results: results[r]=0
  48.         results[r]+=1
  49.     return results
  50.  
  51. def entropy(rows):
  52.     from math import log
  53.     log2=lambda x:log(x)/log(2)
  54.     results=uniquecounts(rows)
  55.     # Now calculate the entropy
  56.     ent=0.0
  57.     for r in results.keys():
  58.         p=float(results[r])/len(rows)
  59.         ent=ent-p*log2(p)
  60.     return ent
  61.  
  62. def buildtree(rows,scoref=entropy):
  63.     if len(rows)==0: return decisionnode()
  64.     current_score=scoref(rows)
  65.  
  66.     # set up some variables to track the best criteria
  67.     best_gain=0.0
  68.     best_criteria=None
  69.     best_sets=None
  70.  
  71.     column_count=len(rows[0])-1
  72.     for col in range(0,column_count):
  73.         # Generate the list of different values in this column
  74.         column_values={}
  75.         for row in rows:
  76.             column_values[row[col]]=1
  77.         # Now try dividing the rows up for each value in this column
  78.         for value in column_values.keys():
  79.             (set1,set2)=divideset(rows,col,value)
  80.  
  81.             # Information gain
  82.             p=float(len(set1))/len(rows)
  83.             gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  84.             if gain>best_gain and len(set1)>0 and len(set2)>0:
  85.                 best_gain=gain
  86.                 best_criteria=(col,value)
  87.                 best_sets=(set1,set2)
  88.     # Create the subbranches
  89.     if best_gain>0:
  90.         trueBranch=buildtree(best_sets[0],scoref)                        # corrected adding scoref
  91.         falseBranch=buildtree(best_sets[1],scoref)                       # corrected adding scoref
  92.         return decisionnode(col=best_criteria[0],value=best_criteria[1],
  93.                             tb=trueBranch,fb=falseBranch)
  94.     else:
  95.         return decisionnode(results=uniquecounts(rows))
  96.  
  97. def mdclassify(observation,tree):
  98.     if tree.results!=None:
  99.         return tree.results
  100.     else:
  101.         v=observation[tree.col]
  102.         if v==None:
  103.             tr,fr=mdclassify(observation,tree.tb),mdclassify(observation,tree.fb)
  104.             tcount=sum(tr.values())
  105.             fcount=sum(fr.values())
  106.             tw=float(tcount)/(tcount+fcount)
  107.             fw=float(fcount)/(tcount+fcount)
  108.             result={}
  109.             for k,v in tr.items(): result[k]=v*tw
  110.             for k,v in fr.items(): result[k]=v*fw
  111.             return result
  112.         else:
  113.             if isinstance(v,int) or isinstance(v,float):
  114.                 if v>tree.value: branch=tree.tb
  115.                 else: branch=tree.fb
  116.             else:
  117.                 if v==tree.value: branch=tree.tb
  118.                 else: branch=tree.fb
  119.             return mdclassify(observation,branch)
  120.  
  121. def am_i_survive(my_data,tree):
  122.     while True:
  123.         list1=[]
  124.         os.system('clear')
  125.         print "-"*44
  126.         try:
  127.             print "    WOULD I SURVIVE THE TITANIC SINKING?"
  128.             print "-"*44
  129.             list1.append((str(raw_input('What class are you? upper,middle or lower? >'))).lower())
  130.             list1.append((str(raw_input('What gender are you? male or female? >'))).lower())
  131.             list1.append(int(raw_input('What is your age? >')))
  132.             a=(str(raw_input('Are you travelling with your spouse or your brother/sister? (y/n) >'))).lower()
  133.             if a=="y": list1.append('ysibsp')
  134.             elif a!="y": list1.append('nsibsp')
  135.             a=(str(raw_input('Are you travelling with your parents or your children? (y/n) >'))).lower()
  136.             if a=="y": list1.append('yparch')
  137.             elif a!="y": list1.append('nparch')
  138.             list1.append((str(raw_input('Which port will you be embarking from? (c)herbourg,(q)ueenstown or (s)outhampton? >'))).upper())
  139.             print "-"*44,"\n"
  140.             a = mdclassify(list1,tree)
  141.             print "When the Titanic sank..."
  142.             for a1 in a: print a[a1],"people like you",a1
  143.         except:
  144.             print "-"*44,"\n"
  145.             print "Try inputting the data properly"
  146.  
  147.         print "\n","-"*44
  148.         moar=str(raw_input('Enter q to QUIT or anything else to see if somebody else survived >'))
  149.         if moar=='q': break
  150.  
  151.  
  152. if __name__ == "__main__":
  153.     my_data=md.my_data
  154.     tree = buildtree(my_data)
  155.     am_i_survive(my_data,tree)
Advertisement
Add Comment
Please, Sign In to add comment