Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. import numpy
  2. MAGIC_CONSTANT = 7
  3.  
  4. INPUT_DATA = [
  5. (numpy.matrix([[-1], [ 1], [ 1], [ 1], [ 1], [-1], [ 1], [ 1], [ 1], [ 1], [-1], [ 1], [ 1], [ 1], [ 1], [-1], [ 1], [ 1], [ 1], [ 1], [-1], [-1], [-1], [-1], [-1]]), numpy.matrix([[ 1.],[-1.], [-1.], [-1.]])),#l
  6. (numpy.matrix([[-1], [-1], [-1], [-1], [-1], [-1], [ 1], [-1], [ 1], [-1], [-1], [ 1], [-1], [ 1], [-1], [-1], [ 1], [-1], [ 1], [-1], [-1], [ 1], [-1], [ 1], [-1]]), numpy.matrix([[-1.], [ 1.], [-1.], [-1.]])),#m
  7. (numpy.matrix([[-1], [-1], [-1], [-1], [-1], [-1], [ 1], [ 1], [ 1], [ 1], [-1], [-1], [-1], [-1], [ 1], [-1], [ 1], [ 1], [ 1], [ 1], [-1], [-1], [-1], [-1], [-1]]), numpy.matrix([[-1.], [-1.], [ 1.], [-1.]])),#e
  8. (numpy.matrix([[-1], [ 1], [ 1], [ 1], [-1], [ 1], [-1], [ 1], [-1], [ 1], [ 1], [ 1], [-1], [ 1], [ 1], [ 1], [-1], [ 1], [-1], [ 1], [-1], [ 1], [ 1], [ 1], [-1]]), numpy.matrix([[-1.], [-1.], [-1.], [ 1.]]))]#x
  9.  
  10.  
  11. def add_one_to_input():
  12. def decorator(func):
  13. def inner(*args, **kwargs):
  14. if 'examples' in kwargs:
  15. kwargs['examples'] = [(numpy.insert(input, 0, 1, axis=0), output) for
  16. input, output in kwargs['examples']]
  17. return func(*args, **kwargs)
  18. return inner
  19. return decorator
  20.  
  21.  
  22. def is_correct_weight(input_matrix, output_matrix, weights):
  23. result = (weights.dot(input_matrix) > 0) * 2 - 1
  24. return numpy.array_equal(result, output_matrix)
  25.  
  26.  
  27. @add_one_to_input()
  28. def hebb(examples):
  29. input, output = examples[0]
  30. input_matrix = numpy.concatenate([input for input, _ in examples], axis=1)
  31. output_matrix = numpy.concatenate([output for _, output in examples], axis=1)
  32. weights = numpy.matrix(numpy.zeros(shape=(output.shape[0], input.shape[0])))
  33. id = 0
  34. for _ in range(len(examples)**2 + MAGIC_CONSTANT):
  35. for input, output in examples:
  36. id+=1
  37. if is_correct_weight(input_matrix, output_matrix, weights):
  38. return weights
  39. weights += output * input.T
  40. print("Веса после {0}-й итерации".format(str(id)))
  41. correct_print_weights(weights)
  42.  
  43.  
  44. def correct_print_weights(weigts):
  45. for i, row in enumerate(weigts):
  46. print("Значение для выхода {}".format(str(i+1)))
  47. print(' '.join([str(e) for e in row.tolist()]))
  48.  
  49.  
  50.  
  51. w = hebb(examples=INPUT_DATA)
  52.  
  53. print("Ответ")
  54. correct_print_weights(w)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement