Ifi6057Perceptron

Allikas: Lambda
class Perceptron:                                                               
 def __init__(self, w=[1], t=0.5):                                             
   self.weights = w                                                            
   self.threshold = t                                                          
                                                                               
 def classify(self, values):                                                   
   s = sum(value * weight for value, weight in                                 
     zip(values, self.weights))                                                
   return s > self.threshold                                                   
                                                                               
 def train(self, trainset, lrate):                                             
   beste = len(trainset) + 1                                                   
   bestv = [ w for w in self.weights ]                                         
   noupdate = 0                                                                
   while noupdate < 1000:                                                      
     errors = 0                                                                
     for vect, val in trainset:                                                
       result = self.classify(vect)                                            
       error = val - result                                                    
       if error != 0:                                                          
         errors += 1                                                           
         for i, v in enumerate(vect):                                          
           self.weights[i] += lrate * error * v                                
     if errors < beste:                                                        
       print (errors,self.weights)                                             
       beste = errors                                                          
       bestv = [ w for w in self.weights ]                                     
       noupdate = 0                                                            
     else:                                                                     
       noupdate += 1                                                           
     if errors == 0:                                                           
       break                                                                   
   print ("Training done with best case: ", beste, bestv)                      
   print ("Current: ", errors, self.weights)                                   
   self.weights = bestv