Advertisement
deko96

Lab 2 Zadaca 1

Nov 5th, 2016
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.31 KB | None | 0 0
  1. trainingData=[['slashdot','USA','yes',18,'None'],
  2.         ['google','France','yes',23,'Premium'],
  3.         ['google','France','yes',23,'Basic'],
  4.         ['google','France','yes',23,'Basic'],
  5.         ['digg','USA','yes',24,'Basic'],
  6.         ['kiwitobes','France','yes',23,'Basic'],
  7.         ['google','UK','no',21,'Premium'],
  8.         ['(direct)','New Zealand','no',12,'None'],
  9.         ['(direct)','UK','no',21,'Basic'],
  10.         ['google','USA','no',24,'Premium'],
  11.         ['slashdot','France','yes',19,'None'],
  12.         ['digg','USA','no',18,'None'],
  13.         ['google','UK','no',18,'None'],
  14.         ['kiwitobes','UK','no',19,'None'],
  15.         ['digg','New Zealand','yes',12,'Basic'],
  16.         ['slashdot','UK','no',21,'None'],
  17.         ['google','UK','yes',18,'Basic'],
  18.         ['kiwitobes','France','yes',19,'Basic']]
  19.  
  20. class decisionnode:
  21.       def __init__(self,col=-1,value=None,results=None,tb=None,fb=None, level = 0):
  22.          self.col=col
  23.          self.value=value
  24.          self.results=results
  25.          self.tb=tb
  26.          self.fb=fb
  27.          self.level = level
  28.  
  29. def sporedi_broj(row,column,value):
  30.   return row[column]>=value
  31.  
  32. def sporedi_string(row,column,value):
  33.   return row[column]==value
  34.  
  35. # Divides a set on a specific column. Can handle numeric
  36. # or nominal values
  37. def divideset(rows,column,value):
  38.     # Make a function that tells us if a row is in
  39.     # the first group (true) or the second group (false)
  40.     split_function=None
  41.     if isinstance(value,int) or isinstance(value,float): # ako vrednosta so koja sporeduvame e od tip int ili float
  42.        #split_function=lambda row:row[column]>=value # togas vrati funkcija cij argument e row i vrakja vrednost true ili false
  43.        split_function=sporedi_broj
  44.     else:
  45.        # split_function=lambda row:row[column]==value # ako vrednosta so koja sporeduvame e od drug tip (string)
  46.        split_function=sporedi_string
  47.  
  48.     # Divide the rows into two sets and return them
  49.     # set1=[row for row in rows if split_function(row)]  # za sekoj row od rows za koj split_function vrakja true
  50.     # set2=[row for row in rows if not split_function(row)] # za sekoj row od rows za koj split_function vrakja false
  51.     set1=[row for row in rows if split_function(row,column,value)]  # za sekoj row od rows za koj split_function vrakja true
  52.     set2=[row for row in rows if not split_function(row,column,value)] # za sekoj row od rows za koj split_function vrakja false
  53.     return (set1,set2)
  54.  
  55. # Create counts of possible results (the last column of
  56. # each row is the result)
  57. def uniquecounts(rows):
  58.   results={}
  59.   for row in rows:
  60.      # The result is the last column
  61.      r=row[len(row)-1]
  62.      if r not in results: results[r]=0
  63.      results[r]+=1
  64.   return results
  65.  
  66. # Probability that a randomly placed item will
  67. # be in the wrong category
  68. def giniimpurity(rows):
  69.       total=len(rows)
  70.       counts=uniquecounts(rows)
  71.       imp=0
  72.       for k1 in counts:
  73.             p1=float(counts[k1])/total
  74.             for k2 in counts:
  75.                   if k1==k2: continue
  76.                   p2=float(counts[k2])/total
  77.                   imp+=p1*p2
  78.                   print(imp)
  79.       return imp
  80.  
  81.  
  82. # Entropy is the sum of p(x)log(p(x)) across all
  83. # the different possible results
  84. def entropy(rows):
  85.       from math import log
  86.       log2=lambda x:log(x)/log(2)
  87.       results=uniquecounts(rows)
  88.       # Now calculate the entropy
  89.       ent=0.0
  90.       for r in results.keys():
  91.             p=float(results[r])/len(rows)
  92.             ent=ent-p*log2(p)
  93.       return ent
  94.  
  95. def buildtree(rows,scoref=entropy, level=0):
  96.       if len(rows)==0: return decisionnode()
  97.       current_score=scoref(rows)
  98.  
  99.       # Set up some variables to track the best criteria
  100.       best_gain=0.0
  101.       best_criteria=None
  102.       best_sets=None
  103.      
  104.       column_count=len(rows[0])-1
  105.       for col in range(0,column_count):
  106.             # Generate the list of different values in
  107.             # this column
  108.             column_values={}
  109.             for row in rows:
  110.                   column_values[row[col]]=1
  111.             # Now try dividing the rows up for each value
  112.             # in this column
  113.             for value in column_values.keys():
  114.                   (set1,set2)=divideset(rows,col,value)
  115.                  
  116.                   # Information gain
  117.                   p=float(len(set1))/len(rows)
  118.                   gain=current_score-p*scoref(set1)-(1-p)*scoref(set2)
  119.                   if gain>best_gain and len(set1)>0 and len(set2)>0:
  120.                         best_gain=gain
  121.                         best_criteria=(col,value)
  122.                         best_sets=(set1,set2)
  123.      
  124.       # Create the subbranches
  125.       if best_gain>0:
  126.             trueBranch=buildtree(best_sets[0], level=level+1)
  127.             falseBranch=buildtree(best_sets[1], level=level+1)
  128.             return decisionnode(col=best_criteria[0],value=best_criteria[1],
  129.                             tb=trueBranch, fb=falseBranch, level=level)
  130.       else:
  131.             return decisionnode(results=uniquecounts(rows))
  132.  
  133. def printtree(tree,indent=''):
  134.       # Is this a leaf node?
  135.       if tree.results!=None:
  136.             print str(tree.results)
  137.       else:
  138.             # Print the criteria
  139.             print str(tree.col)+':'+str(tree.value)+'? ' + 'Level=' + str(tree.level)
  140.             # Print the branches
  141.             print indent+'T->',
  142.             printtree(tree.tb,indent+'  ')
  143.             print indent+'F->',
  144.             printtree(tree.fb,indent+'  ')
  145.  
  146.  
  147. def classify(observation,tree):
  148.     if tree.results!=None:
  149.         return tree.results
  150.     else:
  151.         vrednost=observation[tree.col]
  152.         branch=None
  153.  
  154.         if isinstance(vrednost,int) or isinstance(vrednost,float):
  155.             if vrednost>=tree.value: branch=tree.tb
  156.             else: branch=tree.fb
  157.         else:
  158.            if vrednost==tree.value: branch=tree.tb
  159.            else: branch=tree.fb
  160.  
  161.         return classify(observation,branch)
  162.  
  163. if __name__ == "__main__":
  164.     # referrer='slashdot'
  165.     # location='US'
  166.     # readFAQ='no'
  167.     # pagesVisited=19
  168.     # serviceChosen='None'
  169.  
  170.     referrer=input()
  171.     location=input()
  172.     readFAQ=input()
  173.     pagesVisited=input()
  174.     serviceChosen=input()
  175.  
  176.     testCase=[referrer, location, readFAQ, pagesVisited, serviceChosen]
  177.     trainingData.append(testCase)
  178.     t=buildtree(trainingData)
  179.     printtree(t)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement