Mitko_jos

drvo na odluka

Dec 28th, 2014
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.00 KB | None | 0 0
  1. ---Drvo na odluka
  2. zad1
  3.  
  4. trainingData=[['slashdot','USA','yes',18,'None'],
  5.         ['google','France','yes',23,'Premium'],
  6.         ['google','France','yes',23,'Basic'],
  7.         ['google','France','yes',23,'Basic'],
  8.         ['digg','USA','yes',24,'Basic'],
  9.         ['kiwitobes','France','yes',23,'Basic'],
  10.         ['google','UK','no',21,'Premium'],
  11.         ['(direct)','New Zealand','no',12,'None'],
  12.         ['(direct)','UK','no',21,'Basic'],
  13.         ['google','USA','no',24,'Premium'],
  14.         ['slashdot','France','yes',19,'None'],
  15.         ['digg','USA','no',18,'None'],
  16.         ['google','UK','no',18,'None'],
  17.         ['kiwitobes','UK','no',19,'None'],
  18.         ['digg','New Zealand','yes',12,'Basic'],
  19.         ['slashdot','UK','no',21,'None'],
  20.         ['google','UK','yes',18,'Basic'],
  21.         ['kiwitobes','France','yes',19,'Basic']]
  22.  
  23. class decisionnode:
  24.     def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  25.         self.col=col
  26.         self.value=value
  27.         self.results=results
  28.         self.tb=tb
  29.         self.fb=fb
  30. def sporedi_broj(row,column,value):
  31.     return row[column]>=value
  32. def sporedi_string(row,column,value):
  33.     return row[column]==value
  34. def divideset(rows,column,value):
  35.     split_function=None
  36.     if isinstance(value,int) or isinstance(value,float):
  37.         split_function=sporedi_broj
  38.     else:
  39.         split_function=sporedi_string
  40.     set1=[row for row in rows if split_function(row,column,value)]  
  41.     set2=[row for row in rows if not split_function(row,column,value)]
  42.     return (set1,set2)
  43. def uniquecounts(rows):
  44.     results={}
  45.     for row in rows:
  46.         r=row[len(row)-1]
  47.         if r not in results:
  48.             results[r]=0
  49.         results[r]+=1
  50.            
  51.     return results
  52.        
  53. def entropy(rows):
  54.     from math import log
  55.     log2=lambda x:log(x)/log(2)
  56.     results=uniquecounts(rows)
  57.     ent=0.0
  58.     for r in results.keys():
  59.         p=float(results[r])/len(rows)
  60.         ent=ent-p*log2(p)
  61.    
  62.     return ent
  63.        
  64. def buildtree(rows,scoref=entropy):
  65.     if len(rows)==0: return decisionnode()
  66.     current_score=scoref(rows)
  67.    
  68.     best_gain=0.0
  69.     best_criteria=None
  70.     best_sets=None
  71.      
  72.     column_count=len(rows[0])-1
  73.     for col in range(0,column_count):
  74.         column_values={}
  75.         for row in rows:
  76.             column_values[row[col]]=1
  77.            
  78.         for value in column_values.keys():
  79.             (set1,set2)=divideset(rows,col,value)
  80.          
  81.             p=float(len(set1))/len(rows)
  82.             gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  83.             if gain>best_gain and len(set1)>0 and len(set2)>0:
  84.                 best_gain=gain
  85.                 best_criteria=(col,value)
  86.                 best_sets=(set1,set2)
  87.      
  88.     if best_gain>0:
  89.         trueBranch=buildtree(best_sets[0])
  90.         falseBranch=buildtree(best_sets[1])
  91.         return decisionnode(col=best_criteria[0],value=best_criteria[1],tb=trueBranch, fb=falseBranch)
  92.     else:
  93.         return decisionnode(results=uniquecounts(rows))
  94.        
  95.        
  96. def printtree(tree,indent='',br=0):
  97.     if tree.results!=None:
  98.         print str(tree.results)
  99.     else:
  100.         print str(tree.col)+':'+str(tree.value)+'? '+'Level='+str(br)
  101.         print indent+'T->',
  102.         printtree(tree.tb,indent+'  ',br+1)
  103.         print indent+'F->',
  104.         printtree(tree.fb,indent+'  ',br+1)  
  105.          
  106. #if __name__ == "__main__":
  107.     # referrer='slashdot'
  108.     # location='US'
  109.     # readFAQ='no'
  110.     # pagesVisited=19
  111.     # serviceChosen='None'
  112.  
  113. referrer=input()
  114. location=input()
  115. readFAQ=input()
  116. pagesVisited=input()
  117. serviceChosen=input()
  118. testCase=[referrer, location, readFAQ, pagesVisited, serviceChosen]
  119. trainingData.append(testCase)
  120. t=buildtree(trainingData)
  121. printtree(t,br=0)
  122.  
  123. Zad2
  124.  
  125. trainingData=[['slashdot','USA','yes',18,'None'],
  126.         ['google','France','yes',23,'Premium'],
  127.         ['google','France','yes',23,'Basic'],
  128.         ['google','France','yes',23,'Basic'],
  129.         ['digg','USA','yes',24,'Basic'],
  130.         ['kiwitobes','France','yes',23,'Basic'],
  131.         ['google','UK','no',21,'Premium'],
  132.         ['(direct)','New Zealand','no',12,'None'],
  133.         ['(direct)','UK','no',21,'Basic'],
  134.         ['google','USA','no',24,'Premium'],
  135.         ['slashdot','France','yes',19,'None'],
  136.         ['digg','USA','no',18,'None'],
  137.         ['google','UK','no',18,'None'],
  138.         ['kiwitobes','UK','no',19,'None'],
  139.         ['digg','New Zealand','yes',12,'Basic'],
  140.         ['slashdot','UK','no',21,'None'],
  141.         ['google','UK','yes',18,'Basic'],
  142.         ['kiwitobes','France','yes',19,'Basic']]
  143.  
  144. class decisionnode:
  145.       def __init__(self,col=-1,value=None,results=None,tb=None,fb=None):
  146.          self.col=col
  147.          self.value=value
  148.          self.results=results
  149.          self.tb=tb
  150.          self.fb=fb
  151. def sporedi_broj(row,column,value):
  152.   return row[column]>=value
  153. def sporedi_string(row,column,value):
  154.   return row[column]==value
  155. # Divides a set on a specific column. Can handle numeric
  156. # or nominal values
  157. def divideset(rows,column,value):
  158.     # Make a function that tells us if a row is in
  159.     # the first group (true) or the second group (false)
  160.     split_function=None
  161.     if isinstance(value,int) or isinstance(value,float): # ako vrednosta so koja sporeduvame e od tip int ili float
  162.        #split_function=lambda row:row[column]>=value # togas vrati funkcija cij argument e row i vrakja vrednost true ili false
  163.        split_function=sporedi_broj
  164.     else:
  165.        # split_function=lambda row:row[column]==value # ako vrednosta so koja sporeduvame e od drug tip (string)
  166.        split_function=sporedi_string
  167.     # Divide the rows into two sets and return them
  168.     # set1=[row for row in rows if split_function(row)]  # za sekoj row od rows za koj split_function vrakja true
  169.     # set2=[row for row in rows if not split_function(row)] # za sekoj row od rows za koj split_function vrakja false
  170.     set1=[row for row in rows if split_function(row,column,value)]  # za sekoj row od rows za koj split_function vrakja true
  171.     set2=[row for row in rows if not split_function(row,column,value)] # za sekoj row od rows za koj split_function vrakja false
  172.     return (set1,set2)
  173. # Create counts of possible results (the last column of
  174. # each row is the result)
  175. def uniquecounts(rows):
  176.   results={}
  177.   for row in rows:
  178.      # The result is the last column
  179.      r=row[len(row)-1]
  180.      if r not in results: results[r]=0
  181.      results[r]+=1
  182.   return results
  183. # Probability that a randomly placed item will
  184. # be in the wrong category
  185. def giniimpurity(rows):
  186.       total=len(rows)
  187.       counts=uniquecounts(rows)
  188.       imp=0
  189.       for k1 in counts:
  190.             p1=float(counts[k1])/total
  191.             for k2 in counts:
  192.                   if k1==k2: continue
  193.                   p2=float(counts[k2])/total
  194.                   imp+=p1*p2
  195.       return imp
  196. # Entropy is the sum of p(x)log(p(x)) across all
  197. # the different possible results
  198. def entropy(rows):
  199.       from math import log
  200.       log2=lambda x:log(x)/log(2)
  201.       results=uniquecounts(rows)
  202.       # Now calculate the entropy
  203.       ent=0.0
  204.       for r in results.keys():
  205.             p=float(results[r])/len(rows)
  206.             ent=ent-p*log2(p)
  207.       return ent
  208. def buildtree(rows,scoref=entropy):
  209.       if len(rows)==0: return decisionnode()
  210.       current_score=scoref(rows)
  211.       # Set up some variables to track the best criteria
  212.       best_gain=0.0
  213.       best_criteria=None
  214.       best_sets=None
  215.      
  216.       column_count=len(rows[0])-1
  217.       for col in range(0,column_count):
  218.             # Generate the list of different values in
  219.             # this column
  220.             column_values={}
  221.             for row in rows:
  222.                   column_values[row[col]]=1
  223.                   print
  224.             # Now try dividing the rows up for each value
  225.             # in this column
  226.             for value in column_values.keys():
  227.                   (set1,set2)=divideset(rows,col,value)
  228.                  
  229.                   # Information gain
  230.                   p=float(len(set1))/len(rows)
  231.                   gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  232.                   if gain>best_gain and len(set1)>0 and len(set2)>0:
  233.                         best_gain=gain
  234.                         best_criteria=(col,value)
  235.                         best_sets=(set1,set2)
  236.      
  237.       # Create the subbranches
  238.       if best_gain>0:
  239.             trueBranch=buildtree(best_sets[0])
  240.             falseBranch=buildtree(best_sets[1])
  241.             return decisionnode(col=best_criteria[0],value=best_criteria[1],
  242.                             tb=trueBranch, fb=falseBranch)
  243.       else:
  244.             return decisionnode(results=uniquecounts(rows))
  245.        
  246. def printtree(tree,indent=''):
  247.       # Is this a leaf node?
  248.       if tree.results!=None:
  249.             print str(tree.results)
  250.       else:
  251.             # Print the criteria
  252.             print str(tree.col)+':'+str(tree.value)+'? '
  253.             # Print the branches
  254.             print indent+'T->',
  255.             printtree(tree.tb,indent+'  ')
  256.             print indent+'F->',
  257.             printtree(tree.fb,indent+'  ')
  258. def classify(observation,tree):
  259.     if tree.results!=None:
  260.         results=[(value,key) for key,value in tree.results.items()]
  261.         results.sort(reverse=True)
  262.         return results[0][1]
  263.     else:
  264.         vrednost=observation[tree.col]
  265.         branch=None
  266.         if isinstance(vrednost,int) or isinstance(vrednost,float):
  267.             if vrednost>=tree.value: branch=tree.tb
  268.             else: branch=tree.fb
  269.         else:
  270.            if vrednost==tree.value: branch=tree.tb
  271.            else: branch=tree.fb
  272.         return classify(observation,branch)
  273.    
  274. #if __name__ == "__main__":
  275.     # referrer='slashdot'
  276.     # location='UK'
  277.     # readFAQ='no'
  278.     # pagesVisited=21
  279.     # serviceChosen='Unknown'
  280. referrer=input()
  281. location=input()
  282. readFAQ=input()
  283. pagesVisited=input()
  284. serviceChosen=input()
  285. testCase=[referrer, location, readFAQ, pagesVisited, serviceChosen]
  286. t=buildtree(trainingData)
  287. print classify(testCase,t)
Advertisement
Add Comment
Please, Sign In to add comment