fork(1) download
  1.  
  2.  
  3. #and
  4. #print ("and")
  5. #t_s = [((1, 0, 0), 0), ((1, 0, 1), 0), ((1, 1, 0), 0), ((1, 1, 1), 1)]
  6.  
  7. #or
  8. #print ("or")
  9. #t_s = [((1, 0, 0), 0), ((1, 0, 1), 1), ((1, 1, 0), 1), ((1, 1, 1), 1)]
  10.  
  11. #nand
  12. #print ("nand")
  13. #t_s = [((1, 0, 0), 1), ((1, 0, 1), 1), ((1, 1, 0), 1), ((1, 1, 1), 0)]
  14.  
  15. #xor
  16. print ("xor")
  17. t_s = [((1, 1, 1), 0), ((1, 0, 1), 1), ((1, 1, 0), 1), ((1, 1, 1), 0)]
  18.  
  19.  
  20. threshold = 0.5
  21. learning_rate = 0.1
  22. w = [0, 0, 0]
  23.  
  24. def dot_product(values, weights):
  25. return sum(value * weight for value, weight in zip(values, weights))
  26.  
  27. def train_perceptron(threshold, learning_rate, weights, training_set):
  28. while True:
  29. #print('-' * 60)
  30. error_count = 0
  31.  
  32. for input_vector, desired_output in training_set:
  33. #print(weights)
  34. result = dot_product(input_vector, weights) > threshold
  35. error = desired_output - result
  36.  
  37. if error != 0:
  38. error_count += 1
  39. for index, value in enumerate(input_vector):
  40. weights[index] += learning_rate * error * value
  41.  
  42. if error_count == 0: #iterate till there's no error
  43. break
  44. return training_set
  45.  
  46. t_s = train_perceptron(threshold, learning_rate, w, t_s)
  47.  
  48. t_s = [(a[1:], b) for a, b in t_s]
  49.  
  50. for a, b in t_s:
  51. print "input: " + str(a) + ", output: " + str(b)
  52.  
  53.  
Success #stdin #stdout 0.01s 7896KB
stdin
Standard input is empty
stdout
xor
input: (1, 1), output: 0
input: (0, 1), output: 1
input: (1, 0), output: 1
input: (1, 1), output: 0