Advertisement
Guest User

Perceptron

a guest
May 28th, 2015
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. # type your code here
  2. import random
  3.  
  4. data = [
  5.     [[0,0,1], 0],
  6.     [[0,1,1], 1],
  7.     [[1,0,1], 1],
  8.     [[1,1,1], 1],
  9. ]
  10.  
  11. def get_x(data,index):
  12.     return data[index][0]
  13.  
  14. def get_expected(data,index):
  15.     return data[index][1]
  16.  
  17. def step(x):
  18.     if x > 0:
  19.         return 1
  20.     else:
  21.         return 0
  22.  
  23. def scalar_product(a,b):
  24.     R = 0
  25.     for i in xrange(0,len(a)):
  26.         R += a[i]*b[i]
  27.     return R
  28.  
  29. def add_vectors(a,b):
  30.     R = []
  31.     for i in xrange(0,len(a)):
  32.         R = R + [a[i]+b[i]]
  33.     return R
  34.          
  35. def scale_vector(scale,a):
  36.     R = []
  37.     for i in xrange(0,len(a)):
  38.         R = R + [a[i]*scale]    
  39.     return R
  40.  
  41. w = [random.random(),random.random(),random.random()]
  42.  
  43. errors = []
  44. learn_rate = 0.02
  45. n = 1000
  46.  
  47. for i in xrange(n):
  48.     x, expected = random.choice(data)
  49.     result = scalar_product(w, x)
  50.     error = expected - step(result)
  51.     errors.append(error)
  52.     w = add_vectors(w,scale_vector(learn_rate * error, x))
  53.  
  54.  
  55. print "%5s %10s %10s"%("x_n","w_n","output")
  56. for x,_ in data:
  57.     result = scalar_product(x, w)
  58.     print "%5s %10f %10d "%(x[:2], result, step(result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement