Demo entry 6345700

XOR

   

Submitted by anonymous on Feb 02, 2017 at 20:15
Language: Python. Code size: 709 Bytes.

from operator import add

# Original XOR points
x = [ [0,0], [0,1], [1,0], [1,1] ]
y = [ -1,  1, 1, -1 ]
w = [0, 0, 0, 0]

# Remapping to new feature space with (x_0)(x_1) and 1-(x_0)(x_1)
x = [ [x[0], x[1], x[0]*x[1], 1-x[0]*x[1]] for x in x ]

# Prediction function
def predict(x_i, w):
  total = sum([x_*w_ for (x_, w_) in zip(x_i ,w)])
  return 1 if total > 0 else -1

# Learning
while True:
  cost = 0
  for i in range(len(x)):
    y_ = predict(x[i], w) 
    # Cost is total number of wrong examples
    # Adding y * x_i to w if misclassified
    if y_ <> y[i]:
      cost += 1
      w = map(add, w, [y[i] * x_i for x_i in x[i]])
  if cost == 0:
    break

print('XOR solved')

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).