<s> import sys <EOL> import numpy as np <EOL> import lxmls . classifiers . linear_classifier as lc <EOL> class Perceptron ( lc . LinearClassifier ) : <EOL> def __init__ ( self , nr_epochs = <NUM_LIT:10> , learning_rate = <NUM_LIT:1> , averaged = True ) : <EOL> lc . LinearClassifier . __init__ ( self ) <EOL> self . trained = False <EOL> self . nr_epochs = nr_epochs <EOL> self . learning_rate = learning_rate <EOL> self . averaged = averaged <EOL> self . params_per_round = [ ] <EOL> def train ( self , x , y , seed = <NUM_LIT:1> ) : <EOL> self . params_per_round = [ ] <EOL> x_orig = x [ : , : ] <EOL> x = self . add_intercept_term ( x ) <EOL> nr_x , nr_f = x . shape <EOL> nr_c = np . unique ( y ) . shape [ <NUM_LIT:0> ] <EOL> w = np . zeros ( ( nr_f , nr_c ) ) <EOL> for epoch_nr in xrange ( self . nr_epochs ) : <EOL> np . random . seed ( seed ) <EOL> perm = np . random . permutation ( nr_x ) <EOL> seed = seed + <NUM_LIT:1> <EOL> for nr in xrange ( nr_x ) : <EOL> inst = perm [ nr ] <EOL> y_hat = self . get_label ( x [ inst : inst + <NUM_LIT:1> , : ] , w ) <EOL> if ( y [ inst : inst + <NUM_LIT:1> , <NUM_LIT:0> ] != y_hat ) : <EOL> w [ : , y [ inst : inst + <NUM_LIT:1> , <NUM_LIT:0> ] ] += self . learning_rate * x [ inst : inst + <NUM_LIT:1> , : ] . transpose ( ) <EOL> w [ : , y_hat ] += - <NUM_LIT:1> * self . learning_rate * x [ inst : inst + <NUM_LIT:1> , : ] . transpose ( ) <EOL> self . params_per_round . append ( w . copy ( ) ) <EOL> self . trained = True <EOL> y_pred = self . test ( x_orig , w ) <EOL> acc = self . evaluate ( y , y_pred ) <EOL> self . trained = False <EOL> print "<STR_LIT>" % ( epoch_nr , acc ) <EOL> self . trained = True <EOL> if ( self . averaged == True ) : <EOL> new_w = <NUM_LIT:0> <EOL> for old_w in self . params_per_round : <EOL> new_w += old_w <EOL> new_w = new_w / len ( self . params_per_round ) <EOL> return new_w <EOL> return w </s>
