Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def sgn(x):
  4.     return np.where( x > 0 , 1 , -1 )
  5.  
  6. def theta(s):
  7.     return 1 / ( 1 + np.exp( -s ) )
  8.  
  9. content_train = open( 'hw3_train.dat', 'r' ).read().strip()
  10. content_test = open( 'hw3_test.dat', 'r' ).read().strip()
  11.  
  12. x_train = np.array( [ [1] + [ float(x) for x in line.split()[:-1] ] for line in content_train.split('\n') ] )
  13. y_train = np.array( [ int(line.split()[-1]) for line in content_train.split('\n') ] )
  14. x_test = np.array( [ [1] + [ float(x) for x in line.split()[:-1] ] for line in content_test.split('\n') ] )
  15. y_test = np.array( [ int(line.split()[-1]) for line in content_test.split('\n') ] )
  16.  
  17. N_train = len(y_train)
  18. N_test = len(y_test)
  19. T = 2000
  20. Eta = 0.001
  21.  
  22. w = np.zeros( len( x_train[0] ) )
  23. for _ in range(T):
  24.     grad = np.sum( ( theta( y_train * np.dot( x_train, w ) ) * -y_train ).reshape((N_train, 1)) * x_train, axis=0 ) / N_train
  25.     w = w - Eta * grad
  26.  
  27. Eout_avg = np.sum( np.not_equal( y_test, sgn( np.dot( x_test , w ) ) ) ) / N_test
  28. print(f'Eout_avg = {Eout_avg}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement