Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # type your code here
- import random
- data = [
- [[0,0,1], 0],
- [[0,1,1], 1],
- [[1,0,1], 1],
- [[1,1,1], 1],
- ]
- def get_x(data,index):
- return data[index][0]
- def get_expected(data,index):
- return data[index][1]
- def step(x):
- if x > 0:
- return 1
- else:
- return 0
- def scalar_product(a,b):
- R = 0
- for i in xrange(0,len(a)):
- R += a[i]*b[i]
- return R
- def add_vectors(a,b):
- R = []
- for i in xrange(0,len(a)):
- R = R + [a[i]+b[i]]
- return R
- def scale_vector(scale,a):
- R = []
- for i in xrange(0,len(a)):
- R = R + [a[i]*scale]
- return R
- w = [random.random(),random.random(),random.random()]
- errors = []
- learn_rate = 0.02
- n = 1000
- for i in xrange(n):
- x, expected = random.choice(data)
- result = scalar_product(w, x)
- error = expected - step(result)
- errors.append(error)
- w = add_vectors(w,scale_vector(learn_rate * error, x))
- print "%5s %10s %10s"%("x_n","w_n","output")
- for x,_ in data:
- result = scalar_product(x, w)
- print "%5s %10f %10d "%(x[:2], result, step(result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement